blob: 0e513992ba5ed786aa1f7bd950a9920da051866a [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redl2b916b82012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +000095 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000096 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000097 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ConstVal,
99 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000100 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Eli Friedman8718a6a2009-05-29 18:22:49 +0000103 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000105 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000106 // the size may be smaller or larger than the string we are initializing.
107 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000108 if (S.getLangOpts().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000109 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
110 // For Pascal strings it's OK to strip off the terminating null character,
111 // so the example below is valid:
112 //
113 // unsigned char a[2] = "\pa";
114 if (SL->isPascal())
115 StrLength--;
116 }
117
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000118 // [dcl.init.string]p2
119 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000120 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000121 diag::err_initializer_string_for_char_array_too_long)
122 << Str->getSourceRange();
123 } else {
124 // C99 6.7.8p14.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000126 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
129 }
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Eli Friedman8718a6a2009-05-29 18:22:49 +0000131 // Set the type to the actual size that we are initializing. If we have
132 // something like:
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
135 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000136}
137
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000138//===----------------------------------------------------------------------===//
139// Semantic checking for initializer lists.
140//===----------------------------------------------------------------------===//
141
Douglas Gregor9e80f722009-01-29 01:05:33 +0000142/// @brief Semantic checking for initializer lists.
143///
144/// The InitListChecker class contains a set of routines that each
145/// handle the initialization of a certain kind of entity, e.g.,
146/// arrays, vectors, struct/union types, scalars, etc. The
147/// InitListChecker itself performs a recursive walk of the subobject
148/// structure of the type to be initialized, while stepping through
149/// the initializer list one element at a time. The IList and Index
150/// parameters to each of the Check* routines contain the active
151/// (syntactic) initializer list and the index into that initializer
152/// list that represents the current initializer. Each routine is
153/// responsible for moving that Index forward as it consumes elements.
154///
155/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000156/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157/// initializer list and the index into that initializer list where we
158/// are copying initializers as we map them over to the semantic
159/// list. Once we have completed our recursive walk of the subobject
160/// structure, we will have constructed a full semantic initializer
161/// list.
162///
163/// C99 designators cause changes in the initializer list traversal,
164/// because they make the initialization "jump" into a specific
165/// subobject and then continue the initialization from that
166/// point. CheckDesignatedInitializer() recursively steps into the
167/// designated subobject and manages backing out the recursion to
168/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000169namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000170class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000171 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000172 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000173 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000174 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000175 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000176 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000178 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000179 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000180 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000181 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000182 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000183 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000199 void CheckComplexType(const InitializedEntity &Entity,
200 InitListExpr *IList, QualType DeclType,
201 unsigned &Index,
202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000204 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000205 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000206 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckReferenceType(const InitializedEntity &Entity,
210 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000211 unsigned &Index,
212 InitListExpr *StructuredList,
213 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000214 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000215 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000218 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000219 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000220 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000221 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000222 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000223 unsigned &StructuredIndex,
224 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000225 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000226 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000227 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000228 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000231 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000232 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000233 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000234 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000235 RecordDecl::field_iterator *NextField,
236 llvm::APSInt *NextElementIndex,
237 unsigned &Index,
238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000240 bool FinishSubobjectInit,
241 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
243 QualType CurrentObjectType,
244 InitListExpr *StructuredList,
245 unsigned StructuredIndex,
246 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000247 void UpdateStructuredListElement(InitListExpr *StructuredList,
248 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000249 Expr *expr);
250 int numArrayElements(QualType DeclType);
251 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000256 void FillInValueInitializations(const InitializedEntity &Entity,
257 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000258 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
259 Expr *InitExpr, FieldDecl *Field,
260 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000261 void CheckValueInitializable(const InitializedEntity &Entity);
262
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000263public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000264 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000265 InitListExpr *IL, QualType &T, bool VerifyOnly,
266 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000267 bool HadError() { return hadError; }
268
269 // @brief Retrieves the fully-structured initializer list used for
270 // semantic analysis and code generation.
271 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
272};
Chris Lattner8b419b92009-02-24 22:48:58 +0000273} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000274
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000275void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
276 assert(VerifyOnly &&
277 "CheckValueInitializable is only inteded for verification mode.");
278
279 SourceLocation Loc;
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
283 if (InitSeq.Failed())
284 hadError = true;
285}
286
Douglas Gregord6d37de2009-12-22 00:05:34 +0000287void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000289 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000291 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000292 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000294 = InitializedEntity::InitializeMember(Field, &ParentEntity);
295 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000296 // If there's no explicit initializer but we have a default initializer, use
297 // that. This only happens in C++1y, since classes with default
298 // initializers are not aggregates in C++11.
299 if (Field->hasInClassInitializer()) {
300 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
301 ILE->getRBraceLoc(), Field);
302 if (Init < NumInits)
303 ILE->setInit(Init, DIE);
304 else {
305 ILE->updateInit(SemaRef.Context, Init, DIE);
306 RequiresSecondPass = true;
307 }
308 return;
309 }
310
Douglas Gregord6d37de2009-12-22 00:05:34 +0000311 // FIXME: We probably don't need to handle references
312 // specially here, since value-initialization of references is
313 // handled in InitializationSequence.
314 if (Field->getType()->isReferenceType()) {
315 // C++ [dcl.init.aggr]p9:
316 // If an incomplete or empty initializer-list leaves a
317 // member of reference type uninitialized, the program is
318 // ill-formed.
319 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
320 << Field->getType()
321 << ILE->getSyntacticForm()->getSourceRange();
322 SemaRef.Diag(Field->getLocation(),
323 diag::note_uninit_reference_member);
324 hadError = true;
325 return;
326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327
Douglas Gregord6d37de2009-12-22 00:05:34 +0000328 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
329 true);
330 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
331 if (!InitSeq) {
332 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
333 hadError = true;
334 return;
335 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000336
John McCall60d7b3a2010-08-24 06:29:42 +0000337 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000338 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000339 if (MemberInit.isInvalid()) {
340 hadError = true;
341 return;
342 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343
Douglas Gregord6d37de2009-12-22 00:05:34 +0000344 if (hadError) {
345 // Do nothing
346 } else if (Init < NumInits) {
347 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000348 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000349 // Value-initialization requires a constructor call, so
350 // extend the initializer list to include the constructor
351 // call and make a note that we'll need to take another pass
352 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000353 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000354 RequiresSecondPass = true;
355 }
356 } else if (InitListExpr *InnerILE
357 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358 FillInValueInitializations(MemberEntity, InnerILE,
359 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000360}
361
Douglas Gregor4c678342009-01-28 21:54:33 +0000362/// Recursively replaces NULL values within the given initializer list
363/// with expressions that perform value-initialization of the
364/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000365void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000366InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
367 InitListExpr *ILE,
368 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000369 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000370 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000371 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000373 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Ted Kremenek6217b802009-07-29 21:53:49 +0000375 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000376 const RecordDecl *RDecl = RType->getDecl();
377 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000378 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
379 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000380 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
381 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
382 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
383 FieldEnd = RDecl->field_end();
384 Field != FieldEnd; ++Field) {
385 if (Field->hasInClassInitializer()) {
386 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
387 break;
388 }
389 }
390 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000391 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000392 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
393 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000394 Field != FieldEnd; ++Field) {
395 if (Field->isUnnamedBitfield())
396 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000397
Douglas Gregord6d37de2009-12-22 00:05:34 +0000398 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000400
David Blaikie581deb32012-06-06 20:45:41 +0000401 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000402 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000404
Douglas Gregord6d37de2009-12-22 00:05:34 +0000405 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000406
Douglas Gregord6d37de2009-12-22 00:05:34 +0000407 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000408 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000409 break;
410 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000411 }
412
413 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000414 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000415
416 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000419 unsigned NumInits = ILE->getNumInits();
420 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000421 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000422 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000423 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
424 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000425 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000426 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000427 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000428 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000429 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000430 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000431 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000432 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000433 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000434
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000435
Douglas Gregor87fd7032009-02-02 17:43:21 +0000436 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000437 if (hadError)
438 return;
439
Anders Carlssond3d824d2010-01-23 04:34:47 +0000440 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
441 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000442 ElementEntity.setElementIndex(Init);
443
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000444 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
445 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000446 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
447 true);
448 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
449 if (!InitSeq) {
450 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000451 hadError = true;
452 return;
453 }
454
John McCall60d7b3a2010-08-24 06:29:42 +0000455 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000456 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000457 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000458 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000459 return;
460 }
461
462 if (hadError) {
463 // Do nothing
464 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000465 // For arrays, just set the expression used for value-initialization
466 // of the "holes" in the array.
467 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
468 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
469 else
470 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000471 } else {
472 // For arrays, just set the expression used for value-initialization
473 // of the rest of elements and exit.
474 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
475 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
476 return;
477 }
478
Sebastian Redl7491c492011-06-05 13:59:11 +0000479 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000480 // Value-initialization requires a constructor call, so
481 // extend the initializer list to include the constructor
482 // call and make a note that we'll need to take another pass
483 // through the initializer list.
484 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
485 RequiresSecondPass = true;
486 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000487 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000488 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000489 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000490 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000491 }
492}
493
Chris Lattner68355a52009-01-29 05:10:57 +0000494
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000495InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000496 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000497 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000498 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000499 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000500
Eli Friedmanb85f7072008-05-19 19:16:24 +0000501 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000502 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000503 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000504 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000505 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000506 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000507 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000508
Sebastian Redl14b0c192011-09-24 17:48:00 +0000509 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000510 bool RequiresSecondPass = false;
511 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000512 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000513 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000514 RequiresSecondPass);
515 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000516}
517
518int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000519 // FIXME: use a proper constant
520 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000521 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000522 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000523 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
524 }
525 return maxElements;
526}
527
528int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000529 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000530 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000531 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000532 Field = structDecl->field_begin(),
533 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000534 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000535 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000536 ++InitializableMembers;
537 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000538 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000539 return std::min(InitializableMembers, 1);
540 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000541}
542
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000543void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000544 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000545 QualType T, unsigned &Index,
546 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000547 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000548 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Steve Naroff0cca7492008-05-01 22:18:59 +0000550 if (T->isArrayType())
551 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000552 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000553 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000554 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000555 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000556 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000557 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000558
Eli Friedman402256f2008-05-25 13:49:22 +0000559 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000560 if (!VerifyOnly)
561 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
562 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000563 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000564 hadError = true;
565 return;
566 }
567
Douglas Gregor4c678342009-01-28 21:54:33 +0000568 // Build a structured initializer list corresponding to this subobject.
569 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000570 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
571 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000572 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000573 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000574 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000575
Douglas Gregor4c678342009-01-28 21:54:33 +0000576 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000577 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000579 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000580 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000581 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000582
583 if (VerifyOnly) {
584 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
585 hadError = true;
586 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000587 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000588
Sebastian Redlc2235182011-10-16 18:19:28 +0000589 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000590 // Update the structured sub-object initializer so that it's ending
591 // range corresponds with the end of the last initializer it used.
592 if (EndIndex < ParentIList->getNumInits()) {
593 SourceLocation EndLoc
594 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
595 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
596 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597
Sebastian Redlc2235182011-10-16 18:19:28 +0000598 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000599 if (T->isArrayType() || T->isRecordType()) {
600 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000601 AllowBraceElision ? diag::warn_missing_braces :
602 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000603 << StructuredSubobjectInitList->getSourceRange()
604 << FixItHint::CreateInsertion(
605 StructuredSubobjectInitList->getLocStart(), "{")
606 << FixItHint::CreateInsertion(
607 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000608 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000609 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000610 if (!AllowBraceElision)
611 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000612 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000613 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000614}
615
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000616void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000617 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000618 unsigned &Index,
619 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000620 unsigned &StructuredIndex,
621 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000622 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000623 if (!VerifyOnly) {
624 SyntacticToSemantic[IList] = StructuredList;
625 StructuredList->setSyntacticForm(IList);
626 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000627 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000628 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000629 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000630 QualType ExprTy = T;
631 if (!ExprTy->isArrayType())
632 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000633 IList->setType(ExprTy);
634 StructuredList->setType(ExprTy);
635 }
Eli Friedman638e1442008-05-25 13:22:35 +0000636 if (hadError)
637 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000638
Eli Friedman638e1442008-05-25 13:22:35 +0000639 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000640 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000641 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000642 if (SemaRef.getLangOpts().CPlusPlus ||
643 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000644 IList->getType()->isVectorType())) {
645 hadError = true;
646 }
647 return;
648 }
649
Eli Friedmane5408582009-05-29 20:20:05 +0000650 if (StructuredIndex == 1 &&
651 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000652 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000653 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000654 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000655 hadError = true;
656 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000657 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000658 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000659 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000660 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000661 // Don't complain for incomplete types, since we'll get an error
662 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000663 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000664 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000665 CurrentObjectType->isArrayType()? 0 :
666 CurrentObjectType->isVectorType()? 1 :
667 CurrentObjectType->isScalarType()? 2 :
668 CurrentObjectType->isUnionType()? 3 :
669 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000670
671 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000672 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000673 DK = diag::err_excess_initializers;
674 hadError = true;
675 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000676 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000677 DK = diag::err_excess_initializers;
678 hadError = true;
679 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000680
Chris Lattner08202542009-02-24 22:50:46 +0000681 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000682 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000683 }
684 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000685
Sebastian Redl14b0c192011-09-24 17:48:00 +0000686 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
687 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000688 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000689 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000690 << FixItHint::CreateRemoval(IList->getLocStart())
691 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000692}
693
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000694void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000695 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000696 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000697 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000698 unsigned &Index,
699 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000700 unsigned &StructuredIndex,
701 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000702 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
703 // Explicitly braced initializer for complex type can be real+imaginary
704 // parts.
705 CheckComplexType(Entity, IList, DeclType, Index,
706 StructuredList, StructuredIndex);
707 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000708 CheckScalarType(Entity, IList, DeclType, Index,
709 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000710 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000711 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000712 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000713 } else if (DeclType->isRecordType()) {
714 assert(DeclType->isAggregateType() &&
715 "non-aggregate records should be handed in CheckSubElementType");
716 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
717 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
718 SubobjectIsDesignatorContext, Index,
719 StructuredList, StructuredIndex,
720 TopLevelObject);
721 } else if (DeclType->isArrayType()) {
722 llvm::APSInt Zero(
723 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
724 false);
725 CheckArrayType(Entity, IList, DeclType, Zero,
726 SubobjectIsDesignatorContext, Index,
727 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000728 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
729 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000730 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000731 if (!VerifyOnly)
732 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
733 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000734 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000735 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000736 CheckReferenceType(Entity, IList, DeclType, Index,
737 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000738 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000739 if (!VerifyOnly)
740 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
741 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000742 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000743 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000744 if (!VerifyOnly)
745 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
746 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000747 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000748 }
749}
750
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000751void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000752 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000753 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000754 unsigned &Index,
755 InitListExpr *StructuredList,
756 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000757 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000758 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000759 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
760 unsigned newIndex = 0;
761 unsigned newStructuredIndex = 0;
762 InitListExpr *newStructuredList
763 = getStructuredSubobjectInit(IList, Index, ElemType,
764 StructuredList, StructuredIndex,
765 SubInitList->getSourceRange());
766 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
767 newStructuredList, newStructuredIndex);
768 ++StructuredIndex;
769 ++Index;
770 return;
771 }
772 assert(SemaRef.getLangOpts().CPlusPlus &&
773 "non-aggregate records are only possible in C++");
774 // C++ initialization is handled later.
775 }
776
777 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000778 return CheckScalarType(Entity, IList, ElemType, Index,
779 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000780 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000781 return CheckReferenceType(Entity, IList, ElemType, Index,
782 StructuredList, StructuredIndex);
783 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000784
John McCallfef8b342011-02-21 07:57:55 +0000785 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
786 // arrayType can be incomplete if we're initializing a flexible
787 // array member. There's nothing we can do with the completed
788 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000789
John McCallfef8b342011-02-21 07:57:55 +0000790 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000791 if (!VerifyOnly) {
792 CheckStringInit(Str, ElemType, arrayType, SemaRef);
793 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
794 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000795 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000796 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000797 }
John McCallfef8b342011-02-21 07:57:55 +0000798
799 // Fall through for subaggregate initialization.
800
David Blaikie4e4d0842012-03-11 07:00:24 +0000801 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000802 // C++ [dcl.init.aggr]p12:
803 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000804 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000805 // an initializer-list. If the initializer can initialize a
806 // member, the member is initialized. [...]
807
808 // FIXME: Better EqualLoc?
809 InitializationKind Kind =
810 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
811 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
812
813 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000814 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000815 ExprResult Result =
816 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
817 if (Result.isInvalid())
818 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000819
Sebastian Redl14b0c192011-09-24 17:48:00 +0000820 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000821 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000822 }
John McCallfef8b342011-02-21 07:57:55 +0000823 ++Index;
824 return;
825 }
826
827 // Fall through for subaggregate initialization
828 } else {
829 // C99 6.7.8p13:
830 //
831 // The initializer for a structure or union object that has
832 // automatic storage duration shall be either an initializer
833 // list as described below, or a single expression that has
834 // compatible structure or union type. In the latter case, the
835 // initial value of the object, including unnamed members, is
836 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000837 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000838 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000839 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
840 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000841 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000842 if (ExprRes.isInvalid())
843 hadError = true;
844 else {
845 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
846 if (ExprRes.isInvalid())
847 hadError = true;
848 }
849 UpdateStructuredListElement(StructuredList, StructuredIndex,
850 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000851 ++Index;
852 return;
853 }
John Wiegley429bb272011-04-08 18:41:53 +0000854 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000855 // Fall through for subaggregate initialization
856 }
857
858 // C++ [dcl.init.aggr]p12:
859 //
860 // [...] Otherwise, if the member is itself a non-empty
861 // subaggregate, brace elision is assumed and the initializer is
862 // considered for the initialization of the first member of
863 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000864 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000865 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000866 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
867 StructuredIndex);
868 ++StructuredIndex;
869 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000870 if (!VerifyOnly) {
871 // We cannot initialize this element, so let
872 // PerformCopyInitialization produce the appropriate diagnostic.
873 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
874 SemaRef.Owned(expr),
875 /*TopLevelOfInitList=*/true);
876 }
John McCallfef8b342011-02-21 07:57:55 +0000877 hadError = true;
878 ++Index;
879 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000880 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000881}
882
Eli Friedman0c706c22011-09-19 23:17:44 +0000883void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
884 InitListExpr *IList, QualType DeclType,
885 unsigned &Index,
886 InitListExpr *StructuredList,
887 unsigned &StructuredIndex) {
888 assert(Index == 0 && "Index in explicit init list must be zero");
889
890 // As an extension, clang supports complex initializers, which initialize
891 // a complex number component-wise. When an explicit initializer list for
892 // a complex number contains two two initializers, this extension kicks in:
893 // it exepcts the initializer list to contain two elements convertible to
894 // the element type of the complex type. The first element initializes
895 // the real part, and the second element intitializes the imaginary part.
896
897 if (IList->getNumInits() != 2)
898 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
899 StructuredIndex);
900
901 // This is an extension in C. (The builtin _Complex type does not exist
902 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000903 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000904 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
905 << IList->getSourceRange();
906
907 // Initialize the complex number.
908 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
909 InitializedEntity ElementEntity =
910 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
911
912 for (unsigned i = 0; i < 2; ++i) {
913 ElementEntity.setElementIndex(Index);
914 CheckSubElementType(ElementEntity, IList, elementType, Index,
915 StructuredList, StructuredIndex);
916 }
917}
918
919
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000920void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000921 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000922 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000923 InitListExpr *StructuredList,
924 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000925 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000926 if (!VerifyOnly)
927 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000928 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000929 diag::warn_cxx98_compat_empty_scalar_initializer :
930 diag::err_empty_scalar_initializer)
931 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000932 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000933 ++Index;
934 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000935 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000936 }
John McCallb934c2d2010-11-11 00:46:36 +0000937
938 Expr *expr = IList->getInit(Index);
939 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000940 if (!VerifyOnly)
941 SemaRef.Diag(SubIList->getLocStart(),
942 diag::warn_many_braces_around_scalar_init)
943 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000944
945 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
946 StructuredIndex);
947 return;
948 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000949 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000950 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000951 diag::err_designator_for_scalar_init)
952 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000953 hadError = true;
954 ++Index;
955 ++StructuredIndex;
956 return;
957 }
958
Sebastian Redl14b0c192011-09-24 17:48:00 +0000959 if (VerifyOnly) {
960 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
961 hadError = true;
962 ++Index;
963 return;
964 }
965
John McCallb934c2d2010-11-11 00:46:36 +0000966 ExprResult Result =
967 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000968 SemaRef.Owned(expr),
969 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000970
971 Expr *ResultExpr = 0;
972
973 if (Result.isInvalid())
974 hadError = true; // types weren't compatible.
975 else {
976 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000977
John McCallb934c2d2010-11-11 00:46:36 +0000978 if (ResultExpr != expr) {
979 // The type was promoted, update initializer list.
980 IList->setInit(Index, ResultExpr);
981 }
982 }
983 if (hadError)
984 ++StructuredIndex;
985 else
986 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
987 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000988}
989
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000990void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
991 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000992 unsigned &Index,
993 InitListExpr *StructuredList,
994 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000995 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000996 // FIXME: It would be wonderful if we could point at the actual member. In
997 // general, it would be useful to pass location information down the stack,
998 // so that we know the location (or decl) of the "current object" being
999 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001000 if (!VerifyOnly)
1001 SemaRef.Diag(IList->getLocStart(),
1002 diag::err_init_reference_member_uninitialized)
1003 << DeclType
1004 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001005 hadError = true;
1006 ++Index;
1007 ++StructuredIndex;
1008 return;
1009 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001010
1011 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001012 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001013 if (!VerifyOnly)
1014 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1015 << DeclType << IList->getSourceRange();
1016 hadError = true;
1017 ++Index;
1018 ++StructuredIndex;
1019 return;
1020 }
1021
1022 if (VerifyOnly) {
1023 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1024 hadError = true;
1025 ++Index;
1026 return;
1027 }
1028
1029 ExprResult Result =
1030 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1031 SemaRef.Owned(expr),
1032 /*TopLevelOfInitList=*/true);
1033
1034 if (Result.isInvalid())
1035 hadError = true;
1036
1037 expr = Result.takeAs<Expr>();
1038 IList->setInit(Index, expr);
1039
1040 if (hadError)
1041 ++StructuredIndex;
1042 else
1043 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1044 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001045}
1046
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001047void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001048 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001049 unsigned &Index,
1050 InitListExpr *StructuredList,
1051 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001052 const VectorType *VT = DeclType->getAs<VectorType>();
1053 unsigned maxElements = VT->getNumElements();
1054 unsigned numEltsInit = 0;
1055 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001056
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001057 if (Index >= IList->getNumInits()) {
1058 // Make sure the element type can be value-initialized.
1059 if (VerifyOnly)
1060 CheckValueInitializable(
1061 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1062 return;
1063 }
1064
David Blaikie4e4d0842012-03-11 07:00:24 +00001065 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001066 // If the initializing element is a vector, try to copy-initialize
1067 // instead of breaking it apart (which is doomed to failure anyway).
1068 Expr *Init = IList->getInit(Index);
1069 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001070 if (VerifyOnly) {
1071 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1072 hadError = true;
1073 ++Index;
1074 return;
1075 }
1076
John McCall20e047a2010-10-30 00:11:39 +00001077 ExprResult Result =
1078 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001079 SemaRef.Owned(Init),
1080 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001081
1082 Expr *ResultExpr = 0;
1083 if (Result.isInvalid())
1084 hadError = true; // types weren't compatible.
1085 else {
1086 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001087
John McCall20e047a2010-10-30 00:11:39 +00001088 if (ResultExpr != Init) {
1089 // The type was promoted, update initializer list.
1090 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001091 }
1092 }
John McCall20e047a2010-10-30 00:11:39 +00001093 if (hadError)
1094 ++StructuredIndex;
1095 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001096 UpdateStructuredListElement(StructuredList, StructuredIndex,
1097 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001098 ++Index;
1099 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001100 }
Mike Stump1eb44332009-09-09 15:08:12 +00001101
John McCall20e047a2010-10-30 00:11:39 +00001102 InitializedEntity ElementEntity =
1103 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001104
John McCall20e047a2010-10-30 00:11:39 +00001105 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1106 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001107 if (Index >= IList->getNumInits()) {
1108 if (VerifyOnly)
1109 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001110 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001111 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001112
John McCall20e047a2010-10-30 00:11:39 +00001113 ElementEntity.setElementIndex(Index);
1114 CheckSubElementType(ElementEntity, IList, elementType, Index,
1115 StructuredList, StructuredIndex);
1116 }
1117 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001118 }
John McCall20e047a2010-10-30 00:11:39 +00001119
1120 InitializedEntity ElementEntity =
1121 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001122
John McCall20e047a2010-10-30 00:11:39 +00001123 // OpenCL initializers allows vectors to be constructed from vectors.
1124 for (unsigned i = 0; i < maxElements; ++i) {
1125 // Don't attempt to go past the end of the init list
1126 if (Index >= IList->getNumInits())
1127 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001128
John McCall20e047a2010-10-30 00:11:39 +00001129 ElementEntity.setElementIndex(Index);
1130
1131 QualType IType = IList->getInit(Index)->getType();
1132 if (!IType->isVectorType()) {
1133 CheckSubElementType(ElementEntity, IList, elementType, Index,
1134 StructuredList, StructuredIndex);
1135 ++numEltsInit;
1136 } else {
1137 QualType VecType;
1138 const VectorType *IVT = IType->getAs<VectorType>();
1139 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001140
John McCall20e047a2010-10-30 00:11:39 +00001141 if (IType->isExtVectorType())
1142 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1143 else
1144 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001145 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001146 CheckSubElementType(ElementEntity, IList, VecType, Index,
1147 StructuredList, StructuredIndex);
1148 numEltsInit += numIElts;
1149 }
1150 }
1151
1152 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001153 if (numEltsInit != maxElements) {
1154 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001155 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001156 diag::err_vector_incorrect_num_initializers)
1157 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1158 hadError = true;
1159 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001160}
1161
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001162void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001163 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001164 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001165 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001166 unsigned &Index,
1167 InitListExpr *StructuredList,
1168 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001169 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1170
Steve Naroff0cca7492008-05-01 22:18:59 +00001171 // Check for the special-case of initializing an array with a string.
1172 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001173 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001174 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001175 // We place the string literal directly into the resulting
1176 // initializer list. This is the only place where the structure
1177 // of the structured initializer list doesn't match exactly,
1178 // because doing so would involve allocating one character
1179 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001180 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001181 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001182 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1183 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1184 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001185 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001186 return;
1187 }
1188 }
John McCallce6c9b72011-02-21 07:22:22 +00001189 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001190 // Check for VLAs; in standard C it would be possible to check this
1191 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1192 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001193 if (!VerifyOnly)
1194 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1195 diag::err_variable_object_no_init)
1196 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001197 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001198 ++Index;
1199 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001200 return;
1201 }
1202
Douglas Gregor05c13a32009-01-22 00:58:24 +00001203 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001204 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1205 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001206 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001207 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001208 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001209 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001210 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001211 maxElementsKnown = true;
1212 }
1213
John McCallce6c9b72011-02-21 07:22:22 +00001214 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001215 while (Index < IList->getNumInits()) {
1216 Expr *Init = IList->getInit(Index);
1217 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001218 // If we're not the subobject that matches up with the '{' for
1219 // the designator, we shouldn't be handling the
1220 // designator. Return immediately.
1221 if (!SubobjectIsDesignatorContext)
1222 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001223
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001224 // Handle this designated initializer. elementIndex will be
1225 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001226 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001227 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001228 StructuredList, StructuredIndex, true,
1229 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001230 hadError = true;
1231 continue;
1232 }
1233
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001234 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001235 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001236 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001237 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001238 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001239
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001240 // If the array is of incomplete type, keep track of the number of
1241 // elements in the initializer.
1242 if (!maxElementsKnown && elementIndex > maxElements)
1243 maxElements = elementIndex;
1244
Douglas Gregor05c13a32009-01-22 00:58:24 +00001245 continue;
1246 }
1247
1248 // If we know the maximum number of elements, and we've already
1249 // hit it, stop consuming elements in the initializer list.
1250 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001251 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001252
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001253 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001254 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001255 Entity);
1256 // Check this element.
1257 CheckSubElementType(ElementEntity, IList, elementType, Index,
1258 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001259 ++elementIndex;
1260
1261 // If the array is of incomplete type, keep track of the number of
1262 // elements in the initializer.
1263 if (!maxElementsKnown && elementIndex > maxElements)
1264 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001265 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001266 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001267 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001268 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001269 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001270 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001271 // Sizing an array implicitly to zero is not allowed by ISO C,
1272 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001273 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001274 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001275 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001276
Mike Stump1eb44332009-09-09 15:08:12 +00001277 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001278 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001279 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001280 if (!hadError && VerifyOnly) {
1281 // Check if there are any members of the array that get value-initialized.
1282 // If so, check if doing that is possible.
1283 // FIXME: This needs to detect holes left by designated initializers too.
1284 if (maxElementsKnown && elementIndex < maxElements)
1285 CheckValueInitializable(InitializedEntity::InitializeElement(
1286 SemaRef.Context, 0, Entity));
1287 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001288}
1289
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001290bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1291 Expr *InitExpr,
1292 FieldDecl *Field,
1293 bool TopLevelObject) {
1294 // Handle GNU flexible array initializers.
1295 unsigned FlexArrayDiag;
1296 if (isa<InitListExpr>(InitExpr) &&
1297 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1298 // Empty flexible array init always allowed as an extension
1299 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001300 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001301 // Disallow flexible array init in C++; it is not required for gcc
1302 // compatibility, and it needs work to IRGen correctly in general.
1303 FlexArrayDiag = diag::err_flexible_array_init;
1304 } else if (!TopLevelObject) {
1305 // Disallow flexible array init on non-top-level object
1306 FlexArrayDiag = diag::err_flexible_array_init;
1307 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1308 // Disallow flexible array init on anything which is not a variable.
1309 FlexArrayDiag = diag::err_flexible_array_init;
1310 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1311 // Disallow flexible array init on local variables.
1312 FlexArrayDiag = diag::err_flexible_array_init;
1313 } else {
1314 // Allow other cases.
1315 FlexArrayDiag = diag::ext_flexible_array_init;
1316 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001317
1318 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001319 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001320 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001321 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001322 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1323 << Field;
1324 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001325
1326 return FlexArrayDiag != diag::ext_flexible_array_init;
1327}
1328
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001329void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001330 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001331 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001332 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001333 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001334 unsigned &Index,
1335 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001336 unsigned &StructuredIndex,
1337 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001338 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Eli Friedmanb85f7072008-05-19 19:16:24 +00001340 // If the record is invalid, some of it's members are invalid. To avoid
1341 // confusion, we forgo checking the intializer for the entire record.
1342 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001343 // Assume it was supposed to consume a single initializer.
1344 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001345 hadError = true;
1346 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001347 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001348
1349 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001350 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001351
1352 // If there's a default initializer, use it.
1353 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1354 if (VerifyOnly)
1355 return;
1356 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1357 Field != FieldEnd; ++Field) {
1358 if (Field->hasInClassInitializer()) {
1359 StructuredList->setInitializedFieldInUnion(*Field);
1360 // FIXME: Actually build a CXXDefaultInitExpr?
1361 return;
1362 }
1363 }
1364 }
1365
1366 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001367 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1368 Field != FieldEnd; ++Field) {
1369 if (Field->getDeclName()) {
1370 if (VerifyOnly)
1371 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001372 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001373 else
David Blaikie581deb32012-06-06 20:45:41 +00001374 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001375 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001376 }
1377 }
1378 return;
1379 }
1380
Douglas Gregor05c13a32009-01-22 00:58:24 +00001381 // If structDecl is a forward declaration, this loop won't do
1382 // anything except look at designated initializers; That's okay,
1383 // because an error should get printed out elsewhere. It might be
1384 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001385 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001386 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001387 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001388 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001389 while (Index < IList->getNumInits()) {
1390 Expr *Init = IList->getInit(Index);
1391
1392 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001393 // If we're not the subobject that matches up with the '{' for
1394 // the designator, we shouldn't be handling the
1395 // designator. Return immediately.
1396 if (!SubobjectIsDesignatorContext)
1397 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001398
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001399 // Handle this designated initializer. Field will be updated to
1400 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001401 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001402 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001403 StructuredList, StructuredIndex,
1404 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001405 hadError = true;
1406
Douglas Gregordfb5e592009-02-12 19:00:39 +00001407 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001408
1409 // Disable check for missing fields when designators are used.
1410 // This matches gcc behaviour.
1411 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001412 continue;
1413 }
1414
1415 if (Field == FieldEnd) {
1416 // We've run out of fields. We're done.
1417 break;
1418 }
1419
Douglas Gregordfb5e592009-02-12 19:00:39 +00001420 // We've already initialized a member of a union. We're done.
1421 if (InitializedSomething && DeclType->isUnionType())
1422 break;
1423
Douglas Gregor44b43212008-12-11 16:49:14 +00001424 // If we've hit the flexible array member at the end, we're done.
1425 if (Field->getType()->isIncompleteArrayType())
1426 break;
1427
Douglas Gregor0bb76892009-01-29 16:53:55 +00001428 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001429 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001430 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001431 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001432 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001433
Douglas Gregor54001c12011-06-29 21:51:31 +00001434 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001435 bool InvalidUse;
1436 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001437 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001438 else
David Blaikie581deb32012-06-06 20:45:41 +00001439 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001440 IList->getInit(Index)->getLocStart());
1441 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001442 ++Index;
1443 ++Field;
1444 hadError = true;
1445 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001446 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001447
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001448 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001449 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001450 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1451 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001452 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001453
Sebastian Redl14b0c192011-09-24 17:48:00 +00001454 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001455 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001456 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001457 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001458
1459 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001460 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001461
John McCall80639de2010-03-11 19:32:38 +00001462 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001463 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1464 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1465 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001466 // It is possible we have one or more unnamed bitfields remaining.
1467 // Find first (if any) named field and emit warning.
1468 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1469 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001470 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001471 SemaRef.Diag(IList->getSourceRange().getEnd(),
1472 diag::warn_missing_field_initializers) << it->getName();
1473 break;
1474 }
1475 }
1476 }
1477
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001478 // Check that any remaining fields can be value-initialized.
1479 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1480 !Field->getType()->isIncompleteArrayType()) {
1481 // FIXME: Should check for holes left by designated initializers too.
1482 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001483 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001484 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001485 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001486 }
1487 }
1488
Mike Stump1eb44332009-09-09 15:08:12 +00001489 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001490 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001491 return;
1492
David Blaikie581deb32012-06-06 20:45:41 +00001493 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001494 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001495 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001496 ++Index;
1497 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001498 }
1499
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001500 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001501 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001502
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001503 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001504 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001505 StructuredList, StructuredIndex);
1506 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001507 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001508 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001509}
Steve Naroff0cca7492008-05-01 22:18:59 +00001510
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001511/// \brief Expand a field designator that refers to a member of an
1512/// anonymous struct or union into a series of field designators that
1513/// refers to the field within the appropriate subobject.
1514///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001515static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001516 DesignatedInitExpr *DIE,
1517 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001518 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001519 typedef DesignatedInitExpr::Designator Designator;
1520
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001521 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001522 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001523 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1524 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1525 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001526 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001527 DIE->getDesignator(DesigIdx)->getDotLoc(),
1528 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1529 else
1530 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1531 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001532 assert(isa<FieldDecl>(*PI));
1533 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001534 }
1535
1536 // Expand the current designator into the set of replacement
1537 // designators, so we have a full subobject path down to where the
1538 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001539 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001540 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001541}
Mike Stump1eb44332009-09-09 15:08:12 +00001542
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001543/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001544/// corresponds to FieldName.
1545static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1546 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001547 if (!FieldName)
1548 return 0;
1549
Francois Picheta0e27f02010-12-22 03:46:10 +00001550 assert(AnonField->isAnonymousStructOrUnion());
1551 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001552 while (IndirectFieldDecl *IF =
1553 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001554 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001555 return IF;
1556 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001557 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001558 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001559}
1560
Sebastian Redl14b0c192011-09-24 17:48:00 +00001561static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1562 DesignatedInitExpr *DIE) {
1563 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1564 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1565 for (unsigned I = 0; I < NumIndexExprs; ++I)
1566 IndexExprs[I] = DIE->getSubExpr(I + 1);
1567 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001568 DIE->size(), IndexExprs,
1569 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001570 DIE->usesGNUSyntax(), DIE->getInit());
1571}
1572
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001573namespace {
1574
1575// Callback to only accept typo corrections that are for field members of
1576// the given struct or union.
1577class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1578 public:
1579 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1580 : Record(RD) {}
1581
1582 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1583 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1584 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1585 }
1586
1587 private:
1588 RecordDecl *Record;
1589};
1590
1591}
1592
Douglas Gregor05c13a32009-01-22 00:58:24 +00001593/// @brief Check the well-formedness of a C99 designated initializer.
1594///
1595/// Determines whether the designated initializer @p DIE, which
1596/// resides at the given @p Index within the initializer list @p
1597/// IList, is well-formed for a current object of type @p DeclType
1598/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001599/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001600/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001601///
1602/// @param IList The initializer list in which this designated
1603/// initializer occurs.
1604///
Douglas Gregor71199712009-04-15 04:56:10 +00001605/// @param DIE The designated initializer expression.
1606///
1607/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001608///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001609/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001610/// into which the designation in @p DIE should refer.
1611///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001612/// @param NextField If non-NULL and the first designator in @p DIE is
1613/// a field, this will be set to the field declaration corresponding
1614/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001615///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001616/// @param NextElementIndex If non-NULL and the first designator in @p
1617/// DIE is an array designator or GNU array-range designator, this
1618/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001619///
1620/// @param Index Index into @p IList where the designated initializer
1621/// @p DIE occurs.
1622///
Douglas Gregor4c678342009-01-28 21:54:33 +00001623/// @param StructuredList The initializer list expression that
1624/// describes all of the subobject initializers in the order they'll
1625/// actually be initialized.
1626///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001627/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001628bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001629InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001630 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001631 DesignatedInitExpr *DIE,
1632 unsigned DesigIdx,
1633 QualType &CurrentObjectType,
1634 RecordDecl::field_iterator *NextField,
1635 llvm::APSInt *NextElementIndex,
1636 unsigned &Index,
1637 InitListExpr *StructuredList,
1638 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001639 bool FinishSubobjectInit,
1640 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001641 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001642 // Check the actual initialization for the designated object type.
1643 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001644
1645 // Temporarily remove the designator expression from the
1646 // initializer list that the child calls see, so that we don't try
1647 // to re-process the designator.
1648 unsigned OldIndex = Index;
1649 IList->setInit(OldIndex, DIE->getInit());
1650
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001651 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001652 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001653
1654 // Restore the designated initializer expression in the syntactic
1655 // form of the initializer list.
1656 if (IList->getInit(OldIndex) != DIE->getInit())
1657 DIE->setInit(IList->getInit(OldIndex));
1658 IList->setInit(OldIndex, DIE);
1659
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001660 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001661 }
1662
Douglas Gregor71199712009-04-15 04:56:10 +00001663 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001664 bool IsFirstDesignator = (DesigIdx == 0);
1665 if (!VerifyOnly) {
1666 assert((IsFirstDesignator || StructuredList) &&
1667 "Need a non-designated initializer list to start from");
1668
1669 // Determine the structural initializer list that corresponds to the
1670 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001671 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001672 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1673 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001674 SourceRange(D->getLocStart(),
1675 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001676 assert(StructuredList && "Expected a structured initializer list");
1677 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001678
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001679 if (D->isFieldDesignator()) {
1680 // C99 6.7.8p7:
1681 //
1682 // If a designator has the form
1683 //
1684 // . identifier
1685 //
1686 // then the current object (defined below) shall have
1687 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001688 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001689 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001690 if (!RT) {
1691 SourceLocation Loc = D->getDotLoc();
1692 if (Loc.isInvalid())
1693 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001694 if (!VerifyOnly)
1695 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001696 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001697 ++Index;
1698 return true;
1699 }
1700
Douglas Gregor4c678342009-01-28 21:54:33 +00001701 // Note: we perform a linear search of the fields here, despite
1702 // the fact that we have a faster lookup method, because we always
1703 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001704 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001705 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001706 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001707 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001708 Field = RT->getDecl()->field_begin(),
1709 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001710 for (; Field != FieldEnd; ++Field) {
1711 if (Field->isUnnamedBitfield())
1712 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001713
Francois Picheta0e27f02010-12-22 03:46:10 +00001714 // If we find a field representing an anonymous field, look in the
1715 // IndirectFieldDecl that follow for the designated initializer.
1716 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1717 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001718 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001719 // In verify mode, don't modify the original.
1720 if (VerifyOnly)
1721 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001722 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1723 D = DIE->getDesignator(DesigIdx);
1724 break;
1725 }
1726 }
David Blaikie581deb32012-06-06 20:45:41 +00001727 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001728 break;
1729 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001730 break;
1731
1732 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001733 }
1734
Douglas Gregor4c678342009-01-28 21:54:33 +00001735 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001736 if (VerifyOnly) {
1737 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001738 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001739 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001740
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001741 // There was no normal field in the struct with the designated
1742 // name. Perform another lookup for this name, which may find
1743 // something that we can't designate (e.g., a member function),
1744 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001745 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001746 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001747 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001748 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001749 // Name lookup didn't find anything. Determine whether this
1750 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001751 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001752 TypoCorrection Corrected = SemaRef.CorrectTypo(
1753 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001754 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001755 RT->getDecl());
1756 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001757 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001758 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001759 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001760 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001761 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001762 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001763 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001764 << FieldName << CurrentObjectType << CorrectedQuotedStr
1765 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001766 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001767 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001768 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001769 } else {
1770 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1771 << FieldName << CurrentObjectType;
1772 ++Index;
1773 return true;
1774 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001775 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001776
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001777 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001778 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001779 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001780 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001781 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001782 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001783 ++Index;
1784 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001785 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001786
Francois Picheta0e27f02010-12-22 03:46:10 +00001787 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001788 // The replacement field comes from typo correction; find it
1789 // in the list of fields.
1790 FieldIndex = 0;
1791 Field = RT->getDecl()->field_begin();
1792 for (; Field != FieldEnd; ++Field) {
1793 if (Field->isUnnamedBitfield())
1794 continue;
1795
David Blaikie581deb32012-06-06 20:45:41 +00001796 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001797 Field->getIdentifier() == ReplacementField->getIdentifier())
1798 break;
1799
1800 ++FieldIndex;
1801 }
1802 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001803 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001804
1805 // All of the fields of a union are located at the same place in
1806 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001807 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001808 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001809 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001810 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001811 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001812
Douglas Gregor54001c12011-06-29 21:51:31 +00001813 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001814 bool InvalidUse;
1815 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001816 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001817 else
David Blaikie581deb32012-06-06 20:45:41 +00001818 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001819 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001820 ++Index;
1821 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001822 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001823
Sebastian Redl14b0c192011-09-24 17:48:00 +00001824 if (!VerifyOnly) {
1825 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001826 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Sebastian Redl14b0c192011-09-24 17:48:00 +00001828 // Make sure that our non-designated initializer list has space
1829 // for a subobject corresponding to this field.
1830 if (FieldIndex >= StructuredList->getNumInits())
1831 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1832 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001833
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001834 // This designator names a flexible array member.
1835 if (Field->getType()->isIncompleteArrayType()) {
1836 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001837 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001838 // We can't designate an object within the flexible array
1839 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001840 if (!VerifyOnly) {
1841 DesignatedInitExpr::Designator *NextD
1842 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001843 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001844 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001845 << SourceRange(NextD->getLocStart(),
1846 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001847 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001848 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001849 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001850 Invalid = true;
1851 }
1852
Chris Lattner9046c222010-10-10 17:49:49 +00001853 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1854 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001855 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001856 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001857 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001858 diag::err_flexible_array_init_needs_braces)
1859 << DIE->getInit()->getSourceRange();
1860 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001861 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001862 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001863 Invalid = true;
1864 }
1865
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001866 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001867 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001868 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001869 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001870
1871 if (Invalid) {
1872 ++Index;
1873 return true;
1874 }
1875
1876 // Initialize the array.
1877 bool prevHadError = hadError;
1878 unsigned newStructuredIndex = FieldIndex;
1879 unsigned OldIndex = Index;
1880 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001881
1882 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001883 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001884 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001885 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001886
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001887 IList->setInit(OldIndex, DIE);
1888 if (hadError && !prevHadError) {
1889 ++Field;
1890 ++FieldIndex;
1891 if (NextField)
1892 *NextField = Field;
1893 StructuredIndex = FieldIndex;
1894 return true;
1895 }
1896 } else {
1897 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001898 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001899 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001900
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001901 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001902 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001903 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1904 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001905 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001906 true, false))
1907 return true;
1908 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001909
1910 // Find the position of the next field to be initialized in this
1911 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001912 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001913 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001914
1915 // If this the first designator, our caller will continue checking
1916 // the rest of this struct/class/union subobject.
1917 if (IsFirstDesignator) {
1918 if (NextField)
1919 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001920 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001921 return false;
1922 }
1923
Douglas Gregor34e79462009-01-28 23:36:17 +00001924 if (!FinishSubobjectInit)
1925 return false;
1926
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001927 // We've already initialized something in the union; we're done.
1928 if (RT->getDecl()->isUnion())
1929 return hadError;
1930
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001931 // Check the remaining fields within this class/struct/union subobject.
1932 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001933
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001934 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001935 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001936 return hadError && !prevHadError;
1937 }
1938
1939 // C99 6.7.8p6:
1940 //
1941 // If a designator has the form
1942 //
1943 // [ constant-expression ]
1944 //
1945 // then the current object (defined below) shall have array
1946 // type and the expression shall be an integer constant
1947 // expression. If the array is of unknown size, any
1948 // nonnegative value is valid.
1949 //
1950 // Additionally, cope with the GNU extension that permits
1951 // designators of the form
1952 //
1953 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001954 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001955 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001956 if (!VerifyOnly)
1957 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1958 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001959 ++Index;
1960 return true;
1961 }
1962
1963 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001964 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1965 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001966 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001967 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001968 DesignatedEndIndex = DesignatedStartIndex;
1969 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001970 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001971
Mike Stump1eb44332009-09-09 15:08:12 +00001972 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001973 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001974 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001975 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001976 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001977
Chris Lattnere0fd8322011-02-19 22:28:58 +00001978 // Codegen can't handle evaluating array range designators that have side
1979 // effects, because we replicate the AST value for each initialized element.
1980 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1981 // elements with something that has a side effect, so codegen can emit an
1982 // "error unsupported" error instead of miscompiling the app.
1983 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001984 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001985 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001986 }
1987
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001988 if (isa<ConstantArrayType>(AT)) {
1989 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001990 DesignatedStartIndex
1991 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001992 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001993 DesignatedEndIndex
1994 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001995 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1996 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001997 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001998 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001999 diag::err_array_designator_too_large)
2000 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2001 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002002 ++Index;
2003 return true;
2004 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002005 } else {
2006 // Make sure the bit-widths and signedness match.
2007 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002008 DesignatedEndIndex
2009 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002010 else if (DesignatedStartIndex.getBitWidth() <
2011 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002012 DesignatedStartIndex
2013 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002014 DesignatedStartIndex.setIsUnsigned(true);
2015 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002016 }
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Douglas Gregor4c678342009-01-28 21:54:33 +00002018 // Make sure that our non-designated initializer list has space
2019 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002020 if (!VerifyOnly &&
2021 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002022 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002023 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002024
Douglas Gregor34e79462009-01-28 23:36:17 +00002025 // Repeatedly perform subobject initializations in the range
2026 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002027
Douglas Gregor34e79462009-01-28 23:36:17 +00002028 // Move to the next designator
2029 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2030 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002031
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002032 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002033 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002034
Douglas Gregor34e79462009-01-28 23:36:17 +00002035 while (DesignatedStartIndex <= DesignatedEndIndex) {
2036 // Recurse to check later designated subobjects.
2037 QualType ElementType = AT->getElementType();
2038 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002039
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002040 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002041 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2042 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002043 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002044 (DesignatedStartIndex == DesignatedEndIndex),
2045 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002046 return true;
2047
2048 // Move to the next index in the array that we'll be initializing.
2049 ++DesignatedStartIndex;
2050 ElementIndex = DesignatedStartIndex.getZExtValue();
2051 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002052
2053 // If this the first designator, our caller will continue checking
2054 // the rest of this array subobject.
2055 if (IsFirstDesignator) {
2056 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002057 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002058 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002059 return false;
2060 }
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Douglas Gregor34e79462009-01-28 23:36:17 +00002062 if (!FinishSubobjectInit)
2063 return false;
2064
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002065 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002066 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002067 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002068 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002069 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002070 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002071}
2072
Douglas Gregor4c678342009-01-28 21:54:33 +00002073// Get the structured initializer list for a subobject of type
2074// @p CurrentObjectType.
2075InitListExpr *
2076InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2077 QualType CurrentObjectType,
2078 InitListExpr *StructuredList,
2079 unsigned StructuredIndex,
2080 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002081 if (VerifyOnly)
2082 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002083 Expr *ExistingInit = 0;
2084 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002085 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002086 else if (StructuredIndex < StructuredList->getNumInits())
2087 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Douglas Gregor4c678342009-01-28 21:54:33 +00002089 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2090 return Result;
2091
2092 if (ExistingInit) {
2093 // We are creating an initializer list that initializes the
2094 // subobjects of the current object, but there was already an
2095 // initialization that completely initialized the current
2096 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002097 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002098 // struct X { int a, b; };
2099 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002100 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002101 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2102 // designated initializer re-initializes the whole
2103 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002104 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002105 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002106 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002107 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002108 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002109 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002110 << ExistingInit->getSourceRange();
2111 }
2112
Mike Stump1eb44332009-09-09 15:08:12 +00002113 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002114 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002115 InitRange.getBegin(), MultiExprArg(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00002116 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002117
Eli Friedman5c89c392012-02-23 02:25:10 +00002118 QualType ResultType = CurrentObjectType;
2119 if (!ResultType->isArrayType())
2120 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2121 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002122
Douglas Gregorfa219202009-03-20 23:58:33 +00002123 // Pre-allocate storage for the structured initializer list.
2124 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002125 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002126 bool GotNumInits = false;
2127 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002128 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002129 GotNumInits = true;
2130 } else if (Index < IList->getNumInits()) {
2131 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002132 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002133 GotNumInits = true;
2134 }
Douglas Gregor08457732009-03-21 18:13:52 +00002135 }
2136
Mike Stump1eb44332009-09-09 15:08:12 +00002137 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002138 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2139 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2140 NumElements = CAType->getSize().getZExtValue();
2141 // Simple heuristic so that we don't allocate a very large
2142 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002143 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002144 NumElements = 0;
2145 }
John McCall183700f2009-09-21 23:43:11 +00002146 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002147 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002148 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002149 RecordDecl *RDecl = RType->getDecl();
2150 if (RDecl->isUnion())
2151 NumElements = 1;
2152 else
Mike Stump1eb44332009-09-09 15:08:12 +00002153 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002154 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002155 }
2156
Ted Kremenek709210f2010-04-13 23:39:13 +00002157 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002158
Douglas Gregor4c678342009-01-28 21:54:33 +00002159 // Link this new initializer list into the structured initializer
2160 // lists.
2161 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002162 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002163 else {
2164 Result->setSyntacticForm(IList);
2165 SyntacticToSemantic[IList] = Result;
2166 }
2167
2168 return Result;
2169}
2170
2171/// Update the initializer at index @p StructuredIndex within the
2172/// structured initializer list to the value @p expr.
2173void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2174 unsigned &StructuredIndex,
2175 Expr *expr) {
2176 // No structured initializer list to update
2177 if (!StructuredList)
2178 return;
2179
Ted Kremenek709210f2010-04-13 23:39:13 +00002180 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2181 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002182 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002183 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002184 diag::warn_initializer_overrides)
2185 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002186 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002187 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002188 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002189 << PrevInit->getSourceRange();
2190 }
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Douglas Gregor4c678342009-01-28 21:54:33 +00002192 ++StructuredIndex;
2193}
2194
Douglas Gregor05c13a32009-01-22 00:58:24 +00002195/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002196/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002197/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002198/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002199/// failure. Returns the index expression, possibly with an implicit cast
2200/// added, on success. If everything went okay, Value will receive the
2201/// value of the constant expression.
2202static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002203CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002204 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002205
2206 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002207 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2208 if (Result.isInvalid())
2209 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002210
Chris Lattner3bf68932009-04-25 21:59:05 +00002211 if (Value.isSigned() && Value.isNegative())
2212 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002213 << Value.toString(10) << Index->getSourceRange();
2214
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002215 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002216 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002217}
2218
John McCall60d7b3a2010-08-24 06:29:42 +00002219ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002220 SourceLocation Loc,
2221 bool GNUSyntax,
2222 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002223 typedef DesignatedInitExpr::Designator ASTDesignator;
2224
2225 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002226 SmallVector<ASTDesignator, 32> Designators;
2227 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002228
2229 // Build designators and check array designator expressions.
2230 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2231 const Designator &D = Desig.getDesignator(Idx);
2232 switch (D.getKind()) {
2233 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002234 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002235 D.getFieldLoc()));
2236 break;
2237
2238 case Designator::ArrayDesignator: {
2239 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2240 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002241 if (!Index->isTypeDependent() && !Index->isValueDependent())
2242 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2243 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002244 Invalid = true;
2245 else {
2246 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002247 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002248 D.getRBracketLoc()));
2249 InitExpressions.push_back(Index);
2250 }
2251 break;
2252 }
2253
2254 case Designator::ArrayRangeDesignator: {
2255 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2256 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2257 llvm::APSInt StartValue;
2258 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002259 bool StartDependent = StartIndex->isTypeDependent() ||
2260 StartIndex->isValueDependent();
2261 bool EndDependent = EndIndex->isTypeDependent() ||
2262 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002263 if (!StartDependent)
2264 StartIndex =
2265 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2266 if (!EndDependent)
2267 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2268
2269 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002270 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002271 else {
2272 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002273 if (StartDependent || EndDependent) {
2274 // Nothing to compute.
2275 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002276 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002277 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002278 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002279
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002280 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002281 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002282 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002283 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2284 Invalid = true;
2285 } else {
2286 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002287 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002288 D.getEllipsisLoc(),
2289 D.getRBracketLoc()));
2290 InitExpressions.push_back(StartIndex);
2291 InitExpressions.push_back(EndIndex);
2292 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002293 }
2294 break;
2295 }
2296 }
2297 }
2298
2299 if (Invalid || Init.isInvalid())
2300 return ExprError();
2301
2302 // Clear out the expressions within the designation.
2303 Desig.ClearExprs(*this);
2304
2305 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002306 = DesignatedInitExpr::Create(Context,
2307 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002308 InitExpressions, Loc, GNUSyntax,
2309 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002310
David Blaikie4e4d0842012-03-11 07:00:24 +00002311 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002312 Diag(DIE->getLocStart(), diag::ext_designated_init)
2313 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002314
Douglas Gregor05c13a32009-01-22 00:58:24 +00002315 return Owned(DIE);
2316}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002317
Douglas Gregor20093b42009-12-09 23:02:17 +00002318//===----------------------------------------------------------------------===//
2319// Initialization entity
2320//===----------------------------------------------------------------------===//
2321
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002322InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002323 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002324 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002325{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002326 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2327 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002328 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002329 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002330 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002331 Type = VT->getElementType();
2332 } else {
2333 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2334 assert(CT && "Unexpected type");
2335 Kind = EK_ComplexElement;
2336 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002337 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002338}
2339
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002340InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002341 CXXBaseSpecifier *Base,
2342 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002343{
2344 InitializedEntity Result;
2345 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002346 Result.Base = reinterpret_cast<uintptr_t>(Base);
2347 if (IsInheritedVirtualBase)
2348 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002349
Douglas Gregord6542d82009-12-22 15:35:07 +00002350 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002351 return Result;
2352}
2353
Douglas Gregor99a2e602009-12-16 01:38:02 +00002354DeclarationName InitializedEntity::getName() const {
2355 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002356 case EK_Parameter: {
2357 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2358 return (D ? D->getDeclName() : DeclarationName());
2359 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002360
2361 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002362 case EK_Member:
2363 return VariableOrMember->getDeclName();
2364
Douglas Gregor47736542012-02-15 16:57:26 +00002365 case EK_LambdaCapture:
2366 return Capture.Var->getDeclName();
2367
Douglas Gregor99a2e602009-12-16 01:38:02 +00002368 case EK_Result:
2369 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002370 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002371 case EK_Temporary:
2372 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002373 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002374 case EK_ArrayElement:
2375 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002376 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002377 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002378 return DeclarationName();
2379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002380
David Blaikie7530c032012-01-17 06:56:22 +00002381 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002382}
2383
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002384DeclaratorDecl *InitializedEntity::getDecl() const {
2385 switch (getKind()) {
2386 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002387 case EK_Member:
2388 return VariableOrMember;
2389
John McCallf85e1932011-06-15 23:02:42 +00002390 case EK_Parameter:
2391 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2392
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002393 case EK_Result:
2394 case EK_Exception:
2395 case EK_New:
2396 case EK_Temporary:
2397 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002398 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002399 case EK_ArrayElement:
2400 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002401 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002402 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002403 case EK_LambdaCapture:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002404 return 0;
2405 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002406
David Blaikie7530c032012-01-17 06:56:22 +00002407 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002408}
2409
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002410bool InitializedEntity::allowsNRVO() const {
2411 switch (getKind()) {
2412 case EK_Result:
2413 case EK_Exception:
2414 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002415
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002416 case EK_Variable:
2417 case EK_Parameter:
2418 case EK_Member:
2419 case EK_New:
2420 case EK_Temporary:
2421 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002422 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002423 case EK_ArrayElement:
2424 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002425 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002426 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002427 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002428 break;
2429 }
2430
2431 return false;
2432}
2433
Douglas Gregor20093b42009-12-09 23:02:17 +00002434//===----------------------------------------------------------------------===//
2435// Initialization sequence
2436//===----------------------------------------------------------------------===//
2437
2438void InitializationSequence::Step::Destroy() {
2439 switch (Kind) {
2440 case SK_ResolveAddressOfOverloadedFunction:
2441 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002442 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002443 case SK_CastDerivedToBaseLValue:
2444 case SK_BindReference:
2445 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002446 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002447 case SK_UserConversion:
2448 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002449 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002450 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002451 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002452 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002453 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002454 case SK_UnwrapInitList:
2455 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002456 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002457 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002458 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002459 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002460 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002461 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002462 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002463 case SK_PassByIndirectCopyRestore:
2464 case SK_PassByIndirectRestore:
2465 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002466 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002467 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002468 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002469 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002470
Douglas Gregor20093b42009-12-09 23:02:17 +00002471 case SK_ConversionSequence:
2472 delete ICS;
2473 }
2474}
2475
Douglas Gregorb70cf442010-03-26 20:14:36 +00002476bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002477 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002478}
2479
2480bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002481 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002482 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002483
Douglas Gregorb70cf442010-03-26 20:14:36 +00002484 switch (getFailureKind()) {
2485 case FK_TooManyInitsForReference:
2486 case FK_ArrayNeedsInitList:
2487 case FK_ArrayNeedsInitListOrStringLiteral:
2488 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2489 case FK_NonConstLValueReferenceBindingToTemporary:
2490 case FK_NonConstLValueReferenceBindingToUnrelated:
2491 case FK_RValueReferenceBindingToLValue:
2492 case FK_ReferenceInitDropsQualifiers:
2493 case FK_ReferenceInitFailed:
2494 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002495 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002496 case FK_TooManyInitsForScalar:
2497 case FK_ReferenceBindingToInitList:
2498 case FK_InitListBadDestinationType:
2499 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002500 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002501 case FK_ArrayTypeMismatch:
2502 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002503 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002504 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002505 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002506 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002507 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002508 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002509
Douglas Gregorb70cf442010-03-26 20:14:36 +00002510 case FK_ReferenceInitOverloadFailed:
2511 case FK_UserConversionOverloadFailed:
2512 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002513 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002514 return FailedOverloadResult == OR_Ambiguous;
2515 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002516
David Blaikie7530c032012-01-17 06:56:22 +00002517 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002518}
2519
Douglas Gregord6e44a32010-04-16 22:09:46 +00002520bool InitializationSequence::isConstructorInitialization() const {
2521 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2522}
2523
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002524void
2525InitializationSequence
2526::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2527 DeclAccessPair Found,
2528 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002529 Step S;
2530 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2531 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002532 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002533 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002534 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002535 Steps.push_back(S);
2536}
2537
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002538void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002539 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002540 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002541 switch (VK) {
2542 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2543 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2544 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002545 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002546 S.Type = BaseType;
2547 Steps.push_back(S);
2548}
2549
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002550void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002551 bool BindingTemporary) {
2552 Step S;
2553 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2554 S.Type = T;
2555 Steps.push_back(S);
2556}
2557
Douglas Gregor523d46a2010-04-18 07:40:54 +00002558void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2559 Step S;
2560 S.Kind = SK_ExtraneousCopyToTemporary;
2561 S.Type = T;
2562 Steps.push_back(S);
2563}
2564
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002565void
2566InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2567 DeclAccessPair FoundDecl,
2568 QualType T,
2569 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002570 Step S;
2571 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002572 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002573 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002574 S.Function.Function = Function;
2575 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002576 Steps.push_back(S);
2577}
2578
2579void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002580 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002581 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002582 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002583 switch (VK) {
2584 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002585 S.Kind = SK_QualificationConversionRValue;
2586 break;
John McCall5baba9d2010-08-25 10:28:54 +00002587 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002588 S.Kind = SK_QualificationConversionXValue;
2589 break;
John McCall5baba9d2010-08-25 10:28:54 +00002590 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002591 S.Kind = SK_QualificationConversionLValue;
2592 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002593 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002594 S.Type = Ty;
2595 Steps.push_back(S);
2596}
2597
Jordan Rose1fd1e282013-04-11 00:58:58 +00002598void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2599 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2600
2601 Step S;
2602 S.Kind = SK_LValueToRValue;
2603 S.Type = Ty;
2604 Steps.push_back(S);
2605}
2606
Douglas Gregor20093b42009-12-09 23:02:17 +00002607void InitializationSequence::AddConversionSequenceStep(
2608 const ImplicitConversionSequence &ICS,
2609 QualType T) {
2610 Step S;
2611 S.Kind = SK_ConversionSequence;
2612 S.Type = T;
2613 S.ICS = new ImplicitConversionSequence(ICS);
2614 Steps.push_back(S);
2615}
2616
Douglas Gregord87b61f2009-12-10 17:56:55 +00002617void InitializationSequence::AddListInitializationStep(QualType T) {
2618 Step S;
2619 S.Kind = SK_ListInitialization;
2620 S.Type = T;
2621 Steps.push_back(S);
2622}
2623
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002624void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002625InitializationSequence
2626::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2627 AccessSpecifier Access,
2628 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002629 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002630 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002631 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002632 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2633 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002634 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002635 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002636 S.Function.Function = Constructor;
2637 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002638 Steps.push_back(S);
2639}
2640
Douglas Gregor71d17402009-12-15 00:01:57 +00002641void InitializationSequence::AddZeroInitializationStep(QualType T) {
2642 Step S;
2643 S.Kind = SK_ZeroInitialization;
2644 S.Type = T;
2645 Steps.push_back(S);
2646}
2647
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002648void InitializationSequence::AddCAssignmentStep(QualType T) {
2649 Step S;
2650 S.Kind = SK_CAssignment;
2651 S.Type = T;
2652 Steps.push_back(S);
2653}
2654
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002655void InitializationSequence::AddStringInitStep(QualType T) {
2656 Step S;
2657 S.Kind = SK_StringInit;
2658 S.Type = T;
2659 Steps.push_back(S);
2660}
2661
Douglas Gregor569c3162010-08-07 11:51:51 +00002662void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2663 Step S;
2664 S.Kind = SK_ObjCObjectConversion;
2665 S.Type = T;
2666 Steps.push_back(S);
2667}
2668
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002669void InitializationSequence::AddArrayInitStep(QualType T) {
2670 Step S;
2671 S.Kind = SK_ArrayInit;
2672 S.Type = T;
2673 Steps.push_back(S);
2674}
2675
Richard Smith0f163e92012-02-15 22:38:09 +00002676void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2677 Step S;
2678 S.Kind = SK_ParenthesizedArrayInit;
2679 S.Type = T;
2680 Steps.push_back(S);
2681}
2682
John McCallf85e1932011-06-15 23:02:42 +00002683void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2684 bool shouldCopy) {
2685 Step s;
2686 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2687 : SK_PassByIndirectRestore);
2688 s.Type = type;
2689 Steps.push_back(s);
2690}
2691
2692void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2693 Step S;
2694 S.Kind = SK_ProduceObjCObject;
2695 S.Type = T;
2696 Steps.push_back(S);
2697}
2698
Sebastian Redl2b916b82012-01-17 22:49:42 +00002699void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2700 Step S;
2701 S.Kind = SK_StdInitializerList;
2702 S.Type = T;
2703 Steps.push_back(S);
2704}
2705
Guy Benyei21f18c42013-02-07 10:55:47 +00002706void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2707 Step S;
2708 S.Kind = SK_OCLSamplerInit;
2709 S.Type = T;
2710 Steps.push_back(S);
2711}
2712
Guy Benyeie6b9d802013-01-20 12:31:11 +00002713void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2714 Step S;
2715 S.Kind = SK_OCLZeroEvent;
2716 S.Type = T;
2717 Steps.push_back(S);
2718}
2719
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002720void InitializationSequence::RewrapReferenceInitList(QualType T,
2721 InitListExpr *Syntactic) {
2722 assert(Syntactic->getNumInits() == 1 &&
2723 "Can only rewrap trivial init lists.");
2724 Step S;
2725 S.Kind = SK_UnwrapInitList;
2726 S.Type = Syntactic->getInit(0)->getType();
2727 Steps.insert(Steps.begin(), S);
2728
2729 S.Kind = SK_RewrapInitList;
2730 S.Type = T;
2731 S.WrappingSyntacticList = Syntactic;
2732 Steps.push_back(S);
2733}
2734
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002735void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002736 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002737 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002738 this->Failure = Failure;
2739 this->FailedOverloadResult = Result;
2740}
2741
2742//===----------------------------------------------------------------------===//
2743// Attempt initialization
2744//===----------------------------------------------------------------------===//
2745
John McCallf85e1932011-06-15 23:02:42 +00002746static void MaybeProduceObjCObject(Sema &S,
2747 InitializationSequence &Sequence,
2748 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002749 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002750
2751 /// When initializing a parameter, produce the value if it's marked
2752 /// __attribute__((ns_consumed)).
2753 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2754 if (!Entity.isParameterConsumed())
2755 return;
2756
2757 assert(Entity.getType()->isObjCRetainableType() &&
2758 "consuming an object of unretainable type?");
2759 Sequence.AddProduceObjCObjectStep(Entity.getType());
2760
2761 /// When initializing a return value, if the return type is a
2762 /// retainable type, then returns need to immediately retain the
2763 /// object. If an autorelease is required, it will be done at the
2764 /// last instant.
2765 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2766 if (!Entity.getType()->isObjCRetainableType())
2767 return;
2768
2769 Sequence.AddProduceObjCObjectStep(Entity.getType());
2770 }
2771}
2772
Richard Smithf4bb8d02012-07-05 08:39:21 +00002773/// \brief When initializing from init list via constructor, handle
2774/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002775///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002776/// \return true if we have handled initialization of an object of type
2777/// std::initializer_list<T>, false otherwise.
2778static bool TryInitializerListConstruction(Sema &S,
2779 InitListExpr *List,
2780 QualType DestType,
2781 InitializationSequence &Sequence) {
2782 QualType E;
2783 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002784 return false;
2785
Richard Smithf4bb8d02012-07-05 08:39:21 +00002786 // Check that each individual element can be copy-constructed. But since we
2787 // have no place to store further information, we'll recalculate everything
2788 // later.
2789 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2790 S.Context.getConstantArrayType(E,
2791 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2792 List->getNumInits()),
2793 ArrayType::Normal, 0));
2794 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2795 0, HiddenArray);
2796 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2797 Element.setElementIndex(i);
2798 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2799 Sequence.SetFailed(
2800 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002801 return true;
2802 }
2803 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002804 Sequence.AddStdInitializerListConstructionStep(DestType);
2805 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002806}
2807
Sebastian Redl96715b22012-02-04 21:27:39 +00002808static OverloadingResult
2809ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2810 Expr **Args, unsigned NumArgs,
2811 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002812 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002813 OverloadCandidateSet::iterator &Best,
2814 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002815 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002816 CandidateSet.clear();
2817
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002818 for (ArrayRef<NamedDecl *>::iterator
2819 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002820 NamedDecl *D = *Con;
2821 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2822 bool SuppressUserConversions = false;
2823
2824 // Find the constructor (which may be a template).
2825 CXXConstructorDecl *Constructor = 0;
2826 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2827 if (ConstructorTmpl)
2828 Constructor = cast<CXXConstructorDecl>(
2829 ConstructorTmpl->getTemplatedDecl());
2830 else {
2831 Constructor = cast<CXXConstructorDecl>(D);
2832
2833 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002834 // suppress user-defined conversions on the arguments. We do the same for
2835 // move constructors.
2836 if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2837 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002838 SuppressUserConversions = true;
2839 }
2840
2841 if (!Constructor->isInvalidDecl() &&
2842 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002843 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002844 if (ConstructorTmpl)
2845 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2846 /*ExplicitArgs*/ 0,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002847 llvm::makeArrayRef(Args, NumArgs),
2848 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002849 else {
2850 // C++ [over.match.copy]p1:
2851 // - When initializing a temporary to be bound to the first parameter
2852 // of a constructor that takes a reference to possibly cv-qualified
2853 // T as its first argument, called with a single argument in the
2854 // context of direct-initialization, explicit conversion functions
2855 // are also considered.
2856 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2857 NumArgs == 1 &&
2858 Constructor->isCopyOrMoveConstructor();
Sebastian Redl96715b22012-02-04 21:27:39 +00002859 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002860 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002861 SuppressUserConversions,
2862 /*PartialOverloading=*/false,
2863 /*AllowExplicit=*/AllowExplicitConv);
2864 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002865 }
2866 }
2867
2868 // Perform overload resolution and return the result.
2869 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2870}
2871
Sebastian Redl10f04a62011-12-22 14:44:04 +00002872/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2873/// enumerates the constructors of the initialized entity and performs overload
2874/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002875/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002876/// class type.
2877static void TryConstructorInitialization(Sema &S,
2878 const InitializedEntity &Entity,
2879 const InitializationKind &Kind,
2880 Expr **Args, unsigned NumArgs,
2881 QualType DestType,
2882 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002883 bool InitListSyntax = false) {
2884 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2885 "InitListSyntax must come with a single initializer list argument.");
2886
Sebastian Redl10f04a62011-12-22 14:44:04 +00002887 // The type we're constructing needs to be complete.
2888 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002889 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002890 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002891 }
2892
2893 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2894 assert(DestRecordType && "Constructor initialization requires record type");
2895 CXXRecordDecl *DestRecordDecl
2896 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2897
Sebastian Redl96715b22012-02-04 21:27:39 +00002898 // Build the candidate set directly in the initialization sequence
2899 // structure, so that it will persist if we fail.
2900 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2901
2902 // Determine whether we are allowed to call explicit constructors or
2903 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002904 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002905 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002906
Sebastian Redl10f04a62011-12-22 14:44:04 +00002907 // - Otherwise, if T is a class type, constructors are considered. The
2908 // applicable constructors are enumerated, and the best one is chosen
2909 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00002910 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002911 // The container holding the constructors can under certain conditions
2912 // be changed while iterating (e.g. because of deserialization).
2913 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00002914 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00002915
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002916 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002917 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002918 bool AsInitializerList = false;
2919
2920 // C++11 [over.match.list]p1:
2921 // When objects of non-aggregate type T are list-initialized, overload
2922 // resolution selects the constructor in two phases:
2923 // - Initially, the candidate functions are the initializer-list
2924 // constructors of the class T and the argument list consists of the
2925 // initializer list as a single argument.
2926 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002927 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002928 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00002929
2930 // If the initializer list has no elements and T has a default constructor,
2931 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00002932 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00002933 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002934 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00002935 CopyInitialization, AllowExplicit,
2936 /*OnlyListConstructor=*/true,
2937 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002938
2939 // Time to unwrap the init list.
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002940 Args = ILE->getInits();
2941 NumArgs = ILE->getNumInits();
2942 }
2943
2944 // C++11 [over.match.list]p1:
2945 // - If no viable initializer-list constructor is found, overload resolution
2946 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00002947 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002948 // elements of the initializer list.
2949 if (Result == OR_No_Viable_Function) {
2950 AsInitializerList = false;
2951 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002952 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002953 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002954 /*OnlyListConstructors=*/false,
2955 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002956 }
2957 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002958 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002959 InitializationSequence::FK_ListConstructorOverloadFailed :
2960 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002961 Result);
2962 return;
2963 }
2964
Richard Smithf4bb8d02012-07-05 08:39:21 +00002965 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002966 // If a program calls for the default initialization of an object
2967 // of a const-qualified type T, T shall be a class type with a
2968 // user-provided default constructor.
2969 if (Kind.getKind() == InitializationKind::IK_Default &&
2970 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00002971 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002972 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2973 return;
2974 }
2975
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002976 // C++11 [over.match.list]p1:
2977 // In copy-list-initialization, if an explicit constructor is chosen, the
2978 // initializer is ill-formed.
2979 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2980 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2981 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2982 return;
2983 }
2984
Sebastian Redl10f04a62011-12-22 14:44:04 +00002985 // Add the constructor initialization step. Any cv-qualification conversion is
2986 // subsumed by the initialization.
2987 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002988 Sequence.AddConstructorInitializationStep(CtorDecl,
2989 Best->FoundDecl.getAccess(),
2990 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002991 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002992}
2993
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002994static bool
2995ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2996 Expr *Initializer,
2997 QualType &SourceType,
2998 QualType &UnqualifiedSourceType,
2999 QualType UnqualifiedTargetType,
3000 InitializationSequence &Sequence) {
3001 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3002 S.Context.OverloadTy) {
3003 DeclAccessPair Found;
3004 bool HadMultipleCandidates = false;
3005 if (FunctionDecl *Fn
3006 = S.ResolveAddressOfOverloadedFunction(Initializer,
3007 UnqualifiedTargetType,
3008 false, Found,
3009 &HadMultipleCandidates)) {
3010 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3011 HadMultipleCandidates);
3012 SourceType = Fn->getType();
3013 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3014 } else if (!UnqualifiedTargetType->isRecordType()) {
3015 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3016 return true;
3017 }
3018 }
3019 return false;
3020}
3021
3022static void TryReferenceInitializationCore(Sema &S,
3023 const InitializedEntity &Entity,
3024 const InitializationKind &Kind,
3025 Expr *Initializer,
3026 QualType cv1T1, QualType T1,
3027 Qualifiers T1Quals,
3028 QualType cv2T2, QualType T2,
3029 Qualifiers T2Quals,
3030 InitializationSequence &Sequence);
3031
Richard Smithf4bb8d02012-07-05 08:39:21 +00003032static void TryValueInitialization(Sema &S,
3033 const InitializedEntity &Entity,
3034 const InitializationKind &Kind,
3035 InitializationSequence &Sequence,
3036 InitListExpr *InitList = 0);
3037
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003038static void TryListInitialization(Sema &S,
3039 const InitializedEntity &Entity,
3040 const InitializationKind &Kind,
3041 InitListExpr *InitList,
3042 InitializationSequence &Sequence);
3043
3044/// \brief Attempt list initialization of a reference.
3045static void TryReferenceListInitialization(Sema &S,
3046 const InitializedEntity &Entity,
3047 const InitializationKind &Kind,
3048 InitListExpr *InitList,
3049 InitializationSequence &Sequence)
3050{
3051 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003052 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003053 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3054 return;
3055 }
3056
3057 QualType DestType = Entity.getType();
3058 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3059 Qualifiers T1Quals;
3060 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3061
3062 // Reference initialization via an initializer list works thus:
3063 // If the initializer list consists of a single element that is
3064 // reference-related to the referenced type, bind directly to that element
3065 // (possibly creating temporaries).
3066 // Otherwise, initialize a temporary with the initializer list and
3067 // bind to that.
3068 if (InitList->getNumInits() == 1) {
3069 Expr *Initializer = InitList->getInit(0);
3070 QualType cv2T2 = Initializer->getType();
3071 Qualifiers T2Quals;
3072 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3073
3074 // If this fails, creating a temporary wouldn't work either.
3075 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3076 T1, Sequence))
3077 return;
3078
3079 SourceLocation DeclLoc = Initializer->getLocStart();
3080 bool dummy1, dummy2, dummy3;
3081 Sema::ReferenceCompareResult RefRelationship
3082 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3083 dummy2, dummy3);
3084 if (RefRelationship >= Sema::Ref_Related) {
3085 // Try to bind the reference here.
3086 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3087 T1Quals, cv2T2, T2, T2Quals, Sequence);
3088 if (Sequence)
3089 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3090 return;
3091 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003092
3093 // Update the initializer if we've resolved an overloaded function.
3094 if (Sequence.step_begin() != Sequence.step_end())
3095 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003096 }
3097
3098 // Not reference-related. Create a temporary and bind to that.
3099 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3100
3101 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3102 if (Sequence) {
3103 if (DestType->isRValueReferenceType() ||
3104 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3105 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3106 else
3107 Sequence.SetFailed(
3108 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3109 }
3110}
3111
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003112/// \brief Attempt list initialization (C++0x [dcl.init.list])
3113static void TryListInitialization(Sema &S,
3114 const InitializedEntity &Entity,
3115 const InitializationKind &Kind,
3116 InitListExpr *InitList,
3117 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003118 QualType DestType = Entity.getType();
3119
Sebastian Redl14b0c192011-09-24 17:48:00 +00003120 // C++ doesn't allow scalar initialization with more than one argument.
3121 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003122 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003123 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3124 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3125 return;
3126 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003127 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003128 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003129 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003130 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003131 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003132 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003133 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003134 return;
3135 }
3136
Richard Smithf4bb8d02012-07-05 08:39:21 +00003137 // C++11 [dcl.init.list]p3:
3138 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003139 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003140 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003141 // - Otherwise, if the initializer list has no elements and T is a
3142 // class type with a default constructor, the object is
3143 // value-initialized.
3144 if (InitList->getNumInits() == 0) {
3145 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003146 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003147 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3148 return;
3149 }
3150 }
3151
3152 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3153 // an initializer_list object constructed [...]
3154 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3155 return;
3156
3157 // - Otherwise, if T is a class type, constructors are considered.
Sebastian Redld2231c92012-02-19 12:27:43 +00003158 Expr *Arg = InitList;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003159 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3160 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003161 } else
3162 Sequence.SetFailed(
3163 InitializationSequence::FK_InitListBadDestinationType);
3164 return;
3165 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003166 }
3167
Sebastian Redl14b0c192011-09-24 17:48:00 +00003168 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003169 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003170 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00003171 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003172 if (CheckInitList.HadError()) {
3173 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3174 return;
3175 }
3176
3177 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003178 Sequence.AddListInitializationStep(DestType);
3179}
Douglas Gregor20093b42009-12-09 23:02:17 +00003180
3181/// \brief Try a reference initialization that involves calling a conversion
3182/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003183static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3184 const InitializedEntity &Entity,
3185 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003186 Expr *Initializer,
3187 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003188 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003189 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003190 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3191 QualType T1 = cv1T1.getUnqualifiedType();
3192 QualType cv2T2 = Initializer->getType();
3193 QualType T2 = cv2T2.getUnqualifiedType();
3194
3195 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003196 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003197 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003198 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003199 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003200 ObjCConversion,
3201 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003202 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003203 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003204 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003205 (void)ObjCLifetimeConversion;
3206
Douglas Gregor20093b42009-12-09 23:02:17 +00003207 // Build the candidate set directly in the initialization sequence
3208 // structure, so that it will persist if we fail.
3209 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3210 CandidateSet.clear();
3211
3212 // Determine whether we are allowed to call explicit constructors or
3213 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003214 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003215 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3216
Douglas Gregor20093b42009-12-09 23:02:17 +00003217 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003218 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3219 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003220 // The type we're converting to is a class type. Enumerate its constructors
3221 // to see if there is a suitable conversion.
3222 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003223
David Blaikie3bc93e32012-12-19 00:45:41 +00003224 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003225 // The container holding the constructors can under certain conditions
3226 // be changed while iterating (e.g. because of deserialization).
3227 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003228 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003229 for (SmallVector<NamedDecl*, 16>::iterator
3230 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3231 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003232 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3233
Douglas Gregor20093b42009-12-09 23:02:17 +00003234 // Find the constructor (which may be a template).
3235 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003236 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003237 if (ConstructorTmpl)
3238 Constructor = cast<CXXConstructorDecl>(
3239 ConstructorTmpl->getTemplatedDecl());
3240 else
John McCall9aa472c2010-03-19 07:35:19 +00003241 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003242
Douglas Gregor20093b42009-12-09 23:02:17 +00003243 if (!Constructor->isInvalidDecl() &&
3244 Constructor->isConvertingConstructor(AllowExplicit)) {
3245 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003246 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003247 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003248 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003249 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003250 else
John McCall9aa472c2010-03-19 07:35:19 +00003251 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003252 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003253 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003254 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003256 }
John McCall572fc622010-08-17 07:23:57 +00003257 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3258 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003259
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003260 const RecordType *T2RecordType = 0;
3261 if ((T2RecordType = T2->getAs<RecordType>()) &&
3262 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003263 // The type we're converting from is a class type, enumerate its conversion
3264 // functions.
3265 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3266
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003267 std::pair<CXXRecordDecl::conversion_iterator,
3268 CXXRecordDecl::conversion_iterator>
3269 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3270 for (CXXRecordDecl::conversion_iterator
3271 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003272 NamedDecl *D = *I;
3273 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3274 if (isa<UsingShadowDecl>(D))
3275 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003276
Douglas Gregor20093b42009-12-09 23:02:17 +00003277 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3278 CXXConversionDecl *Conv;
3279 if (ConvTemplate)
3280 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3281 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003282 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003283
Douglas Gregor20093b42009-12-09 23:02:17 +00003284 // If the conversion function doesn't return a reference type,
3285 // it can't be considered for this conversion unless we're allowed to
3286 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287 // FIXME: Do we need to make sure that we only consider conversion
3288 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003289 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003290 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003291 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3292 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003293 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003294 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003295 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003296 else
John McCall9aa472c2010-03-19 07:35:19 +00003297 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003298 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003299 }
3300 }
3301 }
John McCall572fc622010-08-17 07:23:57 +00003302 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3303 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304
Douglas Gregor20093b42009-12-09 23:02:17 +00003305 SourceLocation DeclLoc = Initializer->getLocStart();
3306
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003307 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003309 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003310 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003311 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003312
Douglas Gregor20093b42009-12-09 23:02:17 +00003313 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003314 // This is the overload that will be used for this initialization step if we
3315 // use this initialization. Mark it as referenced.
3316 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003317
Eli Friedman03981012009-12-11 02:42:07 +00003318 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003319 if (isa<CXXConversionDecl>(Function))
3320 T2 = Function->getResultType();
3321 else
3322 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003323
3324 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003325 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003326 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003327 T2.getNonLValueExprType(S.Context),
3328 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003329
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003330 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003331 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003332 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003333 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003334 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003335 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003336 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003337
Douglas Gregor20093b42009-12-09 23:02:17 +00003338 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003339 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003340 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003341 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003342 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003343 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003344 NewDerivedToBase, NewObjCConversion,
3345 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003346 if (NewRefRelationship == Sema::Ref_Incompatible) {
3347 // If the type we've converted to is not reference-related to the
3348 // type we're looking for, then there is another conversion step
3349 // we need to perform to produce a temporary of the right type
3350 // that we'll be binding to.
3351 ImplicitConversionSequence ICS;
3352 ICS.setStandard();
3353 ICS.Standard = Best->FinalConversion;
3354 T2 = ICS.Standard.getToType(2);
3355 Sequence.AddConversionSequenceStep(ICS, T2);
3356 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003357 Sequence.AddDerivedToBaseCastStep(
3358 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003359 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003360 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003361 else if (NewObjCConversion)
3362 Sequence.AddObjCObjectConversionStep(
3363 S.Context.getQualifiedType(T1,
3364 T2.getNonReferenceType().getQualifiers()));
3365
Douglas Gregor20093b42009-12-09 23:02:17 +00003366 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003367 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003368
Douglas Gregor20093b42009-12-09 23:02:17 +00003369 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3370 return OR_Success;
3371}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003372
Richard Smith83da2e72011-10-19 16:55:56 +00003373static void CheckCXX98CompatAccessibleCopy(Sema &S,
3374 const InitializedEntity &Entity,
3375 Expr *CurInitExpr);
3376
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3378static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003379 const InitializedEntity &Entity,
3380 const InitializationKind &Kind,
3381 Expr *Initializer,
3382 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003383 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003384 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003385 Qualifiers T1Quals;
3386 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003387 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003388 Qualifiers T2Quals;
3389 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003390
Douglas Gregor20093b42009-12-09 23:02:17 +00003391 // If the initializer is the address of an overloaded function, try
3392 // to resolve the overloaded function. If all goes well, T2 is the
3393 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003394 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3395 T1, Sequence))
3396 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003397
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003398 // Delegate everything else to a subfunction.
3399 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3400 T1Quals, cv2T2, T2, T2Quals, Sequence);
3401}
3402
Jordan Rose1fd1e282013-04-11 00:58:58 +00003403/// Converts the target of reference initialization so that it has the
3404/// appropriate qualifiers and value kind.
3405///
3406/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3407/// \code
3408/// int x;
3409/// const int &r = x;
3410/// \endcode
3411///
3412/// In this case the reference is binding to a bitfield lvalue, which isn't
3413/// valid. Perform a load to create a lifetime-extended temporary instead.
3414/// \code
3415/// const int &r = someStruct.bitfield;
3416/// \endcode
3417static ExprValueKind
3418convertQualifiersAndValueKindIfNecessary(Sema &S,
3419 InitializationSequence &Sequence,
3420 Expr *Initializer,
3421 QualType cv1T1,
3422 Qualifiers T1Quals,
3423 Qualifiers T2Quals,
3424 bool IsLValueRef) {
3425 bool IsNonAddressableType = Initializer->getBitField() ||
3426 Initializer->refersToVectorElement();
3427
3428 if (IsNonAddressableType) {
3429 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3430 // lvalue reference to a non-volatile const type, or the reference shall be
3431 // an rvalue reference.
3432 //
3433 // If not, we can't make a temporary and bind to that. Give up and allow the
3434 // error to be diagnosed later.
3435 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3436 assert(Initializer->isGLValue());
3437 return Initializer->getValueKind();
3438 }
3439
3440 // Force a load so we can materialize a temporary.
3441 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3442 return VK_RValue;
3443 }
3444
3445 if (T1Quals != T2Quals) {
3446 Sequence.AddQualificationConversionStep(cv1T1,
3447 Initializer->getValueKind());
3448 }
3449
3450 return Initializer->getValueKind();
3451}
3452
3453
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003454/// \brief Reference initialization without resolving overloaded functions.
3455static void TryReferenceInitializationCore(Sema &S,
3456 const InitializedEntity &Entity,
3457 const InitializationKind &Kind,
3458 Expr *Initializer,
3459 QualType cv1T1, QualType T1,
3460 Qualifiers T1Quals,
3461 QualType cv2T2, QualType T2,
3462 Qualifiers T2Quals,
3463 InitializationSequence &Sequence) {
3464 QualType DestType = Entity.getType();
3465 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003466 // Compute some basic properties of the types and the initializer.
3467 bool isLValueRef = DestType->isLValueReferenceType();
3468 bool isRValueRef = !isLValueRef;
3469 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003470 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003471 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003472 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003473 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003474 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003475 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003476
Douglas Gregor20093b42009-12-09 23:02:17 +00003477 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003479 // "cv2 T2" as follows:
3480 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003481 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003482 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003483 // Note the analogous bullet points for rvlaue refs to functions. Because
3484 // there are no function rvalues in C++, rvalue refs to functions are treated
3485 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003486 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003487 bool T1Function = T1->isFunctionType();
3488 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003489 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003490 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003491 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003492 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003494 // reference-compatible with "cv2 T2," or
3495 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003497 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003498 // can occur. However, we do pay attention to whether it is a bit-field
3499 // to decide whether we're actually binding to a temporary created from
3500 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003501 if (DerivedToBase)
3502 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003503 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003504 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003505 else if (ObjCConversion)
3506 Sequence.AddObjCObjectConversionStep(
3507 S.Context.getQualifiedType(T1, T2Quals));
3508
Jordan Rose1fd1e282013-04-11 00:58:58 +00003509 ExprValueKind ValueKind =
3510 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3511 cv1T1, T1Quals, T2Quals,
3512 isLValueRef);
3513 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003514 return;
3515 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003516
3517 // - has a class type (i.e., T2 is a class type), where T1 is not
3518 // reference-related to T2, and can be implicitly converted to an
3519 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3520 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003521 // applicable conversion functions (13.3.1.6) and choosing the best
3522 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003523 // If we have an rvalue ref to function type here, the rhs must be
3524 // an rvalue.
3525 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3526 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003527 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003528 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003529 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003530 Sequence);
3531 if (ConvOvlResult == OR_Success)
3532 return;
John McCall1d318332010-01-12 00:44:57 +00003533 if (ConvOvlResult != OR_No_Viable_Function) {
3534 Sequence.SetOverloadFailure(
3535 InitializationSequence::FK_ReferenceInitOverloadFailed,
3536 ConvOvlResult);
3537 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003538 }
3539 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003540
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003541 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003542 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003543 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003544 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003545 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3546 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3547 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003548 Sequence.SetOverloadFailure(
3549 InitializationSequence::FK_ReferenceInitOverloadFailed,
3550 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003551 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003552 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003553 ? (RefRelationship == Sema::Ref_Related
3554 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3555 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3556 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003557
Douglas Gregor20093b42009-12-09 23:02:17 +00003558 return;
3559 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003560
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003561 // - If the initializer expression
3562 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3563 // "cv1 T1" is reference-compatible with "cv2 T2"
3564 // Note: functions are handled below.
3565 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003566 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003567 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003568 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003569 (InitCategory.isXValue() ||
3570 (InitCategory.isPRValue() && T2->isRecordType()) ||
3571 (InitCategory.isPRValue() && T2->isArrayType()))) {
3572 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3573 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003574 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3575 // compiler the freedom to perform a copy here or bind to the
3576 // object, while C++0x requires that we bind directly to the
3577 // object. Hence, we always bind to the object without making an
3578 // extra copy. However, in C++03 requires that we check for the
3579 // presence of a suitable copy constructor:
3580 //
3581 // The constructor that would be used to make the copy shall
3582 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003583 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003584 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003585 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003586 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003587 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003588
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003589 if (DerivedToBase)
3590 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3591 ValueKind);
3592 else if (ObjCConversion)
3593 Sequence.AddObjCObjectConversionStep(
3594 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003595
Jordan Rose1fd1e282013-04-11 00:58:58 +00003596 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3597 Initializer, cv1T1,
3598 T1Quals, T2Quals,
3599 isLValueRef);
3600
3601 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003602 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003603 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003604
3605 // - has a class type (i.e., T2 is a class type), where T1 is not
3606 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003607 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3608 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003609 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003610 if (RefRelationship == Sema::Ref_Incompatible) {
3611 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3612 Kind, Initializer,
3613 /*AllowRValues=*/true,
3614 Sequence);
3615 if (ConvOvlResult)
3616 Sequence.SetOverloadFailure(
3617 InitializationSequence::FK_ReferenceInitOverloadFailed,
3618 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003619
Douglas Gregor20093b42009-12-09 23:02:17 +00003620 return;
3621 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003622
Douglas Gregordefa32e2013-03-26 23:59:23 +00003623 if ((RefRelationship == Sema::Ref_Compatible ||
3624 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3625 isRValueRef && InitCategory.isLValue()) {
3626 Sequence.SetFailed(
3627 InitializationSequence::FK_RValueReferenceBindingToLValue);
3628 return;
3629 }
3630
Douglas Gregor20093b42009-12-09 23:02:17 +00003631 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3632 return;
3633 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003634
3635 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003636 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003638 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003639
Douglas Gregor20093b42009-12-09 23:02:17 +00003640 // Determine whether we are allowed to call explicit constructors or
3641 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003642 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003643
3644 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3645
John McCallf85e1932011-06-15 23:02:42 +00003646 ImplicitConversionSequence ICS
3647 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003648 /*SuppressUserConversions*/ false,
3649 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003650 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003651 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3652 /*AllowObjCWritebackConversion=*/false);
3653
3654 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003655 // FIXME: Use the conversion function set stored in ICS to turn
3656 // this into an overloading ambiguity diagnostic. However, we need
3657 // to keep that set as an OverloadCandidateSet rather than as some
3658 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003659 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3660 Sequence.SetOverloadFailure(
3661 InitializationSequence::FK_ReferenceInitOverloadFailed,
3662 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003663 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3664 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003665 else
3666 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003667 return;
John McCallf85e1932011-06-15 23:02:42 +00003668 } else {
3669 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003670 }
3671
3672 // [...] If T1 is reference-related to T2, cv1 must be the
3673 // same cv-qualification as, or greater cv-qualification
3674 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003675 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3676 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003677 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003678 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003679 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3680 return;
3681 }
3682
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003683 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003684 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003685 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003686 InitCategory.isLValue()) {
3687 Sequence.SetFailed(
3688 InitializationSequence::FK_RValueReferenceBindingToLValue);
3689 return;
3690 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003691
Douglas Gregor20093b42009-12-09 23:02:17 +00003692 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3693 return;
3694}
3695
3696/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003697/// (C++ [dcl.init.string], C99 6.7.8).
3698static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003699 const InitializedEntity &Entity,
3700 const InitializationKind &Kind,
3701 Expr *Initializer,
3702 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003703 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003704}
3705
Douglas Gregor71d17402009-12-15 00:01:57 +00003706/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003707static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003708 const InitializedEntity &Entity,
3709 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003710 InitializationSequence &Sequence,
3711 InitListExpr *InitList) {
3712 assert((!InitList || InitList->getNumInits() == 0) &&
3713 "Shouldn't use value-init for non-empty init lists");
3714
Richard Smith1d0c9a82012-02-14 21:14:13 +00003715 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003716 //
3717 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003718 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003719
Douglas Gregor71d17402009-12-15 00:01:57 +00003720 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003721 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003722
Douglas Gregor71d17402009-12-15 00:01:57 +00003723 if (const RecordType *RT = T->getAs<RecordType>()) {
3724 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003725 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003726 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003727 // C++98:
3728 // -- if T is a class type (clause 9) with a user-declared constructor
3729 // (12.1), then the default constructor for T is called (and the
3730 // initialization is ill-formed if T has no accessible default
3731 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003732 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003733 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003734 } else {
3735 // C++11:
3736 // -- if T is a class type (clause 9) with either no default constructor
3737 // (12.1 [class.ctor]) or a default constructor that is user-provided
3738 // or deleted, then the object is default-initialized;
3739 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3740 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003741 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003742 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003743
Richard Smith1d0c9a82012-02-14 21:14:13 +00003744 // -- if T is a (possibly cv-qualified) non-union class type without a
3745 // user-provided or deleted default constructor, then the object is
3746 // zero-initialized and, if T has a non-trivial default constructor,
3747 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003748 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3749 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003750 if (NeedZeroInitialization)
3751 Sequence.AddZeroInitializationStep(Entity.getType());
3752
Richard Smithd5bc8672012-12-08 02:01:17 +00003753 // C++03:
3754 // -- if T is a non-union class type without a user-declared constructor,
3755 // then every non-static data member and base class component of T is
3756 // value-initialized;
3757 // [...] A program that calls for [...] value-initialization of an
3758 // entity of reference type is ill-formed.
3759 //
3760 // C++11 doesn't need this handling, because value-initialization does not
3761 // occur recursively there, and the implicit default constructor is
3762 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003763 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003764 ClassDecl->hasUninitializedReferenceMember()) {
3765 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3766 return;
3767 }
3768
Richard Smithf4bb8d02012-07-05 08:39:21 +00003769 // If this is list-value-initialization, pass the empty init list on when
3770 // building the constructor call. This affects the semantics of a few
3771 // things (such as whether an explicit default constructor can be called).
3772 Expr *InitListAsExpr = InitList;
3773 Expr **Args = InitList ? &InitListAsExpr : 0;
3774 unsigned NumArgs = InitList ? 1 : 0;
3775 bool InitListSyntax = InitList;
3776
3777 return TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, T,
3778 Sequence, InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003779 }
3780 }
3781
Douglas Gregord6542d82009-12-22 15:35:07 +00003782 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003783}
3784
Douglas Gregor99a2e602009-12-16 01:38:02 +00003785/// \brief Attempt default initialization (C++ [dcl.init]p6).
3786static void TryDefaultInitialization(Sema &S,
3787 const InitializedEntity &Entity,
3788 const InitializationKind &Kind,
3789 InitializationSequence &Sequence) {
3790 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003791
Douglas Gregor99a2e602009-12-16 01:38:02 +00003792 // C++ [dcl.init]p6:
3793 // To default-initialize an object of type T means:
3794 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003795 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3796
Douglas Gregor99a2e602009-12-16 01:38:02 +00003797 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3798 // constructor for T is called (and the initialization is ill-formed if
3799 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003800 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003801 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3802 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003803 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003804
Douglas Gregor99a2e602009-12-16 01:38:02 +00003805 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806
Douglas Gregor99a2e602009-12-16 01:38:02 +00003807 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003808 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003809 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003810 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003811 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003812 return;
3813 }
3814
3815 // If the destination type has a lifetime property, zero-initialize it.
3816 if (DestType.getQualifiers().hasObjCLifetime()) {
3817 Sequence.AddZeroInitializationStep(Entity.getType());
3818 return;
3819 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003820}
3821
Douglas Gregor20093b42009-12-09 23:02:17 +00003822/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3823/// which enumerates all conversion functions and performs overload resolution
3824/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003825static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003826 const InitializedEntity &Entity,
3827 const InitializationKind &Kind,
3828 Expr *Initializer,
3829 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003830 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003831 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3832 QualType SourceType = Initializer->getType();
3833 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3834 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835
Douglas Gregor4a520a22009-12-14 17:27:33 +00003836 // Build the candidate set directly in the initialization sequence
3837 // structure, so that it will persist if we fail.
3838 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3839 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003840
Douglas Gregor4a520a22009-12-14 17:27:33 +00003841 // Determine whether we are allowed to call explicit constructors or
3842 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003843 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844
Douglas Gregor4a520a22009-12-14 17:27:33 +00003845 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3846 // The type we're converting to is a class type. Enumerate its constructors
3847 // to see if there is a suitable conversion.
3848 CXXRecordDecl *DestRecordDecl
3849 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003850
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003851 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003852 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003853 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003854 // The container holding the constructors can under certain conditions
3855 // be changed while iterating. To be safe we copy the lookup results
3856 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003857 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003858 for (SmallVector<NamedDecl*, 8>::iterator
3859 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003860 Con != ConEnd; ++Con) {
3861 NamedDecl *D = *Con;
3862 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003864 // Find the constructor (which may be a template).
3865 CXXConstructorDecl *Constructor = 0;
3866 FunctionTemplateDecl *ConstructorTmpl
3867 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003868 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003869 Constructor = cast<CXXConstructorDecl>(
3870 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003871 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003872 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003873
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003874 if (!Constructor->isInvalidDecl() &&
3875 Constructor->isConvertingConstructor(AllowExplicit)) {
3876 if (ConstructorTmpl)
3877 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3878 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003879 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003880 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003881 else
3882 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003883 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003884 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003885 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003886 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003887 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003888 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003889
3890 SourceLocation DeclLoc = Initializer->getLocStart();
3891
Douglas Gregor4a520a22009-12-14 17:27:33 +00003892 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3893 // The type we're converting from is a class type, enumerate its conversion
3894 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003895
Eli Friedman33c2da92009-12-20 22:12:03 +00003896 // We can only enumerate the conversion functions for a complete type; if
3897 // the type isn't complete, simply skip this step.
3898 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3899 CXXRecordDecl *SourceRecordDecl
3900 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003901
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003902 std::pair<CXXRecordDecl::conversion_iterator,
3903 CXXRecordDecl::conversion_iterator>
3904 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3905 for (CXXRecordDecl::conversion_iterator
3906 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003907 NamedDecl *D = *I;
3908 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3909 if (isa<UsingShadowDecl>(D))
3910 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003911
Eli Friedman33c2da92009-12-20 22:12:03 +00003912 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3913 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003914 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003915 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003916 else
John McCall32daa422010-03-31 01:36:47 +00003917 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003918
Eli Friedman33c2da92009-12-20 22:12:03 +00003919 if (AllowExplicit || !Conv->isExplicit()) {
3920 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003921 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003922 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003923 CandidateSet);
3924 else
John McCall9aa472c2010-03-19 07:35:19 +00003925 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003926 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003927 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003928 }
3929 }
3930 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003931
3932 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003933 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003934 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003935 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003936 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003937 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003938 Result);
3939 return;
3940 }
John McCall1d318332010-01-12 00:44:57 +00003941
Douglas Gregor4a520a22009-12-14 17:27:33 +00003942 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003943 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003944 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945
Douglas Gregor4a520a22009-12-14 17:27:33 +00003946 if (isa<CXXConstructorDecl>(Function)) {
3947 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003948 // subsumed by the initialization. Per DR5, the created temporary is of the
3949 // cv-unqualified type of the destination.
3950 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3951 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003952 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003953 return;
3954 }
3955
3956 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003957 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003958 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003959 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003960 // the resulting temporary object (possible to create an object of
3961 // a base class type). That copy is not a separate conversion, so
3962 // we just make a note of the actual destination type (possibly a
3963 // base class of the type returned by the conversion function) and
3964 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003965 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3966 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003967 return;
3968 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003969
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003970 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3971 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003972
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003973 // If the conversion following the call to the conversion function
3974 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003975 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3976 Best->FinalConversion.Third) {
3977 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003978 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003979 ICS.Standard = Best->FinalConversion;
3980 Sequence.AddConversionSequenceStep(ICS, DestType);
3981 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003982}
3983
John McCallf85e1932011-06-15 23:02:42 +00003984/// The non-zero enum values here are indexes into diagnostic alternatives.
3985enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3986
3987/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003988static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003989 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00003990 // Skip parens.
3991 e = e->IgnoreParens();
3992
3993 // Skip address-of nodes.
3994 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3995 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003996 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
3997 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00003998
3999 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004000 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4001 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004002 case CK_Dependent:
4003 case CK_BitCast:
4004 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004005 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004006 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004007
4008 case CK_ArrayToPointerDecay:
4009 return IIK_nonscalar;
4010
4011 case CK_NullToPointer:
4012 return IIK_okay;
4013
4014 default:
4015 break;
4016 }
4017
4018 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004019 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004020 // set isWeakAccess to true, to mean that there will be an implicit
4021 // load which requires a cleanup.
4022 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4023 isWeakAccess = true;
4024
John McCallc03fa492011-06-27 23:59:58 +00004025 if (!isAddressOf) return IIK_nonlocal;
4026
John McCallf4b88a42012-03-10 09:33:50 +00004027 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4028 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004029
4030 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004031
4032 // If we have a conditional operator, check both sides.
4033 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004034 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4035 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004036 return iik;
4037
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004038 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004039
4040 // These are never scalar.
4041 } else if (isa<ArraySubscriptExpr>(e)) {
4042 return IIK_nonscalar;
4043
4044 // Otherwise, it needs to be a null pointer constant.
4045 } else {
4046 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4047 ? IIK_okay : IIK_nonlocal);
4048 }
4049
4050 return IIK_nonlocal;
4051}
4052
4053/// Check whether the given expression is a valid operand for an
4054/// indirect copy/restore.
4055static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4056 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004057 bool isWeakAccess = false;
4058 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4059 // If isWeakAccess to true, there will be an implicit
4060 // load which requires a cleanup.
4061 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4062 S.ExprNeedsCleanups = true;
4063
John McCallf85e1932011-06-15 23:02:42 +00004064 if (iik == IIK_okay) return;
4065
4066 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4067 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4068 << src->getSourceRange();
4069}
4070
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004071/// \brief Determine whether we have compatible array types for the
4072/// purposes of GNU by-copy array initialization.
4073static bool hasCompatibleArrayTypes(ASTContext &Context,
4074 const ArrayType *Dest,
4075 const ArrayType *Source) {
4076 // If the source and destination array types are equivalent, we're
4077 // done.
4078 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4079 return true;
4080
4081 // Make sure that the element types are the same.
4082 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4083 return false;
4084
4085 // The only mismatch we allow is when the destination is an
4086 // incomplete array type and the source is a constant array type.
4087 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4088}
4089
John McCallf85e1932011-06-15 23:02:42 +00004090static bool tryObjCWritebackConversion(Sema &S,
4091 InitializationSequence &Sequence,
4092 const InitializedEntity &Entity,
4093 Expr *Initializer) {
4094 bool ArrayDecay = false;
4095 QualType ArgType = Initializer->getType();
4096 QualType ArgPointee;
4097 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4098 ArrayDecay = true;
4099 ArgPointee = ArgArrayType->getElementType();
4100 ArgType = S.Context.getPointerType(ArgPointee);
4101 }
4102
4103 // Handle write-back conversion.
4104 QualType ConvertedArgType;
4105 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4106 ConvertedArgType))
4107 return false;
4108
4109 // We should copy unless we're passing to an argument explicitly
4110 // marked 'out'.
4111 bool ShouldCopy = true;
4112 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4113 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4114
4115 // Do we need an lvalue conversion?
4116 if (ArrayDecay || Initializer->isGLValue()) {
4117 ImplicitConversionSequence ICS;
4118 ICS.setStandard();
4119 ICS.Standard.setAsIdentityConversion();
4120
4121 QualType ResultType;
4122 if (ArrayDecay) {
4123 ICS.Standard.First = ICK_Array_To_Pointer;
4124 ResultType = S.Context.getPointerType(ArgPointee);
4125 } else {
4126 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4127 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4128 }
4129
4130 Sequence.AddConversionSequenceStep(ICS, ResultType);
4131 }
4132
4133 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4134 return true;
4135}
4136
Guy Benyei21f18c42013-02-07 10:55:47 +00004137static bool TryOCLSamplerInitialization(Sema &S,
4138 InitializationSequence &Sequence,
4139 QualType DestType,
4140 Expr *Initializer) {
4141 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4142 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4143 return false;
4144
4145 Sequence.AddOCLSamplerInitStep(DestType);
4146 return true;
4147}
4148
Guy Benyeie6b9d802013-01-20 12:31:11 +00004149//
4150// OpenCL 1.2 spec, s6.12.10
4151//
4152// The event argument can also be used to associate the
4153// async_work_group_copy with a previous async copy allowing
4154// an event to be shared by multiple async copies; otherwise
4155// event should be zero.
4156//
4157static bool TryOCLZeroEventInitialization(Sema &S,
4158 InitializationSequence &Sequence,
4159 QualType DestType,
4160 Expr *Initializer) {
4161 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4162 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4163 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4164 return false;
4165
4166 Sequence.AddOCLZeroEventStep(DestType);
4167 return true;
4168}
4169
Douglas Gregor20093b42009-12-09 23:02:17 +00004170InitializationSequence::InitializationSequence(Sema &S,
4171 const InitializedEntity &Entity,
4172 const InitializationKind &Kind,
4173 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00004174 unsigned NumArgs)
4175 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004176 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004177
John McCall76da55d2013-04-16 07:28:30 +00004178 // Eliminate non-overload placeholder types in the arguments. We
4179 // need to do this before checking whether types are dependent
4180 // because lowering a pseudo-object expression might well give us
4181 // something of dependent type.
4182 for (unsigned I = 0; I != NumArgs; ++I)
4183 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4184 // FIXME: should we be doing this here?
4185 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4186 if (result.isInvalid()) {
4187 SetFailed(FK_PlaceholderType);
4188 return;
4189 }
4190 Args[I] = result.take();
4191 }
4192
Douglas Gregor20093b42009-12-09 23:02:17 +00004193 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004194 // The semantics of initializers are as follows. The destination type is
4195 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004196 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004197 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004198 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004199 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004200
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004201 if (DestType->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +00004202 Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004203 SequenceKind = DependentSequence;
4204 return;
4205 }
4206
Sebastian Redl7491c492011-06-05 13:59:11 +00004207 // Almost everything is a normal sequence.
4208 setSequenceKind(NormalSequence);
4209
Douglas Gregor20093b42009-12-09 23:02:17 +00004210 QualType SourceType;
4211 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004212 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004213 Initializer = Args[0];
4214 if (!isa<InitListExpr>(Initializer))
4215 SourceType = Initializer->getType();
4216 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004217
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004218 // - If the initializer is a (non-parenthesized) braced-init-list, the
4219 // object is list-initialized (8.5.4).
4220 if (Kind.getKind() != InitializationKind::IK_Direct) {
4221 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4222 TryListInitialization(S, Entity, Kind, InitList, *this);
4223 return;
4224 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004225 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004226
Douglas Gregor20093b42009-12-09 23:02:17 +00004227 // - If the destination type is a reference type, see 8.5.3.
4228 if (DestType->isReferenceType()) {
4229 // C++0x [dcl.init.ref]p1:
4230 // A variable declared to be a T& or T&&, that is, "reference to type T"
4231 // (8.3.2), shall be initialized by an object, or function, of type T or
4232 // by an object that can be converted into a T.
4233 // (Therefore, multiple arguments are not permitted.)
4234 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004235 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004236 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004237 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004238 return;
4239 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004240
Douglas Gregor20093b42009-12-09 23:02:17 +00004241 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004242 if (Kind.getKind() == InitializationKind::IK_Value ||
4243 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004244 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004245 return;
4246 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004247
Douglas Gregor99a2e602009-12-16 01:38:02 +00004248 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004249 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004250 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004251 return;
4252 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004253
John McCallce6c9b72011-02-21 07:22:22 +00004254 // - If the destination type is an array of characters, an array of
4255 // char16_t, an array of char32_t, or an array of wchar_t, and the
4256 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004257 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004258 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004259 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004260 if (Initializer && isa<VariableArrayType>(DestAT)) {
4261 SetFailed(FK_VariableLengthArrayHasInitializer);
4262 return;
4263 }
4264
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004265 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004266 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004267 return;
4268 }
4269
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004270 // Note: as an GNU C extension, we allow initialization of an
4271 // array from a compound literal that creates an array of the same
4272 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004273 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004274 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4275 Initializer->getType()->isArrayType()) {
4276 const ArrayType *SourceAT
4277 = Context.getAsArrayType(Initializer->getType());
4278 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004279 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004280 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004281 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004282 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004283 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004284 }
Richard Smith0f163e92012-02-15 22:38:09 +00004285 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004286 // Note: as a GNU C++ extension, we allow list-initialization of a
4287 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004288 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004289 Entity.getKind() == InitializedEntity::EK_Member &&
4290 Initializer && isa<InitListExpr>(Initializer)) {
4291 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4292 *this);
4293 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004294 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004295 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004296 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004297 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004298
Douglas Gregor20093b42009-12-09 23:02:17 +00004299 return;
4300 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004301
John McCallf85e1932011-06-15 23:02:42 +00004302 // Determine whether we should consider writeback conversions for
4303 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004304 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004305 Entity.getKind() == InitializedEntity::EK_Parameter;
4306
4307 // We're at the end of the line for C: it's either a write-back conversion
4308 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004309 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004310 // If allowed, check whether this is an Objective-C writeback conversion.
4311 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004312 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004313 return;
4314 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004315
4316 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4317 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004318
4319 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4320 return;
4321
John McCallf85e1932011-06-15 23:02:42 +00004322 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004323 AddCAssignmentStep(DestType);
4324 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004325 return;
4326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327
David Blaikie4e4d0842012-03-11 07:00:24 +00004328 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004329
Douglas Gregor20093b42009-12-09 23:02:17 +00004330 // - If the destination type is a (possibly cv-qualified) class type:
4331 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004332 // - If the initialization is direct-initialization, or if it is
4333 // copy-initialization where the cv-unqualified version of the
4334 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004335 // class of the destination, constructors are considered. [...]
4336 if (Kind.getKind() == InitializationKind::IK_Direct ||
4337 (Kind.getKind() == InitializationKind::IK_Copy &&
4338 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4339 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004340 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004341 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004342 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004343 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004344 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004345 // used) to a derived class thereof are enumerated as described in
4346 // 13.3.1.4, and the best one is chosen through overload resolution
4347 // (13.3).
4348 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004349 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004350 return;
4351 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004352
Douglas Gregor99a2e602009-12-16 01:38:02 +00004353 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004354 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004355 return;
4356 }
4357 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004358
4359 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004360 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004361 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004362 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4363 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004364 return;
4365 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004366
Douglas Gregor20093b42009-12-09 23:02:17 +00004367 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004368 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004369 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004370 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004371 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004372
4373 ImplicitConversionSequence ICS
4374 = S.TryImplicitConversion(Initializer, Entity.getType(),
4375 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004376 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004377 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004378 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4379 allowObjCWritebackConversion);
4380
4381 if (ICS.isStandard() &&
4382 ICS.Standard.Second == ICK_Writeback_Conversion) {
4383 // Objective-C ARC writeback conversion.
4384
4385 // We should copy unless we're passing to an argument explicitly
4386 // marked 'out'.
4387 bool ShouldCopy = true;
4388 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4389 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4390
4391 // If there was an lvalue adjustment, add it as a separate conversion.
4392 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4393 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4394 ImplicitConversionSequence LvalueICS;
4395 LvalueICS.setStandard();
4396 LvalueICS.Standard.setAsIdentityConversion();
4397 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4398 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004399 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004400 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004401
4402 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004403 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004404 DeclAccessPair dap;
4405 if (Initializer->getType() == Context.OverloadTy &&
4406 !S.ResolveAddressOfOverloadedFunction(Initializer
4407 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004408 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004409 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004410 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004411 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004412 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004413
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004414 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004415 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004416}
4417
4418InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004419 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004420 StepEnd = Steps.end();
4421 Step != StepEnd; ++Step)
4422 Step->Destroy();
4423}
4424
4425//===----------------------------------------------------------------------===//
4426// Perform initialization
4427//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004428static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004429getAssignmentAction(const InitializedEntity &Entity) {
4430 switch(Entity.getKind()) {
4431 case InitializedEntity::EK_Variable:
4432 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004433 case InitializedEntity::EK_Exception:
4434 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004435 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004436 return Sema::AA_Initializing;
4437
4438 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004440 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4441 return Sema::AA_Sending;
4442
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004443 return Sema::AA_Passing;
4444
4445 case InitializedEntity::EK_Result:
4446 return Sema::AA_Returning;
4447
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004448 case InitializedEntity::EK_Temporary:
4449 // FIXME: Can we tell apart casting vs. converting?
4450 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004452 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004453 case InitializedEntity::EK_ArrayElement:
4454 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004455 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004456 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004457 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004458 return Sema::AA_Initializing;
4459 }
4460
David Blaikie7530c032012-01-17 06:56:22 +00004461 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004462}
4463
Richard Smith774d8b42013-01-08 00:08:23 +00004464/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004465/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004466static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004467 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004468 case InitializedEntity::EK_ArrayElement:
4469 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004470 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004471 case InitializedEntity::EK_New:
4472 case InitializedEntity::EK_Variable:
4473 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004474 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004475 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004476 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004477 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004478 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004479 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004480 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004481
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004482 case InitializedEntity::EK_Parameter:
4483 case InitializedEntity::EK_Temporary:
4484 return true;
4485 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004486
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004487 llvm_unreachable("missed an InitializedEntity kind?");
4488}
4489
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004490/// \brief Whether the given entity, when initialized with an object
4491/// created for that initialization, requires destruction.
4492static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4493 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004494 case InitializedEntity::EK_Result:
4495 case InitializedEntity::EK_New:
4496 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004497 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004498 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004499 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004500 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004501 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004502 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004503
Richard Smith774d8b42013-01-08 00:08:23 +00004504 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004505 case InitializedEntity::EK_Variable:
4506 case InitializedEntity::EK_Parameter:
4507 case InitializedEntity::EK_Temporary:
4508 case InitializedEntity::EK_ArrayElement:
4509 case InitializedEntity::EK_Exception:
4510 return true;
4511 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512
4513 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004514}
4515
Richard Smith83da2e72011-10-19 16:55:56 +00004516/// \brief Look for copy and move constructors and constructor templates, for
4517/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4518static void LookupCopyAndMoveConstructors(Sema &S,
4519 OverloadCandidateSet &CandidateSet,
4520 CXXRecordDecl *Class,
4521 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004522 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004523 // The container holding the constructors can under certain conditions
4524 // be changed while iterating (e.g. because of deserialization).
4525 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004526 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004527 for (SmallVector<NamedDecl*, 16>::iterator
4528 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4529 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004530 CXXConstructorDecl *Constructor = 0;
4531
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004532 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004533 // Handle copy/moveconstructors, only.
4534 if (!Constructor || Constructor->isInvalidDecl() ||
4535 !Constructor->isCopyOrMoveConstructor() ||
4536 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4537 continue;
4538
4539 DeclAccessPair FoundDecl
4540 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4541 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004542 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004543 continue;
4544 }
4545
4546 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004547 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004548 if (ConstructorTmpl->isInvalidDecl())
4549 continue;
4550
4551 Constructor = cast<CXXConstructorDecl>(
4552 ConstructorTmpl->getTemplatedDecl());
4553 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4554 continue;
4555
4556 // FIXME: Do we need to limit this to copy-constructor-like
4557 // candidates?
4558 DeclAccessPair FoundDecl
4559 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4560 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004561 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004562 }
4563}
4564
4565/// \brief Get the location at which initialization diagnostics should appear.
4566static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4567 Expr *Initializer) {
4568 switch (Entity.getKind()) {
4569 case InitializedEntity::EK_Result:
4570 return Entity.getReturnLoc();
4571
4572 case InitializedEntity::EK_Exception:
4573 return Entity.getThrowLoc();
4574
4575 case InitializedEntity::EK_Variable:
4576 return Entity.getDecl()->getLocation();
4577
Douglas Gregor47736542012-02-15 16:57:26 +00004578 case InitializedEntity::EK_LambdaCapture:
4579 return Entity.getCaptureLoc();
4580
Richard Smith83da2e72011-10-19 16:55:56 +00004581 case InitializedEntity::EK_ArrayElement:
4582 case InitializedEntity::EK_Member:
4583 case InitializedEntity::EK_Parameter:
4584 case InitializedEntity::EK_Temporary:
4585 case InitializedEntity::EK_New:
4586 case InitializedEntity::EK_Base:
4587 case InitializedEntity::EK_Delegating:
4588 case InitializedEntity::EK_VectorElement:
4589 case InitializedEntity::EK_ComplexElement:
4590 case InitializedEntity::EK_BlockElement:
4591 return Initializer->getLocStart();
4592 }
4593 llvm_unreachable("missed an InitializedEntity kind?");
4594}
4595
Douglas Gregor523d46a2010-04-18 07:40:54 +00004596/// \brief Make a (potentially elidable) temporary copy of the object
4597/// provided by the given initializer by calling the appropriate copy
4598/// constructor.
4599///
4600/// \param S The Sema object used for type-checking.
4601///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004602/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004603/// the type of the initializer expression or a superclass thereof.
4604///
James Dennett1dfbd922012-06-14 21:40:34 +00004605/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004606///
4607/// \param CurInit The initializer expression.
4608///
4609/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4610/// is permitted in C++03 (but not C++0x) when binding a reference to
4611/// an rvalue.
4612///
4613/// \returns An expression that copies the initializer expression into
4614/// a temporary object, or an error expression if a copy could not be
4615/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004616static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004617 QualType T,
4618 const InitializedEntity &Entity,
4619 ExprResult CurInit,
4620 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004621 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004622 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004623 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004624 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004625 Class = cast<CXXRecordDecl>(Record->getDecl());
4626 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004627 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004628
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004629 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004630 // When certain criteria are met, an implementation is allowed to
4631 // omit the copy/move construction of a class object, even if the
4632 // copy/move constructor and/or destructor for the object have
4633 // side effects. [...]
4634 // - when a temporary class object that has not been bound to a
4635 // reference (12.2) would be copied/moved to a class object
4636 // with the same cv-unqualified type, the copy/move operation
4637 // can be omitted by constructing the temporary object
4638 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004639 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004640 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004641 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004642 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004643 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004644 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004645 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004646
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004647 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004648 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004649 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004650
Douglas Gregorcc15f012011-01-21 19:38:21 +00004651 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004652 // Only consider constructors and constructor templates. Per
4653 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4654 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004655 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004656 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004657
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004658 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4659
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004660 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004661 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004662 case OR_Success:
4663 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004664
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004665 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004666 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4667 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4668 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004669 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004670 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004671 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004672 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004673 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004674 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004675
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004676 case OR_Ambiguous:
4677 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004678 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004679 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004680 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004681 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004682
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004683 case OR_Deleted:
4684 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004685 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004686 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004687 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004688 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004689 }
4690
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004691 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004692 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004693 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004694
Anders Carlsson9a68a672010-04-21 18:47:17 +00004695 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004696 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004697
4698 if (IsExtraneousCopy) {
4699 // If this is a totally extraneous copy for C++03 reference
4700 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004701 // expression. We don't generate an (elided) copy operation here
4702 // because doing so would require us to pass down a flag to avoid
4703 // infinite recursion, where each step adds another extraneous,
4704 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004705
Douglas Gregor2559a702010-04-18 07:57:34 +00004706 // Instantiate the default arguments of any extra parameters in
4707 // the selected copy constructor, as if we were going to create a
4708 // proper call to the copy constructor.
4709 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4710 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4711 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004712 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004713 break;
4714
4715 // Build the default argument expression; we don't actually care
4716 // if this succeeds or not, because this routine will complain
4717 // if there was a problem.
4718 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4719 }
4720
Douglas Gregor523d46a2010-04-18 07:40:54 +00004721 return S.Owned(CurInitExpr);
4722 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004723
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004724 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004725 // constructor call (we might have derived-to-base conversions, or
4726 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004727 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004728 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004729 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004730
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004731 // Actually perform the constructor call.
4732 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004733 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004734 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004735 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004736 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004737 CXXConstructExpr::CK_Complete,
4738 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004739
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004740 // If we're supposed to bind temporaries, do so.
4741 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4742 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004743 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004744}
Douglas Gregor20093b42009-12-09 23:02:17 +00004745
Richard Smith83da2e72011-10-19 16:55:56 +00004746/// \brief Check whether elidable copy construction for binding a reference to
4747/// a temporary would have succeeded if we were building in C++98 mode, for
4748/// -Wc++98-compat.
4749static void CheckCXX98CompatAccessibleCopy(Sema &S,
4750 const InitializedEntity &Entity,
4751 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004752 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004753
4754 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4755 if (!Record)
4756 return;
4757
4758 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4759 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4760 == DiagnosticsEngine::Ignored)
4761 return;
4762
4763 // Find constructors which would have been considered.
4764 OverloadCandidateSet CandidateSet(Loc);
4765 LookupCopyAndMoveConstructors(
4766 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4767
4768 // Perform overload resolution.
4769 OverloadCandidateSet::iterator Best;
4770 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4771
4772 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4773 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4774 << CurInitExpr->getSourceRange();
4775
4776 switch (OR) {
4777 case OR_Success:
4778 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004779 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004780 // FIXME: Check default arguments as far as that's possible.
4781 break;
4782
4783 case OR_No_Viable_Function:
4784 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004785 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004786 break;
4787
4788 case OR_Ambiguous:
4789 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004790 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004791 break;
4792
4793 case OR_Deleted:
4794 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004795 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004796 break;
4797 }
4798}
4799
Douglas Gregora41a8c52010-04-22 00:20:18 +00004800void InitializationSequence::PrintInitLocationNote(Sema &S,
4801 const InitializedEntity &Entity) {
4802 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4803 if (Entity.getDecl()->getLocation().isInvalid())
4804 return;
4805
4806 if (Entity.getDecl()->getDeclName())
4807 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4808 << Entity.getDecl()->getDeclName();
4809 else
4810 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4811 }
4812}
4813
Sebastian Redl3b802322011-07-14 19:07:55 +00004814static bool isReferenceBinding(const InitializationSequence::Step &s) {
4815 return s.Kind == InitializationSequence::SK_BindReference ||
4816 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4817}
4818
Sebastian Redl10f04a62011-12-22 14:44:04 +00004819static ExprResult
4820PerformConstructorInitialization(Sema &S,
4821 const InitializedEntity &Entity,
4822 const InitializationKind &Kind,
4823 MultiExprArg Args,
4824 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004825 bool &ConstructorInitRequiresZeroInit,
4826 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004827 unsigned NumArgs = Args.size();
4828 CXXConstructorDecl *Constructor
4829 = cast<CXXConstructorDecl>(Step.Function.Function);
4830 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4831
4832 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004833 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004834 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4835 ? Kind.getEqualLoc()
4836 : Kind.getLocation();
4837
4838 if (Kind.getKind() == InitializationKind::IK_Default) {
4839 // Force even a trivial, implicit default constructor to be
4840 // semantically checked. We do this explicitly because we don't build
4841 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004842 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004843 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004844 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004845 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4846 }
4847
4848 ExprResult CurInit = S.Owned((Expr *)0);
4849
Douglas Gregored878af2012-02-24 23:56:31 +00004850 // C++ [over.match.copy]p1:
4851 // - When initializing a temporary to be bound to the first parameter
4852 // of a constructor that takes a reference to possibly cv-qualified
4853 // T as its first argument, called with a single argument in the
4854 // context of direct-initialization, explicit conversion functions
4855 // are also considered.
4856 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4857 Args.size() == 1 &&
4858 Constructor->isCopyOrMoveConstructor();
4859
Sebastian Redl10f04a62011-12-22 14:44:04 +00004860 // Determine the arguments required to actually perform the constructor
4861 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004862 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004863 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004864 AllowExplicitConv,
4865 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004866 return ExprError();
4867
4868
4869 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Sebastian Redl188158d2012-03-08 21:05:45 +00004870 (Kind.getKind() == InitializationKind::IK_DirectList ||
4871 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4872 (Kind.getKind() == InitializationKind::IK_Direct ||
4873 Kind.getKind() == InitializationKind::IK_Value)))) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004874 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004875 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redl10f04a62011-12-22 14:44:04 +00004876 S.DiagnoseUseOfDecl(Constructor, Loc);
4877
4878 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4879 if (!TSInfo)
4880 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004881 SourceRange ParenRange;
4882 if (Kind.getKind() != InitializationKind::IK_DirectList)
4883 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004884
Richard Smithc83c2302012-12-19 01:39:02 +00004885 CurInit = S.Owned(
4886 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4887 TSInfo, ConstructorArgs,
4888 ParenRange, IsListInitialization,
4889 HadMultipleCandidates,
4890 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00004891 } else {
4892 CXXConstructExpr::ConstructionKind ConstructKind =
4893 CXXConstructExpr::CK_Complete;
4894
4895 if (Entity.getKind() == InitializedEntity::EK_Base) {
4896 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4897 CXXConstructExpr::CK_VirtualBase :
4898 CXXConstructExpr::CK_NonVirtualBase;
4899 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4900 ConstructKind = CXXConstructExpr::CK_Delegating;
4901 }
4902
4903 // Only get the parenthesis range if it is a direct construction.
4904 SourceRange parenRange =
4905 Kind.getKind() == InitializationKind::IK_Direct ?
4906 Kind.getParenRange() : SourceRange();
4907
4908 // If the entity allows NRVO, mark the construction as elidable
4909 // unconditionally.
4910 if (Entity.allowsNRVO())
4911 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4912 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004913 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004914 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004915 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004916 ConstructorInitRequiresZeroInit,
4917 ConstructKind,
4918 parenRange);
4919 else
4920 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4921 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004922 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004923 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004924 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004925 ConstructorInitRequiresZeroInit,
4926 ConstructKind,
4927 parenRange);
4928 }
4929 if (CurInit.isInvalid())
4930 return ExprError();
4931
4932 // Only check access if all of that succeeded.
4933 S.CheckConstructorAccess(Loc, Constructor, Entity,
4934 Step.Function.FoundDecl.getAccess());
4935 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4936
4937 if (shouldBindAsTemporary(Entity))
4938 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4939
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004940 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004941}
4942
Richard Smith36d02af2012-06-04 22:27:30 +00004943/// Determine whether the specified InitializedEntity definitely has a lifetime
4944/// longer than the current full-expression. Conservatively returns false if
4945/// it's unclear.
4946static bool
4947InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4948 const InitializedEntity *Top = &Entity;
4949 while (Top->getParent())
4950 Top = Top->getParent();
4951
4952 switch (Top->getKind()) {
4953 case InitializedEntity::EK_Variable:
4954 case InitializedEntity::EK_Result:
4955 case InitializedEntity::EK_Exception:
4956 case InitializedEntity::EK_Member:
4957 case InitializedEntity::EK_New:
4958 case InitializedEntity::EK_Base:
4959 case InitializedEntity::EK_Delegating:
4960 return true;
4961
4962 case InitializedEntity::EK_ArrayElement:
4963 case InitializedEntity::EK_VectorElement:
4964 case InitializedEntity::EK_BlockElement:
4965 case InitializedEntity::EK_ComplexElement:
4966 // Could not determine what the full initialization is. Assume it might not
4967 // outlive the full-expression.
4968 return false;
4969
4970 case InitializedEntity::EK_Parameter:
4971 case InitializedEntity::EK_Temporary:
4972 case InitializedEntity::EK_LambdaCapture:
4973 // The entity being initialized might not outlive the full-expression.
4974 return false;
4975 }
4976
4977 llvm_unreachable("unknown entity kind");
4978}
4979
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004980ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004981InitializationSequence::Perform(Sema &S,
4982 const InitializedEntity &Entity,
4983 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004984 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004985 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004986 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004987 unsigned NumArgs = Args.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00004988 Diagnose(S, Entity, Kind, Args.data(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004989 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004990 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004991
Sebastian Redl7491c492011-06-05 13:59:11 +00004992 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004993 // If the declaration is a non-dependent, incomplete array type
4994 // that has an initializer, then its type will be completed once
4995 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004996 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004997 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004998 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004999 if (const IncompleteArrayType *ArrayT
5000 = S.Context.getAsIncompleteArrayType(DeclType)) {
5001 // FIXME: We don't currently have the ability to accurately
5002 // compute the length of an initializer list without
5003 // performing full type-checking of the initializer list
5004 // (since we have to determine where braces are implicitly
5005 // introduced and such). So, we fall back to making the array
5006 // type a dependently-sized array type with no specified
5007 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005008 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005009 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005010
Douglas Gregord87b61f2009-12-10 17:56:55 +00005011 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005012 if (DeclaratorDecl *DD = Entity.getDecl()) {
5013 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5014 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005015 if (IncompleteArrayTypeLoc ArrayLoc =
5016 TL.getAs<IncompleteArrayTypeLoc>())
5017 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005018 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005019 }
5020
5021 *ResultType
5022 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5023 /*NumElts=*/0,
5024 ArrayT->getSizeModifier(),
5025 ArrayT->getIndexTypeCVRQualifiers(),
5026 Brackets);
5027 }
5028
5029 }
5030 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005031 if (Kind.getKind() == InitializationKind::IK_Direct &&
5032 !Kind.isExplicitCast()) {
5033 // Rebuild the ParenListExpr.
5034 SourceRange ParenRange = Kind.getParenRange();
5035 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005036 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005037 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005038 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005039 Kind.isExplicitCast() ||
5040 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005041 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005042 }
5043
Sebastian Redl7491c492011-06-05 13:59:11 +00005044 // No steps means no initialization.
5045 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005046 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005047
Richard Smith80ad52f2013-01-02 11:42:31 +00005048 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005049 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005050 Entity.getKind() != InitializedEntity::EK_Parameter) {
5051 // Produce a C++98 compatibility warning if we are initializing a reference
5052 // from an initializer list. For parameters, we produce a better warning
5053 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005054 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005055 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5056 << Init->getSourceRange();
5057 }
5058
Richard Smith36d02af2012-06-04 22:27:30 +00005059 // Diagnose cases where we initialize a pointer to an array temporary, and the
5060 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005061 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005062 Entity.getType()->isPointerType() &&
5063 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005064 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005065 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5066 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5067 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5068 << Init->getSourceRange();
5069 }
5070
Douglas Gregord6542d82009-12-22 15:35:07 +00005071 QualType DestType = Entity.getType().getNonReferenceType();
5072 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005073 // the same as Entity.getDecl()->getType() in cases involving type merging,
5074 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005075 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005076 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005077 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005078
John McCall60d7b3a2010-08-24 06:29:42 +00005079 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005080
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005081 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005082 // grab the only argument out the Args and place it into the "current"
5083 // initializer.
5084 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005085 case SK_ResolveAddressOfOverloadedFunction:
5086 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005087 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005088 case SK_CastDerivedToBaseLValue:
5089 case SK_BindReference:
5090 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005091 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005092 case SK_UserConversion:
5093 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005094 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005095 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005096 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005097 case SK_ConversionSequence:
5098 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005099 case SK_UnwrapInitList:
5100 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005101 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005102 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005103 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005104 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005105 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005106 case SK_PassByIndirectCopyRestore:
5107 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005108 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005109 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005110 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005111 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005112 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005113 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005114 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005115 break;
John McCallf6a16482010-12-04 03:47:34 +00005116 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005117
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005118 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005119 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005120 case SK_ZeroInitialization:
5121 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005123
5124 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005125 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005126 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005127 for (step_iterator Step = step_begin(), StepEnd = step_end();
5128 Step != StepEnd; ++Step) {
5129 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005130 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005131
John Wiegley429bb272011-04-08 18:41:53 +00005132 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005133
Douglas Gregor20093b42009-12-09 23:02:17 +00005134 switch (Step->Kind) {
5135 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005136 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005137 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005138 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00005139 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005140 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005141 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005142 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005143 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005144
Douglas Gregor20093b42009-12-09 23:02:17 +00005145 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005146 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005147 case SK_CastDerivedToBaseLValue: {
5148 // We have a derived-to-base cast that produces either an rvalue or an
5149 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005150
John McCallf871d0c2010-08-07 06:22:56 +00005151 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005152
Douglas Gregor20093b42009-12-09 23:02:17 +00005153 // Casts to inaccessible base classes are allowed with C-style casts.
5154 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5155 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005156 CurInit.get()->getLocStart(),
5157 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005158 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005159 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005160
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005161 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5162 QualType T = SourceType;
5163 if (const PointerType *Pointer = T->getAs<PointerType>())
5164 T = Pointer->getPointeeType();
5165 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005166 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005167 cast<CXXRecordDecl>(RecordTy->getDecl()));
5168 }
5169
John McCall5baba9d2010-08-25 10:28:54 +00005170 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005171 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005172 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005173 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005174 VK_XValue :
5175 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005176 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5177 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005178 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005179 CurInit.get(),
5180 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005181 break;
5182 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005183
Douglas Gregor20093b42009-12-09 23:02:17 +00005184 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00005185 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005186 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
5187 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005188 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005189 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00005190 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00005191 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00005192 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005193 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005194
John Wiegley429bb272011-04-08 18:41:53 +00005195 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005196 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005197 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5198 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005199 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005200 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005201 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005203
Douglas Gregor20093b42009-12-09 23:02:17 +00005204 // Reference binding does not have any corresponding ASTs.
5205
5206 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005207 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005208 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005209
Douglas Gregor20093b42009-12-09 23:02:17 +00005210 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005211
Douglas Gregor20093b42009-12-09 23:02:17 +00005212 case SK_BindReferenceToTemporary:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005213 // Make sure the "temporary" is actually an rvalue.
5214 assert(CurInit.get()->isRValue() && "not a temporary");
5215
Douglas Gregor20093b42009-12-09 23:02:17 +00005216 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005217 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005218 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005219
Douglas Gregor03e80032011-06-21 17:03:29 +00005220 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005221 CurInit = new (S.Context) MaterializeTemporaryExpr(
5222 Entity.getType().getNonReferenceType(),
5223 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005224 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005225
5226 // If we're binding to an Objective-C object that has lifetime, we
5227 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005228 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005229 CurInit.get()->getType()->isObjCLifetimeType())
5230 S.ExprNeedsCleanups = true;
5231
Douglas Gregor20093b42009-12-09 23:02:17 +00005232 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005233
Douglas Gregor523d46a2010-04-18 07:40:54 +00005234 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005235 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005236 /*IsExtraneousCopy=*/true);
5237 break;
5238
Douglas Gregor20093b42009-12-09 23:02:17 +00005239 case SK_UserConversion: {
5240 // We have a user-defined conversion that invokes either a constructor
5241 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005242 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005243 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005244 FunctionDecl *Fn = Step->Function.Function;
5245 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005246 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005247 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005248 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005249 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005250 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005251 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005252 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005253
Douglas Gregor20093b42009-12-09 23:02:17 +00005254 // Determine the arguments required to actually perform the constructor
5255 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005256 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005257 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005258 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005259 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005260 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005261
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005262 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005263 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005264 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005265 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005266 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005267 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005268 CXXConstructExpr::CK_Complete,
5269 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005270 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005271 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005272
Anders Carlsson9a68a672010-04-21 18:47:17 +00005273 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005274 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00005275 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005276
John McCall2de56d12010-08-25 11:45:40 +00005277 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005278 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5279 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5280 S.IsDerivedFrom(SourceType, Class))
5281 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005282
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005283 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005284 } else {
5285 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005286 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005287 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005288 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00005289 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005290
5291 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005292 // derived-to-base conversion? I believe the answer is "no", because
5293 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005294 ExprResult CurInitExprRes =
5295 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5296 FoundFn, Conversion);
5297 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005298 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005299 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005300
Douglas Gregor20093b42009-12-09 23:02:17 +00005301 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005302 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5303 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005304 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005305 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005306
John McCall2de56d12010-08-25 11:45:40 +00005307 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005308
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005309 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005311
Sebastian Redl3b802322011-07-14 19:07:55 +00005312 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005313 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5314
5315 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005316 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005317 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005318 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005319 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005320 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005321 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005322 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley429bb272011-04-08 18:41:53 +00005323 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005324 }
5325 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005326
John McCallf871d0c2010-08-07 06:22:56 +00005327 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005328 CurInit.get()->getType(),
5329 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005330 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005331 if (MaybeBindToTemp)
5332 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005333 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005334 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005335 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005336 break;
5337 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005338
Douglas Gregor20093b42009-12-09 23:02:17 +00005339 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005340 case SK_QualificationConversionXValue:
5341 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005342 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005343 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005344 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005345 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005346 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005347 VK_XValue :
5348 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005349 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005350 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005351 }
5352
Jordan Rose1fd1e282013-04-11 00:58:58 +00005353 case SK_LValueToRValue: {
5354 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5355 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5356 CK_LValueToRValue,
5357 CurInit.take(),
5358 /*BasePath=*/0,
5359 VK_RValue));
5360 break;
5361 }
5362
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005363 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005364 Sema::CheckedConversionKind CCK
5365 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5366 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005367 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005368 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005369 ExprResult CurInitExprRes =
5370 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005371 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005372 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005373 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005374 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005375 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005377
Douglas Gregord87b61f2009-12-10 17:56:55 +00005378 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005379 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005380 // Hack: We must pass *ResultType if available in order to set the type
5381 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5382 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5383 // temporary, not a reference, so we should pass Ty.
5384 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5385 // Since this step is never used for a reference directly, we explicitly
5386 // unwrap references here and rewrap them afterwards.
5387 // We also need to create a InitializeTemporary entity for this.
5388 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005389 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005390 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005391 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5392 InitListChecker PerformInitList(S, InitEntity,
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005393 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005394 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00005395 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005396 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005397 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005398
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005399 if (ResultType) {
5400 if ((*ResultType)->isRValueReferenceType())
5401 Ty = S.Context.getRValueReferenceType(Ty);
5402 else if ((*ResultType)->isLValueReferenceType())
5403 Ty = S.Context.getLValueReferenceType(Ty,
5404 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5405 *ResultType = Ty;
5406 }
5407
5408 InitListExpr *StructuredInitList =
5409 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005410 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005411 CurInit = shouldBindAsTemporary(InitEntity)
5412 ? S.MaybeBindToTemporary(StructuredInitList)
5413 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005414 break;
5415 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005416
Sebastian Redl10f04a62011-12-22 14:44:04 +00005417 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005418 // When an initializer list is passed for a parameter of type "reference
5419 // to object", we don't get an EK_Temporary entity, but instead an
5420 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005421 // FIXME: This is a hack. What we really should do is create a user
5422 // conversion step for this case, but this makes it considerably more
5423 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005424 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5425 Entity.getType().getNonReferenceType());
5426 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005427 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005428 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005429 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5430 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005431 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005432 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5433 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005434 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005435 ConstructorInitRequiresZeroInit,
5436 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005437 break;
5438 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005439
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005440 case SK_UnwrapInitList:
5441 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5442 break;
5443
5444 case SK_RewrapInitList: {
5445 Expr *E = CurInit.take();
5446 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5447 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005448 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005449 ILE->setSyntacticForm(Syntactic);
5450 ILE->setType(E->getType());
5451 ILE->setValueKind(E->getValueKind());
5452 CurInit = S.Owned(ILE);
5453 break;
5454 }
5455
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005456 case SK_ConstructorInitialization: {
5457 // When an initializer list is passed for a parameter of type "reference
5458 // to object", we don't get an EK_Temporary entity, but instead an
5459 // EK_Parameter entity with reference type.
5460 // FIXME: This is a hack. What we really should do is create a user
5461 // conversion step for this case, but this makes it considerably more
5462 // complicated. For now, this will do.
5463 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5464 Entity.getType().getNonReferenceType());
5465 bool UseTemporary = Entity.getType()->isReferenceType();
5466 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5467 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005468 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005469 ConstructorInitRequiresZeroInit,
5470 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005471 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005472 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005473
Douglas Gregor71d17402009-12-15 00:01:57 +00005474 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005475 step_iterator NextStep = Step;
5476 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005477 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005478 (NextStep->Kind == SK_ConstructorInitialization ||
5479 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005480 // The need for zero-initialization is recorded directly into
5481 // the call to the object's constructor within the next step.
5482 ConstructorInitRequiresZeroInit = true;
5483 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005484 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005485 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005486 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5487 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005488 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005489 Kind.getRange().getBegin());
5490
5491 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5492 TSInfo->getType().getNonLValueExprType(S.Context),
5493 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005494 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005495 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005496 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005497 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005498 break;
5499 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005500
5501 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005502 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005503 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005504 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005505 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5506 if (Result.isInvalid())
5507 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005508 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005509
5510 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005511 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005512 if (ConvTy != Sema::Compatible &&
5513 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005514 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005515 == Sema::Compatible)
5516 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005517 if (CurInitExprRes.isInvalid())
5518 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005519 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005520
Douglas Gregora41a8c52010-04-22 00:20:18 +00005521 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005522 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5523 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005524 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005525 getAssignmentAction(Entity),
5526 &Complained)) {
5527 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005528 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005529 } else if (Complained)
5530 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005531 break;
5532 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005533
5534 case SK_StringInit: {
5535 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005536 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005537 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005538 break;
5539 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005540
5541 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005542 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005543 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005544 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005545 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005546
5547 case SK_ArrayInit:
5548 // Okay: we checked everything before creating this step. Note that
5549 // this is a GNU extension.
5550 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005551 << Step->Type << CurInit.get()->getType()
5552 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005553
5554 // If the destination type is an incomplete array type, update the
5555 // type accordingly.
5556 if (ResultType) {
5557 if (const IncompleteArrayType *IncompleteDest
5558 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5559 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005560 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005561 *ResultType = S.Context.getConstantArrayType(
5562 IncompleteDest->getElementType(),
5563 ConstantSource->getSize(),
5564 ArrayType::Normal, 0);
5565 }
5566 }
5567 }
John McCallf85e1932011-06-15 23:02:42 +00005568 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005569
Richard Smith0f163e92012-02-15 22:38:09 +00005570 case SK_ParenthesizedArrayInit:
5571 // Okay: we checked everything before creating this step. Note that
5572 // this is a GNU extension.
5573 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5574 << CurInit.get()->getSourceRange();
5575 break;
5576
John McCallf85e1932011-06-15 23:02:42 +00005577 case SK_PassByIndirectCopyRestore:
5578 case SK_PassByIndirectRestore:
5579 checkIndirectCopyRestoreSource(S, CurInit.get());
5580 CurInit = S.Owned(new (S.Context)
5581 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5582 Step->Kind == SK_PassByIndirectCopyRestore));
5583 break;
5584
5585 case SK_ProduceObjCObject:
5586 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005587 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005588 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005589 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005590
5591 case SK_StdInitializerList: {
5592 QualType Dest = Step->Type;
5593 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005594 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005595 (void)Success;
5596 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005597
5598 // If the element type has a destructor, check it.
5599 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5600 if (!RD->hasIrrelevantDestructor()) {
5601 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5602 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5603 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5604 S.PDiag(diag::err_access_dtor_temp) << E);
5605 S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5606 }
5607 }
5608 }
5609
Sebastian Redl2b916b82012-01-17 22:49:42 +00005610 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005611 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5612 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005613 unsigned NumInits = ILE->getNumInits();
5614 SmallVector<Expr*, 16> Converted(NumInits);
5615 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5616 S.Context.getConstantArrayType(E,
5617 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5618 NumInits),
5619 ArrayType::Normal, 0));
5620 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5621 0, HiddenArray);
5622 for (unsigned i = 0; i < NumInits; ++i) {
5623 Element.setElementIndex(i);
5624 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005625 ExprResult Res = S.PerformCopyInitialization(
5626 Element, Init.get()->getExprLoc(), Init,
5627 /*TopLevelOfInitList=*/ true);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005628 assert(!Res.isInvalid() && "Result changed since try phase.");
5629 Converted[i] = Res.take();
5630 }
5631 InitListExpr *Semantic = new (S.Context)
5632 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005633 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005634 Semantic->setSyntacticForm(ILE);
5635 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005636 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005637 CurInit = S.Owned(Semantic);
5638 break;
5639 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005640 case SK_OCLSamplerInit: {
5641 assert(Step->Type->isSamplerT() &&
5642 "Sampler initialization on non sampler type.");
5643
5644 QualType SourceType = CurInit.get()->getType();
5645 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5646
5647 if (EntityKind == InitializedEntity::EK_Parameter) {
5648 if (!SourceType->isSamplerT())
5649 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5650 << SourceType;
5651 } else if (EntityKind != InitializedEntity::EK_Variable) {
5652 llvm_unreachable("Invalid EntityKind!");
5653 }
5654
5655 break;
5656 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005657 case SK_OCLZeroEvent: {
5658 assert(Step->Type->isEventT() &&
5659 "Event initialization on non event type.");
5660
5661 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5662 CK_ZeroToOCLEvent,
5663 CurInit.get()->getValueKind());
5664 break;
5665 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005666 }
5667 }
John McCall15d7d122010-11-11 03:21:53 +00005668
5669 // Diagnose non-fatal problems with the completed initialization.
5670 if (Entity.getKind() == InitializedEntity::EK_Member &&
5671 cast<FieldDecl>(Entity.getDecl())->isBitField())
5672 S.CheckBitFieldInitialization(Kind.getLocation(),
5673 cast<FieldDecl>(Entity.getDecl()),
5674 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005675
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005676 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005677}
5678
Richard Smithd5bc8672012-12-08 02:01:17 +00005679/// Somewhere within T there is an uninitialized reference subobject.
5680/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005681static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5682 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005683 if (T->isReferenceType()) {
5684 S.Diag(Loc, diag::err_reference_without_init)
5685 << T.getNonReferenceType();
5686 return true;
5687 }
5688
5689 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5690 if (!RD || !RD->hasUninitializedReferenceMember())
5691 return false;
5692
5693 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5694 FE = RD->field_end(); FI != FE; ++FI) {
5695 if (FI->isUnnamedBitfield())
5696 continue;
5697
5698 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5699 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5700 return true;
5701 }
5702 }
5703
5704 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5705 BE = RD->bases_end();
5706 BI != BE; ++BI) {
5707 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5708 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5709 return true;
5710 }
5711 }
5712
5713 return false;
5714}
5715
5716
Douglas Gregor20093b42009-12-09 23:02:17 +00005717//===----------------------------------------------------------------------===//
5718// Diagnose initialization failures
5719//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00005720
5721/// Emit notes associated with an initialization that failed due to a
5722/// "simple" conversion failure.
5723static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5724 Expr *op) {
5725 QualType destType = entity.getType();
5726 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5727 op->getType()->isObjCObjectPointerType()) {
5728
5729 // Emit a possible note about the conversion failing because the
5730 // operand is a message send with a related result type.
5731 S.EmitRelatedResultTypeNote(op);
5732
5733 // Emit a possible note about a return failing because we're
5734 // expecting a related result type.
5735 if (entity.getKind() == InitializedEntity::EK_Result)
5736 S.EmitRelatedResultTypeNoteForReturn(destType);
5737 }
5738}
5739
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005740bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005741 const InitializedEntity &Entity,
5742 const InitializationKind &Kind,
5743 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005744 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005745 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005746
Douglas Gregord6542d82009-12-22 15:35:07 +00005747 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005748 switch (Failure) {
5749 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005750 // FIXME: Customize for the initialized entity?
Richard Smithd5bc8672012-12-08 02:01:17 +00005751 if (NumArgs == 0) {
5752 // Dig out the reference subobject which is uninitialized and diagnose it.
5753 // If this is value-initialization, this could be nested some way within
5754 // the target type.
5755 assert(Kind.getKind() == InitializationKind::IK_Value ||
5756 DestType->isReferenceType());
5757 bool Diagnosed =
5758 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5759 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5760 (void)Diagnosed;
5761 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005762 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5763 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005764 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005765
Douglas Gregor20093b42009-12-09 23:02:17 +00005766 case FK_ArrayNeedsInitList:
5767 case FK_ArrayNeedsInitListOrStringLiteral:
5768 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5769 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5770 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005771
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005772 case FK_ArrayTypeMismatch:
5773 case FK_NonConstantArrayInit:
5774 S.Diag(Kind.getLocation(),
5775 (Failure == FK_ArrayTypeMismatch
5776 ? diag::err_array_init_different_type
5777 : diag::err_array_init_non_constant_array))
5778 << DestType.getNonReferenceType()
5779 << Args[0]->getType()
5780 << Args[0]->getSourceRange();
5781 break;
5782
John McCall73076432012-01-05 00:13:19 +00005783 case FK_VariableLengthArrayHasInitializer:
5784 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5785 << Args[0]->getSourceRange();
5786 break;
5787
John McCall6bb80172010-03-30 21:47:33 +00005788 case FK_AddressOfOverloadFailed: {
5789 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005790 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005791 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005792 true,
5793 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005794 break;
John McCall6bb80172010-03-30 21:47:33 +00005795 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005796
Douglas Gregor20093b42009-12-09 23:02:17 +00005797 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005798 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005799 switch (FailedOverloadResult) {
5800 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005801 if (Failure == FK_UserConversionOverloadFailed)
5802 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5803 << Args[0]->getType() << DestType
5804 << Args[0]->getSourceRange();
5805 else
5806 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5807 << DestType << Args[0]->getType()
5808 << Args[0]->getSourceRange();
5809
Ahmed Charles13a140c2012-02-25 11:00:22 +00005810 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5811 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005812 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005813
Douglas Gregor20093b42009-12-09 23:02:17 +00005814 case OR_No_Viable_Function:
5815 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5816 << Args[0]->getType() << DestType.getNonReferenceType()
5817 << Args[0]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005818 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5819 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005820 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005821
Douglas Gregor20093b42009-12-09 23:02:17 +00005822 case OR_Deleted: {
5823 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5824 << Args[0]->getType() << DestType.getNonReferenceType()
5825 << Args[0]->getSourceRange();
5826 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005827 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005828 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5829 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005830 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005831 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005832 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005833 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005834 }
5835 break;
5836 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005837
Douglas Gregor20093b42009-12-09 23:02:17 +00005838 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005839 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005840 }
5841 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005842
Douglas Gregor20093b42009-12-09 23:02:17 +00005843 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005844 if (isa<InitListExpr>(Args[0])) {
5845 S.Diag(Kind.getLocation(),
5846 diag::err_lvalue_reference_bind_to_initlist)
5847 << DestType.getNonReferenceType().isVolatileQualified()
5848 << DestType.getNonReferenceType()
5849 << Args[0]->getSourceRange();
5850 break;
5851 }
5852 // Intentional fallthrough
5853
Douglas Gregor20093b42009-12-09 23:02:17 +00005854 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005855 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005856 Failure == FK_NonConstLValueReferenceBindingToTemporary
5857 ? diag::err_lvalue_reference_bind_to_temporary
5858 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005859 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005860 << DestType.getNonReferenceType()
5861 << Args[0]->getType()
5862 << Args[0]->getSourceRange();
5863 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005864
Douglas Gregor20093b42009-12-09 23:02:17 +00005865 case FK_RValueReferenceBindingToLValue:
5866 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005867 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005868 << Args[0]->getSourceRange();
5869 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005870
Douglas Gregor20093b42009-12-09 23:02:17 +00005871 case FK_ReferenceInitDropsQualifiers:
5872 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5873 << DestType.getNonReferenceType()
5874 << Args[0]->getType()
5875 << Args[0]->getSourceRange();
5876 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005877
Douglas Gregor20093b42009-12-09 23:02:17 +00005878 case FK_ReferenceInitFailed:
5879 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5880 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005881 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005882 << Args[0]->getType()
5883 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00005884 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005885 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005886
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005887 case FK_ConversionFailed: {
5888 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005889 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005890 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005891 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005892 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005893 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005894 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005895 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5896 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00005897 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005898 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005899 }
John Wiegley429bb272011-04-08 18:41:53 +00005900
5901 case FK_ConversionFromPropertyFailed:
5902 // No-op. This error has already been reported.
5903 break;
5904
Douglas Gregord87b61f2009-12-10 17:56:55 +00005905 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005906 SourceRange R;
5907
5908 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005909 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005910 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005911 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005912 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005913
Douglas Gregor19311e72010-09-08 21:40:08 +00005914 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5915 if (Kind.isCStyleOrFunctionalCast())
5916 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5917 << R;
5918 else
5919 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5920 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005921 break;
5922 }
5923
5924 case FK_ReferenceBindingToInitList:
5925 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5926 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5927 break;
5928
5929 case FK_InitListBadDestinationType:
5930 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5931 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5932 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005933
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005934 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005935 case FK_ConstructorOverloadFailed: {
5936 SourceRange ArgsRange;
5937 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005938 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005939 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005940
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005941 if (Failure == FK_ListConstructorOverloadFailed) {
5942 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5943 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5944 Args = InitList->getInits();
5945 NumArgs = InitList->getNumInits();
5946 }
5947
Douglas Gregor51c56d62009-12-14 20:49:26 +00005948 // FIXME: Using "DestType" for the entity we're printing is probably
5949 // bad.
5950 switch (FailedOverloadResult) {
5951 case OR_Ambiguous:
5952 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5953 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005954 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005955 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00005956 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005957
Douglas Gregor51c56d62009-12-14 20:49:26 +00005958 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005959 if (Kind.getKind() == InitializationKind::IK_Default &&
5960 (Entity.getKind() == InitializedEntity::EK_Base ||
5961 Entity.getKind() == InitializedEntity::EK_Member) &&
5962 isa<CXXConstructorDecl>(S.CurContext)) {
5963 // This is implicit default initialization of a member or
5964 // base within a constructor. If no viable function was
5965 // found, notify the user that she needs to explicitly
5966 // initialize this base/member.
5967 CXXConstructorDecl *Constructor
5968 = cast<CXXConstructorDecl>(S.CurContext);
5969 if (Entity.getKind() == InitializedEntity::EK_Base) {
5970 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00005971 << (Constructor->getInheritedConstructor() ? 2 :
5972 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005973 << S.Context.getTypeDeclType(Constructor->getParent())
5974 << /*base=*/0
5975 << Entity.getType();
5976
5977 RecordDecl *BaseDecl
5978 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5979 ->getDecl();
5980 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5981 << S.Context.getTagDeclType(BaseDecl);
5982 } else {
5983 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00005984 << (Constructor->getInheritedConstructor() ? 2 :
5985 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005986 << S.Context.getTypeDeclType(Constructor->getParent())
5987 << /*member=*/1
5988 << Entity.getName();
5989 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5990
5991 if (const RecordType *Record
5992 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005993 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005994 diag::note_previous_decl)
5995 << S.Context.getTagDeclType(Record->getDecl());
5996 }
5997 break;
5998 }
5999
Douglas Gregor51c56d62009-12-14 20:49:26 +00006000 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6001 << DestType << ArgsRange;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006002 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
6003 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00006004 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006005
Douglas Gregor51c56d62009-12-14 20:49:26 +00006006 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006007 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006008 OverloadingResult Ovl
6009 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006010 if (Ovl != OR_Deleted) {
6011 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6012 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006013 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006014 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006015 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006016
6017 // If this is a defaulted or implicitly-declared function, then
6018 // it was implicitly deleted. Make it clear that the deletion was
6019 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006020 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006021 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006022 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006023 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006024 else
6025 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6026 << true << DestType << ArgsRange;
6027
6028 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006029 break;
6030 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006031
Douglas Gregor51c56d62009-12-14 20:49:26 +00006032 case OR_Success:
6033 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006034 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006035 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006036 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006037
Douglas Gregor99a2e602009-12-16 01:38:02 +00006038 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006039 if (Entity.getKind() == InitializedEntity::EK_Member &&
6040 isa<CXXConstructorDecl>(S.CurContext)) {
6041 // This is implicit default-initialization of a const member in
6042 // a constructor. Complain that it needs to be explicitly
6043 // initialized.
6044 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6045 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006046 << (Constructor->getInheritedConstructor() ? 2 :
6047 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006048 << S.Context.getTypeDeclType(Constructor->getParent())
6049 << /*const=*/1
6050 << Entity.getName();
6051 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6052 << Entity.getName();
6053 } else {
6054 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6055 << DestType << (bool)DestType->getAs<RecordType>();
6056 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006057 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006058
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006059 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006060 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006061 diag::err_init_incomplete_type);
6062 break;
6063
Sebastian Redl14b0c192011-09-24 17:48:00 +00006064 case FK_ListInitializationFailed: {
6065 // Run the init list checker again to emit diagnostics.
6066 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6067 QualType DestType = Entity.getType();
6068 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00006069 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00006070 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00006071 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006072 assert(DiagnoseInitList.HadError() &&
6073 "Inconsistent init list check result.");
6074 break;
6075 }
John McCall5acb0c92011-10-17 18:40:02 +00006076
6077 case FK_PlaceholderType: {
6078 // FIXME: Already diagnosed!
6079 break;
6080 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006081
6082 case FK_InitListElementCopyFailure: {
6083 // Try to perform all copies again.
6084 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6085 unsigned NumInits = InitList->getNumInits();
6086 QualType DestType = Entity.getType();
6087 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006088 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006089 (void)Success;
6090 assert(Success && "Where did the std::initializer_list go?");
6091 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6092 S.Context.getConstantArrayType(E,
6093 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6094 NumInits),
6095 ArrayType::Normal, 0));
6096 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6097 0, HiddenArray);
6098 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6099 // where the init list type is wrong, e.g.
6100 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6101 // FIXME: Emit a note if we hit the limit?
6102 int ErrorCount = 0;
6103 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6104 Element.setElementIndex(i);
6105 ExprResult Init = S.Owned(InitList->getInit(i));
6106 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6107 .isInvalid())
6108 ++ErrorCount;
6109 }
6110 break;
6111 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006112
6113 case FK_ExplicitConstructor: {
6114 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6115 << Args[0]->getSourceRange();
6116 OverloadCandidateSet::iterator Best;
6117 OverloadingResult Ovl
6118 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006119 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006120 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6121 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6122 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6123 break;
6124 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006125 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006126
Douglas Gregora41a8c52010-04-22 00:20:18 +00006127 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006128 return true;
6129}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006130
Chris Lattner5f9e2722011-07-23 10:55:15 +00006131void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006132 switch (SequenceKind) {
6133 case FailedSequence: {
6134 OS << "Failed sequence: ";
6135 switch (Failure) {
6136 case FK_TooManyInitsForReference:
6137 OS << "too many initializers for reference";
6138 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006139
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006140 case FK_ArrayNeedsInitList:
6141 OS << "array requires initializer list";
6142 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006143
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006144 case FK_ArrayNeedsInitListOrStringLiteral:
6145 OS << "array requires initializer list or string literal";
6146 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006147
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006148 case FK_ArrayTypeMismatch:
6149 OS << "array type mismatch";
6150 break;
6151
6152 case FK_NonConstantArrayInit:
6153 OS << "non-constant array initializer";
6154 break;
6155
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006156 case FK_AddressOfOverloadFailed:
6157 OS << "address of overloaded function failed";
6158 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006159
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006160 case FK_ReferenceInitOverloadFailed:
6161 OS << "overload resolution for reference initialization failed";
6162 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006163
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006164 case FK_NonConstLValueReferenceBindingToTemporary:
6165 OS << "non-const lvalue reference bound to temporary";
6166 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006167
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006168 case FK_NonConstLValueReferenceBindingToUnrelated:
6169 OS << "non-const lvalue reference bound to unrelated type";
6170 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006171
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006172 case FK_RValueReferenceBindingToLValue:
6173 OS << "rvalue reference bound to an lvalue";
6174 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006175
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006176 case FK_ReferenceInitDropsQualifiers:
6177 OS << "reference initialization drops qualifiers";
6178 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006179
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006180 case FK_ReferenceInitFailed:
6181 OS << "reference initialization failed";
6182 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006183
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006184 case FK_ConversionFailed:
6185 OS << "conversion failed";
6186 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006187
John Wiegley429bb272011-04-08 18:41:53 +00006188 case FK_ConversionFromPropertyFailed:
6189 OS << "conversion from property failed";
6190 break;
6191
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006192 case FK_TooManyInitsForScalar:
6193 OS << "too many initializers for scalar";
6194 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006195
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006196 case FK_ReferenceBindingToInitList:
6197 OS << "referencing binding to initializer list";
6198 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006199
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006200 case FK_InitListBadDestinationType:
6201 OS << "initializer list for non-aggregate, non-scalar type";
6202 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006203
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006204 case FK_UserConversionOverloadFailed:
6205 OS << "overloading failed for user-defined conversion";
6206 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006207
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006208 case FK_ConstructorOverloadFailed:
6209 OS << "constructor overloading failed";
6210 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006211
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006212 case FK_DefaultInitOfConst:
6213 OS << "default initialization of a const variable";
6214 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006215
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006216 case FK_Incomplete:
6217 OS << "initialization of incomplete type";
6218 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006219
6220 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006221 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006222 break;
6223
John McCall73076432012-01-05 00:13:19 +00006224 case FK_VariableLengthArrayHasInitializer:
6225 OS << "variable length array has an initializer";
6226 break;
6227
John McCall5acb0c92011-10-17 18:40:02 +00006228 case FK_PlaceholderType:
6229 OS << "initializer expression isn't contextually valid";
6230 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006231
6232 case FK_ListConstructorOverloadFailed:
6233 OS << "list constructor overloading failed";
6234 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006235
6236 case FK_InitListElementCopyFailure:
6237 OS << "copy construction of initializer list element failed";
6238 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006239
6240 case FK_ExplicitConstructor:
6241 OS << "list copy initialization chose explicit constructor";
6242 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006243 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006244 OS << '\n';
6245 return;
6246 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006247
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006248 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006249 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006250 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006251
Sebastian Redl7491c492011-06-05 13:59:11 +00006252 case NormalSequence:
6253 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006254 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006256
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006257 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6258 if (S != step_begin()) {
6259 OS << " -> ";
6260 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006261
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006262 switch (S->Kind) {
6263 case SK_ResolveAddressOfOverloadedFunction:
6264 OS << "resolve address of overloaded function";
6265 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006266
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006267 case SK_CastDerivedToBaseRValue:
6268 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6269 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006270
Sebastian Redl906082e2010-07-20 04:20:21 +00006271 case SK_CastDerivedToBaseXValue:
6272 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6273 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006274
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006275 case SK_CastDerivedToBaseLValue:
6276 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6277 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006278
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006279 case SK_BindReference:
6280 OS << "bind reference to lvalue";
6281 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006282
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006283 case SK_BindReferenceToTemporary:
6284 OS << "bind reference to a temporary";
6285 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006286
Douglas Gregor523d46a2010-04-18 07:40:54 +00006287 case SK_ExtraneousCopyToTemporary:
6288 OS << "extraneous C++03 copy to temporary";
6289 break;
6290
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006291 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006292 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006293 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006294
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006295 case SK_QualificationConversionRValue:
6296 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006297 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006298
Sebastian Redl906082e2010-07-20 04:20:21 +00006299 case SK_QualificationConversionXValue:
6300 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006301 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006302
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006303 case SK_QualificationConversionLValue:
6304 OS << "qualification conversion (lvalue)";
6305 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006306
Jordan Rose1fd1e282013-04-11 00:58:58 +00006307 case SK_LValueToRValue:
6308 OS << "load (lvalue to rvalue)";
6309 break;
6310
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006311 case SK_ConversionSequence:
6312 OS << "implicit conversion sequence (";
6313 S->ICS->DebugPrint(); // FIXME: use OS
6314 OS << ")";
6315 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006316
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006317 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006318 OS << "list aggregate initialization";
6319 break;
6320
6321 case SK_ListConstructorCall:
6322 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006323 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006324
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006325 case SK_UnwrapInitList:
6326 OS << "unwrap reference initializer list";
6327 break;
6328
6329 case SK_RewrapInitList:
6330 OS << "rewrap reference initializer list";
6331 break;
6332
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006333 case SK_ConstructorInitialization:
6334 OS << "constructor initialization";
6335 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006336
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006337 case SK_ZeroInitialization:
6338 OS << "zero initialization";
6339 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006340
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006341 case SK_CAssignment:
6342 OS << "C assignment";
6343 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006344
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006345 case SK_StringInit:
6346 OS << "string initialization";
6347 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006348
6349 case SK_ObjCObjectConversion:
6350 OS << "Objective-C object conversion";
6351 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006352
6353 case SK_ArrayInit:
6354 OS << "array initialization";
6355 break;
John McCallf85e1932011-06-15 23:02:42 +00006356
Richard Smith0f163e92012-02-15 22:38:09 +00006357 case SK_ParenthesizedArrayInit:
6358 OS << "parenthesized array initialization";
6359 break;
6360
John McCallf85e1932011-06-15 23:02:42 +00006361 case SK_PassByIndirectCopyRestore:
6362 OS << "pass by indirect copy and restore";
6363 break;
6364
6365 case SK_PassByIndirectRestore:
6366 OS << "pass by indirect restore";
6367 break;
6368
6369 case SK_ProduceObjCObject:
6370 OS << "Objective-C object retension";
6371 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006372
6373 case SK_StdInitializerList:
6374 OS << "std::initializer_list from initializer list";
6375 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006376
Guy Benyei21f18c42013-02-07 10:55:47 +00006377 case SK_OCLSamplerInit:
6378 OS << "OpenCL sampler_t from integer constant";
6379 break;
6380
Guy Benyeie6b9d802013-01-20 12:31:11 +00006381 case SK_OCLZeroEvent:
6382 OS << "OpenCL event_t from zero";
6383 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006384 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006385
6386 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006387 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006388
6389 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006390}
6391
6392void InitializationSequence::dump() const {
6393 dump(llvm::errs());
6394}
6395
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006396static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6397 QualType EntityType,
6398 const Expr *PreInit,
6399 const Expr *PostInit) {
6400 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6401 return;
6402
6403 // A narrowing conversion can only appear as the final implicit conversion in
6404 // an initialization sequence.
6405 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6406 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6407 return;
6408
6409 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6410 const StandardConversionSequence *SCS = 0;
6411 switch (ICS.getKind()) {
6412 case ImplicitConversionSequence::StandardConversion:
6413 SCS = &ICS.Standard;
6414 break;
6415 case ImplicitConversionSequence::UserDefinedConversion:
6416 SCS = &ICS.UserDefined.After;
6417 break;
6418 case ImplicitConversionSequence::AmbiguousConversion:
6419 case ImplicitConversionSequence::EllipsisConversion:
6420 case ImplicitConversionSequence::BadConversion:
6421 return;
6422 }
6423
6424 // Determine the type prior to the narrowing conversion. If a conversion
6425 // operator was used, this may be different from both the type of the entity
6426 // and of the pre-initialization expression.
6427 QualType PreNarrowingType = PreInit->getType();
6428 if (Seq.step_begin() + 1 != Seq.step_end())
6429 PreNarrowingType = Seq.step_end()[-2].Type;
6430
6431 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6432 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006433 QualType ConstantType;
6434 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6435 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006436 case NK_Not_Narrowing:
6437 // No narrowing occurred.
6438 return;
6439
6440 case NK_Type_Narrowing:
6441 // This was a floating-to-integer conversion, which is always considered a
6442 // narrowing conversion even if the value is a constant and can be
6443 // represented exactly as an integer.
6444 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006445 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006446 diag::warn_init_list_type_narrowing
6447 : S.isSFINAEContext()?
6448 diag::err_init_list_type_narrowing_sfinae
6449 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006450 << PostInit->getSourceRange()
6451 << PreNarrowingType.getLocalUnqualifiedType()
6452 << EntityType.getLocalUnqualifiedType();
6453 break;
6454
6455 case NK_Constant_Narrowing:
6456 // A constant value was narrowed.
6457 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006458 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006459 diag::warn_init_list_constant_narrowing
6460 : S.isSFINAEContext()?
6461 diag::err_init_list_constant_narrowing_sfinae
6462 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006463 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006464 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006465 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006466 break;
6467
6468 case NK_Variable_Narrowing:
6469 // A variable's value may have been narrowed.
6470 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006471 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006472 diag::warn_init_list_variable_narrowing
6473 : S.isSFINAEContext()?
6474 diag::err_init_list_variable_narrowing_sfinae
6475 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006476 << PostInit->getSourceRange()
6477 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006478 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006479 break;
6480 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006481
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006482 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006483 llvm::raw_svector_ostream OS(StaticCast);
6484 OS << "static_cast<";
6485 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6486 // It's important to use the typedef's name if there is one so that the
6487 // fixit doesn't break code using types like int64_t.
6488 //
6489 // FIXME: This will break if the typedef requires qualification. But
6490 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006491 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006492 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006493 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006494 else {
6495 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6496 // with a broken cast.
6497 return;
6498 }
6499 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006500 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6501 << PostInit->getSourceRange()
6502 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006503 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006504 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006505}
6506
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006507//===----------------------------------------------------------------------===//
6508// Initialization helper functions
6509//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006510bool
6511Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6512 ExprResult Init) {
6513 if (Init.isInvalid())
6514 return false;
6515
6516 Expr *InitE = Init.get();
6517 assert(InitE && "No initialization expression");
6518
Douglas Gregor3c394c52012-07-31 22:15:04 +00006519 InitializationKind Kind
6520 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Sean Hunt2be7e902011-05-12 22:46:29 +00006521 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00006522 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006523}
6524
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006525ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006526Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6527 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006528 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006529 bool TopLevelOfInitList,
6530 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006531 if (Init.isInvalid())
6532 return ExprError();
6533
John McCall15d7d122010-11-11 03:21:53 +00006534 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006535 assert(InitE && "No initialization expression?");
6536
6537 if (EqualLoc.isInvalid())
6538 EqualLoc = InitE->getLocStart();
6539
6540 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006541 EqualLoc,
6542 AllowExplicit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006543 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6544 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006545
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006546 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6547
6548 if (!Result.isInvalid() && TopLevelOfInitList)
6549 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6550 InitE, Result.get());
6551
6552 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006553}