blob: 08536fbc219e0ef66ac421d4cc8747f4e2e5cbb2 [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
Richard Smith30ae1ed2013-05-05 16:40:13 +000085/// Update the type of a string literal, including any surrounding parentheses,
86/// to match the type of the object which it is initializing.
87static void updateStringLiteralType(Expr *E, QualType Ty) {
88 while (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
89 E->setType(Ty);
90 E = PE->getSubExpr();
91 }
92 assert(isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E));
93 E->setType(Ty);
94}
95
John McCallfef8b342011-02-21 07:57:55 +000096static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
97 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000098 // Get the length of the string as parsed.
99 uint64_t StrLength =
100 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
101
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000103 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000104 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000105 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +0000106 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000107 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000108 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
109 ConstVal,
110 ArrayType::Normal, 0);
Richard Smith30ae1ed2013-05-05 16:40:13 +0000111 updateStringLiteralType(Str, DeclT);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000112 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Eli Friedman8718a6a2009-05-29 18:22:49 +0000115 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000117 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000118 // the size may be smaller or larger than the string we are initializing.
119 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000120 if (S.getLangOpts().CPlusPlus) {
Richard Smith30ae1ed2013-05-05 16:40:13 +0000121 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000122 // For Pascal strings it's OK to strip off the terminating null character,
123 // so the example below is valid:
124 //
125 // unsigned char a[2] = "\pa";
126 if (SL->isPascal())
127 StrLength--;
128 }
129
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000130 // [dcl.init.string]p2
131 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000132 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000133 diag::err_initializer_string_for_char_array_too_long)
134 << Str->getSourceRange();
135 } else {
136 // C99 6.7.8p14.
137 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000138 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000139 diag::warn_initializer_string_for_char_array_too_long)
140 << Str->getSourceRange();
141 }
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Eli Friedman8718a6a2009-05-29 18:22:49 +0000143 // Set the type to the actual size that we are initializing. If we have
144 // something like:
145 // char x[1] = "foo";
146 // then this will set the string literal's type to char[1].
Richard Smith30ae1ed2013-05-05 16:40:13 +0000147 updateStringLiteralType(Str, DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000148}
149
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000150//===----------------------------------------------------------------------===//
151// Semantic checking for initializer lists.
152//===----------------------------------------------------------------------===//
153
Douglas Gregor9e80f722009-01-29 01:05:33 +0000154/// @brief Semantic checking for initializer lists.
155///
156/// The InitListChecker class contains a set of routines that each
157/// handle the initialization of a certain kind of entity, e.g.,
158/// arrays, vectors, struct/union types, scalars, etc. The
159/// InitListChecker itself performs a recursive walk of the subobject
160/// structure of the type to be initialized, while stepping through
161/// the initializer list one element at a time. The IList and Index
162/// parameters to each of the Check* routines contain the active
163/// (syntactic) initializer list and the index into that initializer
164/// list that represents the current initializer. Each routine is
165/// responsible for moving that Index forward as it consumes elements.
166///
167/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000168/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000169/// initializer list and the index into that initializer list where we
170/// are copying initializers as we map them over to the semantic
171/// list. Once we have completed our recursive walk of the subobject
172/// structure, we will have constructed a full semantic initializer
173/// list.
174///
175/// C99 designators cause changes in the initializer list traversal,
176/// because they make the initialization "jump" into a specific
177/// subobject and then continue the initialization from that
178/// point. CheckDesignatedInitializer() recursively steps into the
179/// designated subobject and manages backing out the recursion to
180/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000181namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000182class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000183 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000184 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000185 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000186 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000187 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000188 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000190 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000191 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000192 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000193 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000196 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000197 unsigned &StructuredIndex,
198 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000199 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000200 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000201 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000202 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000203 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000204 unsigned &StructuredIndex,
205 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000206 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000207 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000208 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000209 InitListExpr *StructuredList,
210 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000211 void CheckComplexType(const InitializedEntity &Entity,
212 InitListExpr *IList, QualType DeclType,
213 unsigned &Index,
214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000216 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000217 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000218 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000219 InitListExpr *StructuredList,
220 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000221 void CheckReferenceType(const InitializedEntity &Entity,
222 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000223 unsigned &Index,
224 InitListExpr *StructuredList,
225 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000226 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000227 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000228 InitListExpr *StructuredList,
229 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000230 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000231 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000233 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000234 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000235 unsigned &StructuredIndex,
236 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000237 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000238 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000239 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000241 InitListExpr *StructuredList,
242 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000243 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000244 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000245 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000246 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000247 RecordDecl::field_iterator *NextField,
248 llvm::APSInt *NextElementIndex,
249 unsigned &Index,
250 InitListExpr *StructuredList,
251 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000252 bool FinishSubobjectInit,
253 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000254 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
255 QualType CurrentObjectType,
256 InitListExpr *StructuredList,
257 unsigned StructuredIndex,
258 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000259 void UpdateStructuredListElement(InitListExpr *StructuredList,
260 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000261 Expr *expr);
262 int numArrayElements(QualType DeclType);
263 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000264
Douglas Gregord6d37de2009-12-22 00:05:34 +0000265 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
266 const InitializedEntity &ParentEntity,
267 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000268 void FillInValueInitializations(const InitializedEntity &Entity,
269 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000270 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
271 Expr *InitExpr, FieldDecl *Field,
272 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000273 void CheckValueInitializable(const InitializedEntity &Entity);
274
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000275public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000276 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000277 InitListExpr *IL, QualType &T, bool VerifyOnly,
278 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000279 bool HadError() { return hadError; }
280
281 // @brief Retrieves the fully-structured initializer list used for
282 // semantic analysis and code generation.
283 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
284};
Chris Lattner8b419b92009-02-24 22:48:58 +0000285} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000286
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000287void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
288 assert(VerifyOnly &&
289 "CheckValueInitializable is only inteded for verification mode.");
290
291 SourceLocation Loc;
292 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
293 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000294 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000295 if (InitSeq.Failed())
296 hadError = true;
297}
298
Douglas Gregord6d37de2009-12-22 00:05:34 +0000299void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
300 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000301 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000302 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000303 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000304 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000305 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000306 = InitializedEntity::InitializeMember(Field, &ParentEntity);
307 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000308 // If there's no explicit initializer but we have a default initializer, use
309 // that. This only happens in C++1y, since classes with default
310 // initializers are not aggregates in C++11.
311 if (Field->hasInClassInitializer()) {
312 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
313 ILE->getRBraceLoc(), Field);
314 if (Init < NumInits)
315 ILE->setInit(Init, DIE);
316 else {
317 ILE->updateInit(SemaRef.Context, Init, DIE);
318 RequiresSecondPass = true;
319 }
320 return;
321 }
322
Douglas Gregord6d37de2009-12-22 00:05:34 +0000323 // FIXME: We probably don't need to handle references
324 // specially here, since value-initialization of references is
325 // handled in InitializationSequence.
326 if (Field->getType()->isReferenceType()) {
327 // C++ [dcl.init.aggr]p9:
328 // If an incomplete or empty initializer-list leaves a
329 // member of reference type uninitialized, the program is
330 // ill-formed.
331 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
332 << Field->getType()
333 << ILE->getSyntacticForm()->getSourceRange();
334 SemaRef.Diag(Field->getLocation(),
335 diag::note_uninit_reference_member);
336 hadError = true;
337 return;
338 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000339
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
341 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000342 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000343 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000344 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000345 hadError = true;
346 return;
347 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000348
John McCall60d7b3a2010-08-24 06:29:42 +0000349 ExprResult MemberInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000350 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000351 if (MemberInit.isInvalid()) {
352 hadError = true;
353 return;
354 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355
Douglas Gregord6d37de2009-12-22 00:05:34 +0000356 if (hadError) {
357 // Do nothing
358 } else if (Init < NumInits) {
359 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000360 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000361 // Value-initialization requires a constructor call, so
362 // extend the initializer list to include the constructor
363 // call and make a note that we'll need to take another pass
364 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000365 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000366 RequiresSecondPass = true;
367 }
368 } else if (InitListExpr *InnerILE
369 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000370 FillInValueInitializations(MemberEntity, InnerILE,
371 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000372}
373
Douglas Gregor4c678342009-01-28 21:54:33 +0000374/// Recursively replaces NULL values within the given initializer list
375/// with expressions that perform value-initialization of the
376/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000377void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000378InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
379 InitListExpr *ILE,
380 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000381 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000382 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000383 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000384 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000385 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Ted Kremenek6217b802009-07-29 21:53:49 +0000387 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000388 const RecordDecl *RDecl = RType->getDecl();
389 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000390 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
391 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000392 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
393 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
394 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
395 FieldEnd = RDecl->field_end();
396 Field != FieldEnd; ++Field) {
397 if (Field->hasInClassInitializer()) {
398 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
399 break;
400 }
401 }
402 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000403 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000404 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
405 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000406 Field != FieldEnd; ++Field) {
407 if (Field->isUnnamedBitfield())
408 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000409
Douglas Gregord6d37de2009-12-22 00:05:34 +0000410 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000411 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000412
David Blaikie581deb32012-06-06 20:45:41 +0000413 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000414 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000415 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000416
Douglas Gregord6d37de2009-12-22 00:05:34 +0000417 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418
Douglas Gregord6d37de2009-12-22 00:05:34 +0000419 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000420 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000421 break;
422 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000423 }
424
425 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000426 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000427
428 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000430 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000431 unsigned NumInits = ILE->getNumInits();
432 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000433 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000434 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000435 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
436 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000437 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000438 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000439 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000440 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000441 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000442 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000443 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000444 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000445 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000446
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000447
Douglas Gregor87fd7032009-02-02 17:43:21 +0000448 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000449 if (hadError)
450 return;
451
Anders Carlssond3d824d2010-01-23 04:34:47 +0000452 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
453 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000454 ElementEntity.setElementIndex(Init);
455
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000456 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
457 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000458 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
459 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000460 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000461 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000462 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000463 hadError = true;
464 return;
465 }
466
John McCall60d7b3a2010-08-24 06:29:42 +0000467 ExprResult ElementInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000468 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000469 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000470 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000471 return;
472 }
473
474 if (hadError) {
475 // Do nothing
476 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000477 // For arrays, just set the expression used for value-initialization
478 // of the "holes" in the array.
479 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
480 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
481 else
482 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000483 } else {
484 // For arrays, just set the expression used for value-initialization
485 // of the rest of elements and exit.
486 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
487 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
488 return;
489 }
490
Sebastian Redl7491c492011-06-05 13:59:11 +0000491 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000492 // Value-initialization requires a constructor call, so
493 // extend the initializer list to include the constructor
494 // call and make a note that we'll need to take another pass
495 // through the initializer list.
496 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
497 RequiresSecondPass = true;
498 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000499 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000500 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000501 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000502 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 }
504}
505
Chris Lattner68355a52009-01-29 05:10:57 +0000506
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000507InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000508 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000509 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000510 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000511 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000512
Eli Friedmanb85f7072008-05-19 19:16:24 +0000513 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000515 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000516 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000517 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000518 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000519 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000520
Sebastian Redl14b0c192011-09-24 17:48:00 +0000521 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000522 bool RequiresSecondPass = false;
523 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000524 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000525 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000526 RequiresSecondPass);
527 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000528}
529
530int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000531 // FIXME: use a proper constant
532 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000533 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000534 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000535 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
536 }
537 return maxElements;
538}
539
540int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000541 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000542 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000543 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000544 Field = structDecl->field_begin(),
545 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000546 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000547 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000548 ++InitializableMembers;
549 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000550 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000551 return std::min(InitializableMembers, 1);
552 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000553}
554
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000555void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000556 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000557 QualType T, unsigned &Index,
558 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000559 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000560 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Steve Naroff0cca7492008-05-01 22:18:59 +0000562 if (T->isArrayType())
563 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000564 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000565 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000566 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000567 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000568 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000569 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000570
Eli Friedman402256f2008-05-25 13:49:22 +0000571 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000572 if (!VerifyOnly)
573 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
574 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000576 hadError = true;
577 return;
578 }
579
Douglas Gregor4c678342009-01-28 21:54:33 +0000580 // Build a structured initializer list corresponding to this subobject.
581 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000582 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
583 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000584 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000585 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000586 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000587
Douglas Gregor4c678342009-01-28 21:54:33 +0000588 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000589 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000591 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000592 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000593 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000594
595 if (VerifyOnly) {
596 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
597 hadError = true;
598 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000599 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000600
Sebastian Redlc2235182011-10-16 18:19:28 +0000601 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000602 // Update the structured sub-object initializer so that it's ending
603 // range corresponds with the end of the last initializer it used.
604 if (EndIndex < ParentIList->getNumInits()) {
605 SourceLocation EndLoc
606 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
607 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
608 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Sebastian Redlc2235182011-10-16 18:19:28 +0000610 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000611 if (T->isArrayType() || T->isRecordType()) {
612 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000613 AllowBraceElision ? diag::warn_missing_braces :
614 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000615 << StructuredSubobjectInitList->getSourceRange()
616 << FixItHint::CreateInsertion(
617 StructuredSubobjectInitList->getLocStart(), "{")
618 << FixItHint::CreateInsertion(
619 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000620 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000621 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000622 if (!AllowBraceElision)
623 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000624 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000625 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000626}
627
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000628void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000629 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000630 unsigned &Index,
631 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000632 unsigned &StructuredIndex,
633 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000634 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000635 if (!VerifyOnly) {
636 SyntacticToSemantic[IList] = StructuredList;
637 StructuredList->setSyntacticForm(IList);
638 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000640 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000641 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000642 QualType ExprTy = T;
643 if (!ExprTy->isArrayType())
644 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000645 IList->setType(ExprTy);
646 StructuredList->setType(ExprTy);
647 }
Eli Friedman638e1442008-05-25 13:22:35 +0000648 if (hadError)
649 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000650
Eli Friedman638e1442008-05-25 13:22:35 +0000651 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000652 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000653 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000654 if (SemaRef.getLangOpts().CPlusPlus ||
655 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000656 IList->getType()->isVectorType())) {
657 hadError = true;
658 }
659 return;
660 }
661
Eli Friedmane5408582009-05-29 20:20:05 +0000662 if (StructuredIndex == 1 &&
663 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000664 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000665 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000666 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000667 hadError = true;
668 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000669 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000670 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000671 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000672 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000673 // Don't complain for incomplete types, since we'll get an error
674 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000675 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000676 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000677 CurrentObjectType->isArrayType()? 0 :
678 CurrentObjectType->isVectorType()? 1 :
679 CurrentObjectType->isScalarType()? 2 :
680 CurrentObjectType->isUnionType()? 3 :
681 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000682
683 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000684 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000685 DK = diag::err_excess_initializers;
686 hadError = true;
687 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000688 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000689 DK = diag::err_excess_initializers;
690 hadError = true;
691 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000692
Chris Lattner08202542009-02-24 22:50:46 +0000693 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000694 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000695 }
696 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000697
Sebastian Redl14b0c192011-09-24 17:48:00 +0000698 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
699 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000700 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000701 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000702 << FixItHint::CreateRemoval(IList->getLocStart())
703 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000704}
705
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000706void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000707 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000708 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000709 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000710 unsigned &Index,
711 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000712 unsigned &StructuredIndex,
713 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000714 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
715 // Explicitly braced initializer for complex type can be real+imaginary
716 // parts.
717 CheckComplexType(Entity, IList, DeclType, Index,
718 StructuredList, StructuredIndex);
719 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000720 CheckScalarType(Entity, IList, DeclType, Index,
721 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000722 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000723 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000724 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000725 } else if (DeclType->isRecordType()) {
726 assert(DeclType->isAggregateType() &&
727 "non-aggregate records should be handed in CheckSubElementType");
728 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
729 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
730 SubobjectIsDesignatorContext, Index,
731 StructuredList, StructuredIndex,
732 TopLevelObject);
733 } else if (DeclType->isArrayType()) {
734 llvm::APSInt Zero(
735 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
736 false);
737 CheckArrayType(Entity, IList, DeclType, Zero,
738 SubobjectIsDesignatorContext, Index,
739 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000740 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
741 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000742 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000743 if (!VerifyOnly)
744 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
745 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000746 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000747 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000748 CheckReferenceType(Entity, IList, DeclType, Index,
749 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000750 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000751 if (!VerifyOnly)
752 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
753 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000754 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000755 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000756 if (!VerifyOnly)
757 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
758 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000759 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000760 }
761}
762
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000763void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000764 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000765 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000766 unsigned &Index,
767 InitListExpr *StructuredList,
768 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000769 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000770 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000771 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
772 unsigned newIndex = 0;
773 unsigned newStructuredIndex = 0;
774 InitListExpr *newStructuredList
775 = getStructuredSubobjectInit(IList, Index, ElemType,
776 StructuredList, StructuredIndex,
777 SubInitList->getSourceRange());
778 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
779 newStructuredList, newStructuredIndex);
780 ++StructuredIndex;
781 ++Index;
782 return;
783 }
784 assert(SemaRef.getLangOpts().CPlusPlus &&
785 "non-aggregate records are only possible in C++");
786 // C++ initialization is handled later.
787 }
788
789 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000790 return CheckScalarType(Entity, IList, ElemType, Index,
791 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000792 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000793 return CheckReferenceType(Entity, IList, ElemType, Index,
794 StructuredList, StructuredIndex);
795 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000796
John McCallfef8b342011-02-21 07:57:55 +0000797 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
798 // arrayType can be incomplete if we're initializing a flexible
799 // array member. There's nothing we can do with the completed
800 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000801
John McCallfef8b342011-02-21 07:57:55 +0000802 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000803 if (!VerifyOnly) {
804 CheckStringInit(Str, ElemType, arrayType, SemaRef);
805 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
806 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000807 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000808 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000809 }
John McCallfef8b342011-02-21 07:57:55 +0000810
811 // Fall through for subaggregate initialization.
812
David Blaikie4e4d0842012-03-11 07:00:24 +0000813 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000814 // C++ [dcl.init.aggr]p12:
815 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000816 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000817 // an initializer-list. If the initializer can initialize a
818 // member, the member is initialized. [...]
819
820 // FIXME: Better EqualLoc?
821 InitializationKind Kind =
822 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000823 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000824
825 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000826 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000827 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000828 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000829 if (Result.isInvalid())
830 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000831
Sebastian Redl14b0c192011-09-24 17:48:00 +0000832 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000833 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000834 }
John McCallfef8b342011-02-21 07:57:55 +0000835 ++Index;
836 return;
837 }
838
839 // Fall through for subaggregate initialization
840 } else {
841 // C99 6.7.8p13:
842 //
843 // The initializer for a structure or union object that has
844 // automatic storage duration shall be either an initializer
845 // list as described below, or a single expression that has
846 // compatible structure or union type. In the latter case, the
847 // initial value of the object, including unnamed members, is
848 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000849 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000850 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000851 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
852 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000853 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000854 if (ExprRes.isInvalid())
855 hadError = true;
856 else {
857 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000858 if (ExprRes.isInvalid())
859 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000860 }
861 UpdateStructuredListElement(StructuredList, StructuredIndex,
862 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000863 ++Index;
864 return;
865 }
John Wiegley429bb272011-04-08 18:41:53 +0000866 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000867 // Fall through for subaggregate initialization
868 }
869
870 // C++ [dcl.init.aggr]p12:
871 //
872 // [...] Otherwise, if the member is itself a non-empty
873 // subaggregate, brace elision is assumed and the initializer is
874 // considered for the initialization of the first member of
875 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000876 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000877 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000878 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
879 StructuredIndex);
880 ++StructuredIndex;
881 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000882 if (!VerifyOnly) {
883 // We cannot initialize this element, so let
884 // PerformCopyInitialization produce the appropriate diagnostic.
885 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
886 SemaRef.Owned(expr),
887 /*TopLevelOfInitList=*/true);
888 }
John McCallfef8b342011-02-21 07:57:55 +0000889 hadError = true;
890 ++Index;
891 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000892 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000893}
894
Eli Friedman0c706c22011-09-19 23:17:44 +0000895void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
896 InitListExpr *IList, QualType DeclType,
897 unsigned &Index,
898 InitListExpr *StructuredList,
899 unsigned &StructuredIndex) {
900 assert(Index == 0 && "Index in explicit init list must be zero");
901
902 // As an extension, clang supports complex initializers, which initialize
903 // a complex number component-wise. When an explicit initializer list for
904 // a complex number contains two two initializers, this extension kicks in:
905 // it exepcts the initializer list to contain two elements convertible to
906 // the element type of the complex type. The first element initializes
907 // the real part, and the second element intitializes the imaginary part.
908
909 if (IList->getNumInits() != 2)
910 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
911 StructuredIndex);
912
913 // This is an extension in C. (The builtin _Complex type does not exist
914 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000915 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000916 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
917 << IList->getSourceRange();
918
919 // Initialize the complex number.
920 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
921 InitializedEntity ElementEntity =
922 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
923
924 for (unsigned i = 0; i < 2; ++i) {
925 ElementEntity.setElementIndex(Index);
926 CheckSubElementType(ElementEntity, IList, elementType, Index,
927 StructuredList, StructuredIndex);
928 }
929}
930
931
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000932void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000933 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000934 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000935 InitListExpr *StructuredList,
936 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000937 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000938 if (!VerifyOnly)
939 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000940 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000941 diag::warn_cxx98_compat_empty_scalar_initializer :
942 diag::err_empty_scalar_initializer)
943 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000944 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000945 ++Index;
946 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000947 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000948 }
John McCallb934c2d2010-11-11 00:46:36 +0000949
950 Expr *expr = IList->getInit(Index);
951 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000952 if (!VerifyOnly)
953 SemaRef.Diag(SubIList->getLocStart(),
954 diag::warn_many_braces_around_scalar_init)
955 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000956
957 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
958 StructuredIndex);
959 return;
960 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000961 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000962 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000963 diag::err_designator_for_scalar_init)
964 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000965 hadError = true;
966 ++Index;
967 ++StructuredIndex;
968 return;
969 }
970
Sebastian Redl14b0c192011-09-24 17:48:00 +0000971 if (VerifyOnly) {
972 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
973 hadError = true;
974 ++Index;
975 return;
976 }
977
John McCallb934c2d2010-11-11 00:46:36 +0000978 ExprResult Result =
979 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000980 SemaRef.Owned(expr),
981 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000982
983 Expr *ResultExpr = 0;
984
985 if (Result.isInvalid())
986 hadError = true; // types weren't compatible.
987 else {
988 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000989
John McCallb934c2d2010-11-11 00:46:36 +0000990 if (ResultExpr != expr) {
991 // The type was promoted, update initializer list.
992 IList->setInit(Index, ResultExpr);
993 }
994 }
995 if (hadError)
996 ++StructuredIndex;
997 else
998 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
999 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001000}
1001
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001002void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1003 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001004 unsigned &Index,
1005 InitListExpr *StructuredList,
1006 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001007 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001008 // FIXME: It would be wonderful if we could point at the actual member. In
1009 // general, it would be useful to pass location information down the stack,
1010 // so that we know the location (or decl) of the "current object" being
1011 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001012 if (!VerifyOnly)
1013 SemaRef.Diag(IList->getLocStart(),
1014 diag::err_init_reference_member_uninitialized)
1015 << DeclType
1016 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001017 hadError = true;
1018 ++Index;
1019 ++StructuredIndex;
1020 return;
1021 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001022
1023 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001024 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001025 if (!VerifyOnly)
1026 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1027 << DeclType << IList->getSourceRange();
1028 hadError = true;
1029 ++Index;
1030 ++StructuredIndex;
1031 return;
1032 }
1033
1034 if (VerifyOnly) {
1035 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1036 hadError = true;
1037 ++Index;
1038 return;
1039 }
1040
1041 ExprResult Result =
1042 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1043 SemaRef.Owned(expr),
1044 /*TopLevelOfInitList=*/true);
1045
1046 if (Result.isInvalid())
1047 hadError = true;
1048
1049 expr = Result.takeAs<Expr>();
1050 IList->setInit(Index, expr);
1051
1052 if (hadError)
1053 ++StructuredIndex;
1054 else
1055 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1056 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001057}
1058
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001059void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001060 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001061 unsigned &Index,
1062 InitListExpr *StructuredList,
1063 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001064 const VectorType *VT = DeclType->getAs<VectorType>();
1065 unsigned maxElements = VT->getNumElements();
1066 unsigned numEltsInit = 0;
1067 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001068
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001069 if (Index >= IList->getNumInits()) {
1070 // Make sure the element type can be value-initialized.
1071 if (VerifyOnly)
1072 CheckValueInitializable(
1073 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1074 return;
1075 }
1076
David Blaikie4e4d0842012-03-11 07:00:24 +00001077 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001078 // If the initializing element is a vector, try to copy-initialize
1079 // instead of breaking it apart (which is doomed to failure anyway).
1080 Expr *Init = IList->getInit(Index);
1081 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001082 if (VerifyOnly) {
1083 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1084 hadError = true;
1085 ++Index;
1086 return;
1087 }
1088
John McCall20e047a2010-10-30 00:11:39 +00001089 ExprResult Result =
1090 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001091 SemaRef.Owned(Init),
1092 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001093
1094 Expr *ResultExpr = 0;
1095 if (Result.isInvalid())
1096 hadError = true; // types weren't compatible.
1097 else {
1098 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001099
John McCall20e047a2010-10-30 00:11:39 +00001100 if (ResultExpr != Init) {
1101 // The type was promoted, update initializer list.
1102 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001103 }
1104 }
John McCall20e047a2010-10-30 00:11:39 +00001105 if (hadError)
1106 ++StructuredIndex;
1107 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001108 UpdateStructuredListElement(StructuredList, StructuredIndex,
1109 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001110 ++Index;
1111 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001112 }
Mike Stump1eb44332009-09-09 15:08:12 +00001113
John McCall20e047a2010-10-30 00:11:39 +00001114 InitializedEntity ElementEntity =
1115 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001116
John McCall20e047a2010-10-30 00:11:39 +00001117 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1118 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001119 if (Index >= IList->getNumInits()) {
1120 if (VerifyOnly)
1121 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001122 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001124
John McCall20e047a2010-10-30 00:11:39 +00001125 ElementEntity.setElementIndex(Index);
1126 CheckSubElementType(ElementEntity, IList, elementType, Index,
1127 StructuredList, StructuredIndex);
1128 }
1129 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001130 }
John McCall20e047a2010-10-30 00:11:39 +00001131
1132 InitializedEntity ElementEntity =
1133 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001134
John McCall20e047a2010-10-30 00:11:39 +00001135 // OpenCL initializers allows vectors to be constructed from vectors.
1136 for (unsigned i = 0; i < maxElements; ++i) {
1137 // Don't attempt to go past the end of the init list
1138 if (Index >= IList->getNumInits())
1139 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001140
John McCall20e047a2010-10-30 00:11:39 +00001141 ElementEntity.setElementIndex(Index);
1142
1143 QualType IType = IList->getInit(Index)->getType();
1144 if (!IType->isVectorType()) {
1145 CheckSubElementType(ElementEntity, IList, elementType, Index,
1146 StructuredList, StructuredIndex);
1147 ++numEltsInit;
1148 } else {
1149 QualType VecType;
1150 const VectorType *IVT = IType->getAs<VectorType>();
1151 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001152
John McCall20e047a2010-10-30 00:11:39 +00001153 if (IType->isExtVectorType())
1154 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1155 else
1156 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001157 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001158 CheckSubElementType(ElementEntity, IList, VecType, Index,
1159 StructuredList, StructuredIndex);
1160 numEltsInit += numIElts;
1161 }
1162 }
1163
1164 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001165 if (numEltsInit != maxElements) {
1166 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001167 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001168 diag::err_vector_incorrect_num_initializers)
1169 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1170 hadError = true;
1171 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001172}
1173
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001174void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001175 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001176 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001177 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001178 unsigned &Index,
1179 InitListExpr *StructuredList,
1180 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001181 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1182
Steve Naroff0cca7492008-05-01 22:18:59 +00001183 // Check for the special-case of initializing an array with a string.
1184 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001185 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001186 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001187 // We place the string literal directly into the resulting
1188 // initializer list. This is the only place where the structure
1189 // of the structured initializer list doesn't match exactly,
1190 // because doing so would involve allocating one character
1191 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001192 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001193 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001194 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1195 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1196 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001197 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001198 return;
1199 }
1200 }
John McCallce6c9b72011-02-21 07:22:22 +00001201 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001202 // Check for VLAs; in standard C it would be possible to check this
1203 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1204 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001205 if (!VerifyOnly)
1206 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1207 diag::err_variable_object_no_init)
1208 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001209 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001210 ++Index;
1211 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001212 return;
1213 }
1214
Douglas Gregor05c13a32009-01-22 00:58:24 +00001215 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001216 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1217 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001218 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001219 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001220 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001221 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001222 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001223 maxElementsKnown = true;
1224 }
1225
John McCallce6c9b72011-02-21 07:22:22 +00001226 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001227 while (Index < IList->getNumInits()) {
1228 Expr *Init = IList->getInit(Index);
1229 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001230 // If we're not the subobject that matches up with the '{' for
1231 // the designator, we shouldn't be handling the
1232 // designator. Return immediately.
1233 if (!SubobjectIsDesignatorContext)
1234 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001235
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001236 // Handle this designated initializer. elementIndex will be
1237 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001238 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001239 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001240 StructuredList, StructuredIndex, true,
1241 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001242 hadError = true;
1243 continue;
1244 }
1245
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001246 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001247 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001248 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001249 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001250 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001251
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001252 // If the array is of incomplete type, keep track of the number of
1253 // elements in the initializer.
1254 if (!maxElementsKnown && elementIndex > maxElements)
1255 maxElements = elementIndex;
1256
Douglas Gregor05c13a32009-01-22 00:58:24 +00001257 continue;
1258 }
1259
1260 // If we know the maximum number of elements, and we've already
1261 // hit it, stop consuming elements in the initializer list.
1262 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001263 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001264
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001265 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001266 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001267 Entity);
1268 // Check this element.
1269 CheckSubElementType(ElementEntity, IList, elementType, Index,
1270 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271 ++elementIndex;
1272
1273 // If the array is of incomplete type, keep track of the number of
1274 // elements in the initializer.
1275 if (!maxElementsKnown && elementIndex > maxElements)
1276 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001277 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001278 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001279 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001280 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001281 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001282 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001283 // Sizing an array implicitly to zero is not allowed by ISO C,
1284 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001285 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001286 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001287 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001288
Mike Stump1eb44332009-09-09 15:08:12 +00001289 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001290 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001291 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001292 if (!hadError && VerifyOnly) {
1293 // Check if there are any members of the array that get value-initialized.
1294 // If so, check if doing that is possible.
1295 // FIXME: This needs to detect holes left by designated initializers too.
1296 if (maxElementsKnown && elementIndex < maxElements)
1297 CheckValueInitializable(InitializedEntity::InitializeElement(
1298 SemaRef.Context, 0, Entity));
1299 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001300}
1301
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001302bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1303 Expr *InitExpr,
1304 FieldDecl *Field,
1305 bool TopLevelObject) {
1306 // Handle GNU flexible array initializers.
1307 unsigned FlexArrayDiag;
1308 if (isa<InitListExpr>(InitExpr) &&
1309 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1310 // Empty flexible array init always allowed as an extension
1311 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001312 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001313 // Disallow flexible array init in C++; it is not required for gcc
1314 // compatibility, and it needs work to IRGen correctly in general.
1315 FlexArrayDiag = diag::err_flexible_array_init;
1316 } else if (!TopLevelObject) {
1317 // Disallow flexible array init on non-top-level object
1318 FlexArrayDiag = diag::err_flexible_array_init;
1319 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1320 // Disallow flexible array init on anything which is not a variable.
1321 FlexArrayDiag = diag::err_flexible_array_init;
1322 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1323 // Disallow flexible array init on local variables.
1324 FlexArrayDiag = diag::err_flexible_array_init;
1325 } else {
1326 // Allow other cases.
1327 FlexArrayDiag = diag::ext_flexible_array_init;
1328 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001329
1330 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001331 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001332 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001333 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001334 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1335 << Field;
1336 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001337
1338 return FlexArrayDiag != diag::ext_flexible_array_init;
1339}
1340
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001341void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001342 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001343 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001344 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001345 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001346 unsigned &Index,
1347 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001348 unsigned &StructuredIndex,
1349 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001350 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Eli Friedmanb85f7072008-05-19 19:16:24 +00001352 // If the record is invalid, some of it's members are invalid. To avoid
1353 // confusion, we forgo checking the intializer for the entire record.
1354 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001355 // Assume it was supposed to consume a single initializer.
1356 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001357 hadError = true;
1358 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001359 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001360
1361 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001362 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001363
1364 // If there's a default initializer, use it.
1365 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1366 if (VerifyOnly)
1367 return;
1368 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1369 Field != FieldEnd; ++Field) {
1370 if (Field->hasInClassInitializer()) {
1371 StructuredList->setInitializedFieldInUnion(*Field);
1372 // FIXME: Actually build a CXXDefaultInitExpr?
1373 return;
1374 }
1375 }
1376 }
1377
1378 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001379 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1380 Field != FieldEnd; ++Field) {
1381 if (Field->getDeclName()) {
1382 if (VerifyOnly)
1383 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001384 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001385 else
David Blaikie581deb32012-06-06 20:45:41 +00001386 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001387 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001388 }
1389 }
1390 return;
1391 }
1392
Douglas Gregor05c13a32009-01-22 00:58:24 +00001393 // If structDecl is a forward declaration, this loop won't do
1394 // anything except look at designated initializers; That's okay,
1395 // because an error should get printed out elsewhere. It might be
1396 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001397 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001398 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001399 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001400 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001401 while (Index < IList->getNumInits()) {
1402 Expr *Init = IList->getInit(Index);
1403
1404 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001405 // If we're not the subobject that matches up with the '{' for
1406 // the designator, we shouldn't be handling the
1407 // designator. Return immediately.
1408 if (!SubobjectIsDesignatorContext)
1409 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001410
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001411 // Handle this designated initializer. Field will be updated to
1412 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001413 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001414 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001415 StructuredList, StructuredIndex,
1416 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001417 hadError = true;
1418
Douglas Gregordfb5e592009-02-12 19:00:39 +00001419 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001420
1421 // Disable check for missing fields when designators are used.
1422 // This matches gcc behaviour.
1423 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001424 continue;
1425 }
1426
1427 if (Field == FieldEnd) {
1428 // We've run out of fields. We're done.
1429 break;
1430 }
1431
Douglas Gregordfb5e592009-02-12 19:00:39 +00001432 // We've already initialized a member of a union. We're done.
1433 if (InitializedSomething && DeclType->isUnionType())
1434 break;
1435
Douglas Gregor44b43212008-12-11 16:49:14 +00001436 // If we've hit the flexible array member at the end, we're done.
1437 if (Field->getType()->isIncompleteArrayType())
1438 break;
1439
Douglas Gregor0bb76892009-01-29 16:53:55 +00001440 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001441 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001442 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001443 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001444 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001445
Douglas Gregor54001c12011-06-29 21:51:31 +00001446 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001447 bool InvalidUse;
1448 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001449 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001450 else
David Blaikie581deb32012-06-06 20:45:41 +00001451 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001452 IList->getInit(Index)->getLocStart());
1453 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001454 ++Index;
1455 ++Field;
1456 hadError = true;
1457 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001458 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001459
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001460 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001461 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001462 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1463 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001464 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001465
Sebastian Redl14b0c192011-09-24 17:48:00 +00001466 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001467 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001468 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001469 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001470
1471 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001472 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001473
John McCall80639de2010-03-11 19:32:38 +00001474 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001475 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1476 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1477 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001478 // It is possible we have one or more unnamed bitfields remaining.
1479 // Find first (if any) named field and emit warning.
1480 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1481 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001482 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001483 SemaRef.Diag(IList->getSourceRange().getEnd(),
1484 diag::warn_missing_field_initializers) << it->getName();
1485 break;
1486 }
1487 }
1488 }
1489
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001490 // Check that any remaining fields can be value-initialized.
1491 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1492 !Field->getType()->isIncompleteArrayType()) {
1493 // FIXME: Should check for holes left by designated initializers too.
1494 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001495 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001496 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001497 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001498 }
1499 }
1500
Mike Stump1eb44332009-09-09 15:08:12 +00001501 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001502 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001503 return;
1504
David Blaikie581deb32012-06-06 20:45:41 +00001505 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001506 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001507 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001508 ++Index;
1509 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001510 }
1511
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001512 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001513 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001514
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001515 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001516 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001517 StructuredList, StructuredIndex);
1518 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001519 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001520 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001521}
Steve Naroff0cca7492008-05-01 22:18:59 +00001522
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001523/// \brief Expand a field designator that refers to a member of an
1524/// anonymous struct or union into a series of field designators that
1525/// refers to the field within the appropriate subobject.
1526///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001527static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001528 DesignatedInitExpr *DIE,
1529 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001530 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001531 typedef DesignatedInitExpr::Designator Designator;
1532
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001533 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001534 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001535 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1536 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1537 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001538 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001539 DIE->getDesignator(DesigIdx)->getDotLoc(),
1540 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1541 else
1542 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1543 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001544 assert(isa<FieldDecl>(*PI));
1545 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001546 }
1547
1548 // Expand the current designator into the set of replacement
1549 // designators, so we have a full subobject path down to where the
1550 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001551 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001552 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001553}
Mike Stump1eb44332009-09-09 15:08:12 +00001554
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001555/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001556/// corresponds to FieldName.
1557static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1558 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001559 if (!FieldName)
1560 return 0;
1561
Francois Picheta0e27f02010-12-22 03:46:10 +00001562 assert(AnonField->isAnonymousStructOrUnion());
1563 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001564 while (IndirectFieldDecl *IF =
1565 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001566 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001567 return IF;
1568 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001569 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001570 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001571}
1572
Sebastian Redl14b0c192011-09-24 17:48:00 +00001573static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1574 DesignatedInitExpr *DIE) {
1575 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1576 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1577 for (unsigned I = 0; I < NumIndexExprs; ++I)
1578 IndexExprs[I] = DIE->getSubExpr(I + 1);
1579 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001580 DIE->size(), IndexExprs,
1581 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001582 DIE->usesGNUSyntax(), DIE->getInit());
1583}
1584
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001585namespace {
1586
1587// Callback to only accept typo corrections that are for field members of
1588// the given struct or union.
1589class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1590 public:
1591 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1592 : Record(RD) {}
1593
1594 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1595 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1596 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1597 }
1598
1599 private:
1600 RecordDecl *Record;
1601};
1602
1603}
1604
Douglas Gregor05c13a32009-01-22 00:58:24 +00001605/// @brief Check the well-formedness of a C99 designated initializer.
1606///
1607/// Determines whether the designated initializer @p DIE, which
1608/// resides at the given @p Index within the initializer list @p
1609/// IList, is well-formed for a current object of type @p DeclType
1610/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001611/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001612/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001613///
1614/// @param IList The initializer list in which this designated
1615/// initializer occurs.
1616///
Douglas Gregor71199712009-04-15 04:56:10 +00001617/// @param DIE The designated initializer expression.
1618///
1619/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001620///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001621/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001622/// into which the designation in @p DIE should refer.
1623///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001624/// @param NextField If non-NULL and the first designator in @p DIE is
1625/// a field, this will be set to the field declaration corresponding
1626/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001627///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001628/// @param NextElementIndex If non-NULL and the first designator in @p
1629/// DIE is an array designator or GNU array-range designator, this
1630/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001631///
1632/// @param Index Index into @p IList where the designated initializer
1633/// @p DIE occurs.
1634///
Douglas Gregor4c678342009-01-28 21:54:33 +00001635/// @param StructuredList The initializer list expression that
1636/// describes all of the subobject initializers in the order they'll
1637/// actually be initialized.
1638///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001639/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001640bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001641InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001642 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001643 DesignatedInitExpr *DIE,
1644 unsigned DesigIdx,
1645 QualType &CurrentObjectType,
1646 RecordDecl::field_iterator *NextField,
1647 llvm::APSInt *NextElementIndex,
1648 unsigned &Index,
1649 InitListExpr *StructuredList,
1650 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001651 bool FinishSubobjectInit,
1652 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001653 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001654 // Check the actual initialization for the designated object type.
1655 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001656
1657 // Temporarily remove the designator expression from the
1658 // initializer list that the child calls see, so that we don't try
1659 // to re-process the designator.
1660 unsigned OldIndex = Index;
1661 IList->setInit(OldIndex, DIE->getInit());
1662
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001663 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001664 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001665
1666 // Restore the designated initializer expression in the syntactic
1667 // form of the initializer list.
1668 if (IList->getInit(OldIndex) != DIE->getInit())
1669 DIE->setInit(IList->getInit(OldIndex));
1670 IList->setInit(OldIndex, DIE);
1671
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001672 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001673 }
1674
Douglas Gregor71199712009-04-15 04:56:10 +00001675 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001676 bool IsFirstDesignator = (DesigIdx == 0);
1677 if (!VerifyOnly) {
1678 assert((IsFirstDesignator || StructuredList) &&
1679 "Need a non-designated initializer list to start from");
1680
1681 // Determine the structural initializer list that corresponds to the
1682 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001683 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001684 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1685 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001686 SourceRange(D->getLocStart(),
1687 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001688 assert(StructuredList && "Expected a structured initializer list");
1689 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001690
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001691 if (D->isFieldDesignator()) {
1692 // C99 6.7.8p7:
1693 //
1694 // If a designator has the form
1695 //
1696 // . identifier
1697 //
1698 // then the current object (defined below) shall have
1699 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001700 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001701 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001702 if (!RT) {
1703 SourceLocation Loc = D->getDotLoc();
1704 if (Loc.isInvalid())
1705 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001706 if (!VerifyOnly)
1707 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001708 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001709 ++Index;
1710 return true;
1711 }
1712
Douglas Gregor4c678342009-01-28 21:54:33 +00001713 // Note: we perform a linear search of the fields here, despite
1714 // the fact that we have a faster lookup method, because we always
1715 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001716 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001717 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001718 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001719 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001720 Field = RT->getDecl()->field_begin(),
1721 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001722 for (; Field != FieldEnd; ++Field) {
1723 if (Field->isUnnamedBitfield())
1724 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001725
Francois Picheta0e27f02010-12-22 03:46:10 +00001726 // If we find a field representing an anonymous field, look in the
1727 // IndirectFieldDecl that follow for the designated initializer.
1728 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1729 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001730 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001731 // In verify mode, don't modify the original.
1732 if (VerifyOnly)
1733 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001734 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1735 D = DIE->getDesignator(DesigIdx);
1736 break;
1737 }
1738 }
David Blaikie581deb32012-06-06 20:45:41 +00001739 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001740 break;
1741 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001742 break;
1743
1744 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001745 }
1746
Douglas Gregor4c678342009-01-28 21:54:33 +00001747 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001748 if (VerifyOnly) {
1749 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001750 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001751 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001752
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001753 // There was no normal field in the struct with the designated
1754 // name. Perform another lookup for this name, which may find
1755 // something that we can't designate (e.g., a member function),
1756 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001757 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001758 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001759 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001760 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001761 // Name lookup didn't find anything. Determine whether this
1762 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001763 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001764 TypoCorrection Corrected = SemaRef.CorrectTypo(
1765 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001766 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001767 RT->getDecl());
1768 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001769 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001770 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001771 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001772 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001773 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001774 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001775 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001776 << FieldName << CurrentObjectType << CorrectedQuotedStr
1777 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001778 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001779 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001780 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001781 } else {
1782 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1783 << FieldName << CurrentObjectType;
1784 ++Index;
1785 return true;
1786 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001787 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001788
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001789 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001790 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001791 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001792 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001793 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001794 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001795 ++Index;
1796 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001797 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001798
Francois Picheta0e27f02010-12-22 03:46:10 +00001799 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001800 // The replacement field comes from typo correction; find it
1801 // in the list of fields.
1802 FieldIndex = 0;
1803 Field = RT->getDecl()->field_begin();
1804 for (; Field != FieldEnd; ++Field) {
1805 if (Field->isUnnamedBitfield())
1806 continue;
1807
David Blaikie581deb32012-06-06 20:45:41 +00001808 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001809 Field->getIdentifier() == ReplacementField->getIdentifier())
1810 break;
1811
1812 ++FieldIndex;
1813 }
1814 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001815 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001816
1817 // All of the fields of a union are located at the same place in
1818 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001819 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001820 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001821 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001822 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001823 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001824
Douglas Gregor54001c12011-06-29 21:51:31 +00001825 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001826 bool InvalidUse;
1827 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001828 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001829 else
David Blaikie581deb32012-06-06 20:45:41 +00001830 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001831 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001832 ++Index;
1833 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001834 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001835
Sebastian Redl14b0c192011-09-24 17:48:00 +00001836 if (!VerifyOnly) {
1837 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001838 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Sebastian Redl14b0c192011-09-24 17:48:00 +00001840 // Make sure that our non-designated initializer list has space
1841 // for a subobject corresponding to this field.
1842 if (FieldIndex >= StructuredList->getNumInits())
1843 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1844 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001845
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001846 // This designator names a flexible array member.
1847 if (Field->getType()->isIncompleteArrayType()) {
1848 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001849 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001850 // We can't designate an object within the flexible array
1851 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001852 if (!VerifyOnly) {
1853 DesignatedInitExpr::Designator *NextD
1854 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001855 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001856 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001857 << SourceRange(NextD->getLocStart(),
1858 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001859 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001860 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001861 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001862 Invalid = true;
1863 }
1864
Chris Lattner9046c222010-10-10 17:49:49 +00001865 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1866 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001867 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001868 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001869 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001870 diag::err_flexible_array_init_needs_braces)
1871 << DIE->getInit()->getSourceRange();
1872 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001873 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001874 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001875 Invalid = true;
1876 }
1877
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001878 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001879 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001880 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001881 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001882
1883 if (Invalid) {
1884 ++Index;
1885 return true;
1886 }
1887
1888 // Initialize the array.
1889 bool prevHadError = hadError;
1890 unsigned newStructuredIndex = FieldIndex;
1891 unsigned OldIndex = Index;
1892 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001893
1894 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001895 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001896 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001897 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001898
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001899 IList->setInit(OldIndex, DIE);
1900 if (hadError && !prevHadError) {
1901 ++Field;
1902 ++FieldIndex;
1903 if (NextField)
1904 *NextField = Field;
1905 StructuredIndex = FieldIndex;
1906 return true;
1907 }
1908 } else {
1909 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001910 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001911 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001912
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001913 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001914 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001915 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1916 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001917 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001918 true, false))
1919 return true;
1920 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001921
1922 // Find the position of the next field to be initialized in this
1923 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001924 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001925 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001926
1927 // If this the first designator, our caller will continue checking
1928 // the rest of this struct/class/union subobject.
1929 if (IsFirstDesignator) {
1930 if (NextField)
1931 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001932 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001933 return false;
1934 }
1935
Douglas Gregor34e79462009-01-28 23:36:17 +00001936 if (!FinishSubobjectInit)
1937 return false;
1938
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001939 // We've already initialized something in the union; we're done.
1940 if (RT->getDecl()->isUnion())
1941 return hadError;
1942
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001943 // Check the remaining fields within this class/struct/union subobject.
1944 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001945
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001946 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001947 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001948 return hadError && !prevHadError;
1949 }
1950
1951 // C99 6.7.8p6:
1952 //
1953 // If a designator has the form
1954 //
1955 // [ constant-expression ]
1956 //
1957 // then the current object (defined below) shall have array
1958 // type and the expression shall be an integer constant
1959 // expression. If the array is of unknown size, any
1960 // nonnegative value is valid.
1961 //
1962 // Additionally, cope with the GNU extension that permits
1963 // designators of the form
1964 //
1965 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001966 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001967 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001968 if (!VerifyOnly)
1969 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1970 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001971 ++Index;
1972 return true;
1973 }
1974
1975 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001976 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1977 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001978 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001979 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001980 DesignatedEndIndex = DesignatedStartIndex;
1981 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001982 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001983
Mike Stump1eb44332009-09-09 15:08:12 +00001984 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001985 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001986 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001987 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001988 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001989
Chris Lattnere0fd8322011-02-19 22:28:58 +00001990 // Codegen can't handle evaluating array range designators that have side
1991 // effects, because we replicate the AST value for each initialized element.
1992 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1993 // elements with something that has a side effect, so codegen can emit an
1994 // "error unsupported" error instead of miscompiling the app.
1995 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001996 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001997 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001998 }
1999
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002000 if (isa<ConstantArrayType>(AT)) {
2001 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002002 DesignatedStartIndex
2003 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002004 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002005 DesignatedEndIndex
2006 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002007 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2008 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002009 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002010 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002011 diag::err_array_designator_too_large)
2012 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2013 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002014 ++Index;
2015 return true;
2016 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002017 } else {
2018 // Make sure the bit-widths and signedness match.
2019 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002020 DesignatedEndIndex
2021 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002022 else if (DesignatedStartIndex.getBitWidth() <
2023 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002024 DesignatedStartIndex
2025 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002026 DesignatedStartIndex.setIsUnsigned(true);
2027 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002028 }
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Douglas Gregor4c678342009-01-28 21:54:33 +00002030 // Make sure that our non-designated initializer list has space
2031 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002032 if (!VerifyOnly &&
2033 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002034 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002035 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002036
Douglas Gregor34e79462009-01-28 23:36:17 +00002037 // Repeatedly perform subobject initializations in the range
2038 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002039
Douglas Gregor34e79462009-01-28 23:36:17 +00002040 // Move to the next designator
2041 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2042 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002043
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002044 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002045 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002046
Douglas Gregor34e79462009-01-28 23:36:17 +00002047 while (DesignatedStartIndex <= DesignatedEndIndex) {
2048 // Recurse to check later designated subobjects.
2049 QualType ElementType = AT->getElementType();
2050 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002051
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002052 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002053 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2054 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002055 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002056 (DesignatedStartIndex == DesignatedEndIndex),
2057 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002058 return true;
2059
2060 // Move to the next index in the array that we'll be initializing.
2061 ++DesignatedStartIndex;
2062 ElementIndex = DesignatedStartIndex.getZExtValue();
2063 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002064
2065 // If this the first designator, our caller will continue checking
2066 // the rest of this array subobject.
2067 if (IsFirstDesignator) {
2068 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002069 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002071 return false;
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Douglas Gregor34e79462009-01-28 23:36:17 +00002074 if (!FinishSubobjectInit)
2075 return false;
2076
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002077 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002078 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002080 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002081 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002082 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002083}
2084
Douglas Gregor4c678342009-01-28 21:54:33 +00002085// Get the structured initializer list for a subobject of type
2086// @p CurrentObjectType.
2087InitListExpr *
2088InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2089 QualType CurrentObjectType,
2090 InitListExpr *StructuredList,
2091 unsigned StructuredIndex,
2092 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002093 if (VerifyOnly)
2094 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002095 Expr *ExistingInit = 0;
2096 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002097 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002098 else if (StructuredIndex < StructuredList->getNumInits())
2099 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Douglas Gregor4c678342009-01-28 21:54:33 +00002101 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2102 return Result;
2103
2104 if (ExistingInit) {
2105 // We are creating an initializer list that initializes the
2106 // subobjects of the current object, but there was already an
2107 // initialization that completely initialized the current
2108 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002109 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002110 // struct X { int a, b; };
2111 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002112 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002113 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2114 // designated initializer re-initializes the whole
2115 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002116 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002117 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002118 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002119 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002120 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002121 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002122 << ExistingInit->getSourceRange();
2123 }
2124
Mike Stump1eb44332009-09-09 15:08:12 +00002125 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002126 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002127 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002128 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002129
Eli Friedman5c89c392012-02-23 02:25:10 +00002130 QualType ResultType = CurrentObjectType;
2131 if (!ResultType->isArrayType())
2132 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2133 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002134
Douglas Gregorfa219202009-03-20 23:58:33 +00002135 // Pre-allocate storage for the structured initializer list.
2136 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002137 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002138 bool GotNumInits = false;
2139 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002140 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002141 GotNumInits = true;
2142 } else if (Index < IList->getNumInits()) {
2143 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002144 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002145 GotNumInits = true;
2146 }
Douglas Gregor08457732009-03-21 18:13:52 +00002147 }
2148
Mike Stump1eb44332009-09-09 15:08:12 +00002149 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002150 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2151 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2152 NumElements = CAType->getSize().getZExtValue();
2153 // Simple heuristic so that we don't allocate a very large
2154 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002155 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002156 NumElements = 0;
2157 }
John McCall183700f2009-09-21 23:43:11 +00002158 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002159 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002160 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002161 RecordDecl *RDecl = RType->getDecl();
2162 if (RDecl->isUnion())
2163 NumElements = 1;
2164 else
Mike Stump1eb44332009-09-09 15:08:12 +00002165 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002166 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002167 }
2168
Ted Kremenek709210f2010-04-13 23:39:13 +00002169 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002170
Douglas Gregor4c678342009-01-28 21:54:33 +00002171 // Link this new initializer list into the structured initializer
2172 // lists.
2173 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002174 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002175 else {
2176 Result->setSyntacticForm(IList);
2177 SyntacticToSemantic[IList] = Result;
2178 }
2179
2180 return Result;
2181}
2182
2183/// Update the initializer at index @p StructuredIndex within the
2184/// structured initializer list to the value @p expr.
2185void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2186 unsigned &StructuredIndex,
2187 Expr *expr) {
2188 // No structured initializer list to update
2189 if (!StructuredList)
2190 return;
2191
Ted Kremenek709210f2010-04-13 23:39:13 +00002192 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2193 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002194 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002195 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002196 diag::warn_initializer_overrides)
2197 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002198 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002199 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002200 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002201 << PrevInit->getSourceRange();
2202 }
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Douglas Gregor4c678342009-01-28 21:54:33 +00002204 ++StructuredIndex;
2205}
2206
Douglas Gregor05c13a32009-01-22 00:58:24 +00002207/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002208/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002209/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002210/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002211/// failure. Returns the index expression, possibly with an implicit cast
2212/// added, on success. If everything went okay, Value will receive the
2213/// value of the constant expression.
2214static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002215CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002216 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002217
2218 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002219 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2220 if (Result.isInvalid())
2221 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002222
Chris Lattner3bf68932009-04-25 21:59:05 +00002223 if (Value.isSigned() && Value.isNegative())
2224 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002225 << Value.toString(10) << Index->getSourceRange();
2226
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002227 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002228 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002229}
2230
John McCall60d7b3a2010-08-24 06:29:42 +00002231ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002232 SourceLocation Loc,
2233 bool GNUSyntax,
2234 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002235 typedef DesignatedInitExpr::Designator ASTDesignator;
2236
2237 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002238 SmallVector<ASTDesignator, 32> Designators;
2239 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002240
2241 // Build designators and check array designator expressions.
2242 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2243 const Designator &D = Desig.getDesignator(Idx);
2244 switch (D.getKind()) {
2245 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002246 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002247 D.getFieldLoc()));
2248 break;
2249
2250 case Designator::ArrayDesignator: {
2251 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2252 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002253 if (!Index->isTypeDependent() && !Index->isValueDependent())
2254 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2255 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002256 Invalid = true;
2257 else {
2258 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002259 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002260 D.getRBracketLoc()));
2261 InitExpressions.push_back(Index);
2262 }
2263 break;
2264 }
2265
2266 case Designator::ArrayRangeDesignator: {
2267 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2268 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2269 llvm::APSInt StartValue;
2270 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002271 bool StartDependent = StartIndex->isTypeDependent() ||
2272 StartIndex->isValueDependent();
2273 bool EndDependent = EndIndex->isTypeDependent() ||
2274 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002275 if (!StartDependent)
2276 StartIndex =
2277 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2278 if (!EndDependent)
2279 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2280
2281 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002282 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002283 else {
2284 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002285 if (StartDependent || EndDependent) {
2286 // Nothing to compute.
2287 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002288 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002289 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002290 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002291
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002292 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002293 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002294 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002295 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2296 Invalid = true;
2297 } else {
2298 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002299 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002300 D.getEllipsisLoc(),
2301 D.getRBracketLoc()));
2302 InitExpressions.push_back(StartIndex);
2303 InitExpressions.push_back(EndIndex);
2304 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002305 }
2306 break;
2307 }
2308 }
2309 }
2310
2311 if (Invalid || Init.isInvalid())
2312 return ExprError();
2313
2314 // Clear out the expressions within the designation.
2315 Desig.ClearExprs(*this);
2316
2317 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002318 = DesignatedInitExpr::Create(Context,
2319 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002320 InitExpressions, Loc, GNUSyntax,
2321 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002322
David Blaikie4e4d0842012-03-11 07:00:24 +00002323 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002324 Diag(DIE->getLocStart(), diag::ext_designated_init)
2325 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002326
Douglas Gregor05c13a32009-01-22 00:58:24 +00002327 return Owned(DIE);
2328}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002329
Douglas Gregor20093b42009-12-09 23:02:17 +00002330//===----------------------------------------------------------------------===//
2331// Initialization entity
2332//===----------------------------------------------------------------------===//
2333
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002334InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002335 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002336 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002337{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002338 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2339 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002340 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002341 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002342 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002343 Type = VT->getElementType();
2344 } else {
2345 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2346 assert(CT && "Unexpected type");
2347 Kind = EK_ComplexElement;
2348 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002349 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002350}
2351
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002352InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002353 CXXBaseSpecifier *Base,
2354 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002355{
2356 InitializedEntity Result;
2357 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002358 Result.Base = reinterpret_cast<uintptr_t>(Base);
2359 if (IsInheritedVirtualBase)
2360 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002361
Douglas Gregord6542d82009-12-22 15:35:07 +00002362 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002363 return Result;
2364}
2365
Douglas Gregor99a2e602009-12-16 01:38:02 +00002366DeclarationName InitializedEntity::getName() const {
2367 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002368 case EK_Parameter: {
2369 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2370 return (D ? D->getDeclName() : DeclarationName());
2371 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002372
2373 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002374 case EK_Member:
2375 return VariableOrMember->getDeclName();
2376
Douglas Gregor47736542012-02-15 16:57:26 +00002377 case EK_LambdaCapture:
2378 return Capture.Var->getDeclName();
2379
Douglas Gregor99a2e602009-12-16 01:38:02 +00002380 case EK_Result:
2381 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002382 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002383 case EK_Temporary:
2384 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002385 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002386 case EK_ArrayElement:
2387 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002388 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002389 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002390 return DeclarationName();
2391 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002392
David Blaikie7530c032012-01-17 06:56:22 +00002393 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002394}
2395
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002396DeclaratorDecl *InitializedEntity::getDecl() const {
2397 switch (getKind()) {
2398 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002399 case EK_Member:
2400 return VariableOrMember;
2401
John McCallf85e1932011-06-15 23:02:42 +00002402 case EK_Parameter:
2403 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2404
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002405 case EK_Result:
2406 case EK_Exception:
2407 case EK_New:
2408 case EK_Temporary:
2409 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002410 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002411 case EK_ArrayElement:
2412 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002413 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002414 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002415 case EK_LambdaCapture:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002416 return 0;
2417 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002418
David Blaikie7530c032012-01-17 06:56:22 +00002419 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002420}
2421
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002422bool InitializedEntity::allowsNRVO() const {
2423 switch (getKind()) {
2424 case EK_Result:
2425 case EK_Exception:
2426 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002427
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002428 case EK_Variable:
2429 case EK_Parameter:
2430 case EK_Member:
2431 case EK_New:
2432 case EK_Temporary:
2433 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002434 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002435 case EK_ArrayElement:
2436 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002437 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002438 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002439 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002440 break;
2441 }
2442
2443 return false;
2444}
2445
Douglas Gregor20093b42009-12-09 23:02:17 +00002446//===----------------------------------------------------------------------===//
2447// Initialization sequence
2448//===----------------------------------------------------------------------===//
2449
2450void InitializationSequence::Step::Destroy() {
2451 switch (Kind) {
2452 case SK_ResolveAddressOfOverloadedFunction:
2453 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002454 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002455 case SK_CastDerivedToBaseLValue:
2456 case SK_BindReference:
2457 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002458 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002459 case SK_UserConversion:
2460 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002461 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002462 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002463 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002464 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002465 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002466 case SK_UnwrapInitList:
2467 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002468 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002469 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002470 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002471 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002472 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002473 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002474 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002475 case SK_PassByIndirectCopyRestore:
2476 case SK_PassByIndirectRestore:
2477 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002478 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002479 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002480 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002481 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002482
Douglas Gregor20093b42009-12-09 23:02:17 +00002483 case SK_ConversionSequence:
2484 delete ICS;
2485 }
2486}
2487
Douglas Gregorb70cf442010-03-26 20:14:36 +00002488bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002489 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002490}
2491
2492bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002493 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002494 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002495
Douglas Gregorb70cf442010-03-26 20:14:36 +00002496 switch (getFailureKind()) {
2497 case FK_TooManyInitsForReference:
2498 case FK_ArrayNeedsInitList:
2499 case FK_ArrayNeedsInitListOrStringLiteral:
2500 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2501 case FK_NonConstLValueReferenceBindingToTemporary:
2502 case FK_NonConstLValueReferenceBindingToUnrelated:
2503 case FK_RValueReferenceBindingToLValue:
2504 case FK_ReferenceInitDropsQualifiers:
2505 case FK_ReferenceInitFailed:
2506 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002507 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002508 case FK_TooManyInitsForScalar:
2509 case FK_ReferenceBindingToInitList:
2510 case FK_InitListBadDestinationType:
2511 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002512 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002513 case FK_ArrayTypeMismatch:
2514 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002515 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002516 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002517 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002518 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002519 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002520 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002521
Douglas Gregorb70cf442010-03-26 20:14:36 +00002522 case FK_ReferenceInitOverloadFailed:
2523 case FK_UserConversionOverloadFailed:
2524 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002525 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002526 return FailedOverloadResult == OR_Ambiguous;
2527 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002528
David Blaikie7530c032012-01-17 06:56:22 +00002529 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002530}
2531
Douglas Gregord6e44a32010-04-16 22:09:46 +00002532bool InitializationSequence::isConstructorInitialization() const {
2533 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2534}
2535
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002536void
2537InitializationSequence
2538::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2539 DeclAccessPair Found,
2540 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002541 Step S;
2542 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2543 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002544 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002545 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002546 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002547 Steps.push_back(S);
2548}
2549
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002550void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002551 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002552 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002553 switch (VK) {
2554 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2555 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2556 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002557 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 S.Type = BaseType;
2559 Steps.push_back(S);
2560}
2561
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002562void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002563 bool BindingTemporary) {
2564 Step S;
2565 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2566 S.Type = T;
2567 Steps.push_back(S);
2568}
2569
Douglas Gregor523d46a2010-04-18 07:40:54 +00002570void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2571 Step S;
2572 S.Kind = SK_ExtraneousCopyToTemporary;
2573 S.Type = T;
2574 Steps.push_back(S);
2575}
2576
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002577void
2578InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2579 DeclAccessPair FoundDecl,
2580 QualType T,
2581 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002582 Step S;
2583 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002584 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002585 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002586 S.Function.Function = Function;
2587 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002588 Steps.push_back(S);
2589}
2590
2591void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002592 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002593 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002594 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002595 switch (VK) {
2596 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002597 S.Kind = SK_QualificationConversionRValue;
2598 break;
John McCall5baba9d2010-08-25 10:28:54 +00002599 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002600 S.Kind = SK_QualificationConversionXValue;
2601 break;
John McCall5baba9d2010-08-25 10:28:54 +00002602 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002603 S.Kind = SK_QualificationConversionLValue;
2604 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002605 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002606 S.Type = Ty;
2607 Steps.push_back(S);
2608}
2609
Jordan Rose1fd1e282013-04-11 00:58:58 +00002610void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2611 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2612
2613 Step S;
2614 S.Kind = SK_LValueToRValue;
2615 S.Type = Ty;
2616 Steps.push_back(S);
2617}
2618
Douglas Gregor20093b42009-12-09 23:02:17 +00002619void InitializationSequence::AddConversionSequenceStep(
2620 const ImplicitConversionSequence &ICS,
2621 QualType T) {
2622 Step S;
2623 S.Kind = SK_ConversionSequence;
2624 S.Type = T;
2625 S.ICS = new ImplicitConversionSequence(ICS);
2626 Steps.push_back(S);
2627}
2628
Douglas Gregord87b61f2009-12-10 17:56:55 +00002629void InitializationSequence::AddListInitializationStep(QualType T) {
2630 Step S;
2631 S.Kind = SK_ListInitialization;
2632 S.Type = T;
2633 Steps.push_back(S);
2634}
2635
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002636void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002637InitializationSequence
2638::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2639 AccessSpecifier Access,
2640 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002641 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002642 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002643 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002644 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2645 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002646 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002647 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002648 S.Function.Function = Constructor;
2649 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002650 Steps.push_back(S);
2651}
2652
Douglas Gregor71d17402009-12-15 00:01:57 +00002653void InitializationSequence::AddZeroInitializationStep(QualType T) {
2654 Step S;
2655 S.Kind = SK_ZeroInitialization;
2656 S.Type = T;
2657 Steps.push_back(S);
2658}
2659
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002660void InitializationSequence::AddCAssignmentStep(QualType T) {
2661 Step S;
2662 S.Kind = SK_CAssignment;
2663 S.Type = T;
2664 Steps.push_back(S);
2665}
2666
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002667void InitializationSequence::AddStringInitStep(QualType T) {
2668 Step S;
2669 S.Kind = SK_StringInit;
2670 S.Type = T;
2671 Steps.push_back(S);
2672}
2673
Douglas Gregor569c3162010-08-07 11:51:51 +00002674void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2675 Step S;
2676 S.Kind = SK_ObjCObjectConversion;
2677 S.Type = T;
2678 Steps.push_back(S);
2679}
2680
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002681void InitializationSequence::AddArrayInitStep(QualType T) {
2682 Step S;
2683 S.Kind = SK_ArrayInit;
2684 S.Type = T;
2685 Steps.push_back(S);
2686}
2687
Richard Smith0f163e92012-02-15 22:38:09 +00002688void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2689 Step S;
2690 S.Kind = SK_ParenthesizedArrayInit;
2691 S.Type = T;
2692 Steps.push_back(S);
2693}
2694
John McCallf85e1932011-06-15 23:02:42 +00002695void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2696 bool shouldCopy) {
2697 Step s;
2698 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2699 : SK_PassByIndirectRestore);
2700 s.Type = type;
2701 Steps.push_back(s);
2702}
2703
2704void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2705 Step S;
2706 S.Kind = SK_ProduceObjCObject;
2707 S.Type = T;
2708 Steps.push_back(S);
2709}
2710
Sebastian Redl2b916b82012-01-17 22:49:42 +00002711void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2712 Step S;
2713 S.Kind = SK_StdInitializerList;
2714 S.Type = T;
2715 Steps.push_back(S);
2716}
2717
Guy Benyei21f18c42013-02-07 10:55:47 +00002718void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2719 Step S;
2720 S.Kind = SK_OCLSamplerInit;
2721 S.Type = T;
2722 Steps.push_back(S);
2723}
2724
Guy Benyeie6b9d802013-01-20 12:31:11 +00002725void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2726 Step S;
2727 S.Kind = SK_OCLZeroEvent;
2728 S.Type = T;
2729 Steps.push_back(S);
2730}
2731
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002732void InitializationSequence::RewrapReferenceInitList(QualType T,
2733 InitListExpr *Syntactic) {
2734 assert(Syntactic->getNumInits() == 1 &&
2735 "Can only rewrap trivial init lists.");
2736 Step S;
2737 S.Kind = SK_UnwrapInitList;
2738 S.Type = Syntactic->getInit(0)->getType();
2739 Steps.insert(Steps.begin(), S);
2740
2741 S.Kind = SK_RewrapInitList;
2742 S.Type = T;
2743 S.WrappingSyntacticList = Syntactic;
2744 Steps.push_back(S);
2745}
2746
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002747void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002748 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002749 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002750 this->Failure = Failure;
2751 this->FailedOverloadResult = Result;
2752}
2753
2754//===----------------------------------------------------------------------===//
2755// Attempt initialization
2756//===----------------------------------------------------------------------===//
2757
John McCallf85e1932011-06-15 23:02:42 +00002758static void MaybeProduceObjCObject(Sema &S,
2759 InitializationSequence &Sequence,
2760 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002761 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002762
2763 /// When initializing a parameter, produce the value if it's marked
2764 /// __attribute__((ns_consumed)).
2765 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2766 if (!Entity.isParameterConsumed())
2767 return;
2768
2769 assert(Entity.getType()->isObjCRetainableType() &&
2770 "consuming an object of unretainable type?");
2771 Sequence.AddProduceObjCObjectStep(Entity.getType());
2772
2773 /// When initializing a return value, if the return type is a
2774 /// retainable type, then returns need to immediately retain the
2775 /// object. If an autorelease is required, it will be done at the
2776 /// last instant.
2777 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2778 if (!Entity.getType()->isObjCRetainableType())
2779 return;
2780
2781 Sequence.AddProduceObjCObjectStep(Entity.getType());
2782 }
2783}
2784
Richard Smithf4bb8d02012-07-05 08:39:21 +00002785/// \brief When initializing from init list via constructor, handle
2786/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002787///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002788/// \return true if we have handled initialization of an object of type
2789/// std::initializer_list<T>, false otherwise.
2790static bool TryInitializerListConstruction(Sema &S,
2791 InitListExpr *List,
2792 QualType DestType,
2793 InitializationSequence &Sequence) {
2794 QualType E;
2795 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002796 return false;
2797
Richard Smithf4bb8d02012-07-05 08:39:21 +00002798 // Check that each individual element can be copy-constructed. But since we
2799 // have no place to store further information, we'll recalculate everything
2800 // later.
2801 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2802 S.Context.getConstantArrayType(E,
2803 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2804 List->getNumInits()),
2805 ArrayType::Normal, 0));
2806 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2807 0, HiddenArray);
2808 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2809 Element.setElementIndex(i);
2810 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2811 Sequence.SetFailed(
2812 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002813 return true;
2814 }
2815 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002816 Sequence.AddStdInitializerListConstructionStep(DestType);
2817 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002818}
2819
Sebastian Redl96715b22012-02-04 21:27:39 +00002820static OverloadingResult
2821ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002822 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002823 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002824 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002825 OverloadCandidateSet::iterator &Best,
2826 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002827 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002828 CandidateSet.clear();
2829
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002830 for (ArrayRef<NamedDecl *>::iterator
2831 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002832 NamedDecl *D = *Con;
2833 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2834 bool SuppressUserConversions = false;
2835
2836 // Find the constructor (which may be a template).
2837 CXXConstructorDecl *Constructor = 0;
2838 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2839 if (ConstructorTmpl)
2840 Constructor = cast<CXXConstructorDecl>(
2841 ConstructorTmpl->getTemplatedDecl());
2842 else {
2843 Constructor = cast<CXXConstructorDecl>(D);
2844
2845 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002846 // suppress user-defined conversions on the arguments. We do the same for
2847 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002848 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002849 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002850 SuppressUserConversions = true;
2851 }
2852
2853 if (!Constructor->isInvalidDecl() &&
2854 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002855 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002856 if (ConstructorTmpl)
2857 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002858 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002859 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002860 else {
2861 // C++ [over.match.copy]p1:
2862 // - When initializing a temporary to be bound to the first parameter
2863 // of a constructor that takes a reference to possibly cv-qualified
2864 // T as its first argument, called with a single argument in the
2865 // context of direct-initialization, explicit conversion functions
2866 // are also considered.
2867 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002868 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00002869 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002870 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002871 SuppressUserConversions,
2872 /*PartialOverloading=*/false,
2873 /*AllowExplicit=*/AllowExplicitConv);
2874 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002875 }
2876 }
2877
2878 // Perform overload resolution and return the result.
2879 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2880}
2881
Sebastian Redl10f04a62011-12-22 14:44:04 +00002882/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2883/// enumerates the constructors of the initialized entity and performs overload
2884/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002885/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002886/// class type.
2887static void TryConstructorInitialization(Sema &S,
2888 const InitializedEntity &Entity,
2889 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002890 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002891 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002892 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002893 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00002894 "InitListSyntax must come with a single initializer list argument.");
2895
Sebastian Redl10f04a62011-12-22 14:44:04 +00002896 // The type we're constructing needs to be complete.
2897 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002898 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002899 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002900 }
2901
2902 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2903 assert(DestRecordType && "Constructor initialization requires record type");
2904 CXXRecordDecl *DestRecordDecl
2905 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2906
Sebastian Redl96715b22012-02-04 21:27:39 +00002907 // Build the candidate set directly in the initialization sequence
2908 // structure, so that it will persist if we fail.
2909 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2910
2911 // Determine whether we are allowed to call explicit constructors or
2912 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002913 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002914 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002915
Sebastian Redl10f04a62011-12-22 14:44:04 +00002916 // - Otherwise, if T is a class type, constructors are considered. The
2917 // applicable constructors are enumerated, and the best one is chosen
2918 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00002919 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002920 // The container holding the constructors can under certain conditions
2921 // be changed while iterating (e.g. because of deserialization).
2922 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00002923 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00002924
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002925 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002926 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002927 bool AsInitializerList = false;
2928
2929 // C++11 [over.match.list]p1:
2930 // When objects of non-aggregate type T are list-initialized, overload
2931 // resolution selects the constructor in two phases:
2932 // - Initially, the candidate functions are the initializer-list
2933 // constructors of the class T and the argument list consists of the
2934 // initializer list as a single argument.
2935 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002936 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002937 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00002938
2939 // If the initializer list has no elements and T has a default constructor,
2940 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00002941 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002942 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002943 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00002944 CopyInitialization, AllowExplicit,
2945 /*OnlyListConstructor=*/true,
2946 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002947
2948 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002949 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002950 }
2951
2952 // C++11 [over.match.list]p1:
2953 // - If no viable initializer-list constructor is found, overload resolution
2954 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00002955 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002956 // elements of the initializer list.
2957 if (Result == OR_No_Viable_Function) {
2958 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002959 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002960 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002961 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002962 /*OnlyListConstructors=*/false,
2963 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002964 }
2965 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002966 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002967 InitializationSequence::FK_ListConstructorOverloadFailed :
2968 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002969 Result);
2970 return;
2971 }
2972
Richard Smithf4bb8d02012-07-05 08:39:21 +00002973 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002974 // If a program calls for the default initialization of an object
2975 // of a const-qualified type T, T shall be a class type with a
2976 // user-provided default constructor.
2977 if (Kind.getKind() == InitializationKind::IK_Default &&
2978 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00002979 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002980 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2981 return;
2982 }
2983
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002984 // C++11 [over.match.list]p1:
2985 // In copy-list-initialization, if an explicit constructor is chosen, the
2986 // initializer is ill-formed.
2987 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2988 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2989 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2990 return;
2991 }
2992
Sebastian Redl10f04a62011-12-22 14:44:04 +00002993 // Add the constructor initialization step. Any cv-qualification conversion is
2994 // subsumed by the initialization.
2995 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002996 Sequence.AddConstructorInitializationStep(CtorDecl,
2997 Best->FoundDecl.getAccess(),
2998 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002999 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003000}
3001
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003002static bool
3003ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3004 Expr *Initializer,
3005 QualType &SourceType,
3006 QualType &UnqualifiedSourceType,
3007 QualType UnqualifiedTargetType,
3008 InitializationSequence &Sequence) {
3009 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3010 S.Context.OverloadTy) {
3011 DeclAccessPair Found;
3012 bool HadMultipleCandidates = false;
3013 if (FunctionDecl *Fn
3014 = S.ResolveAddressOfOverloadedFunction(Initializer,
3015 UnqualifiedTargetType,
3016 false, Found,
3017 &HadMultipleCandidates)) {
3018 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3019 HadMultipleCandidates);
3020 SourceType = Fn->getType();
3021 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3022 } else if (!UnqualifiedTargetType->isRecordType()) {
3023 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3024 return true;
3025 }
3026 }
3027 return false;
3028}
3029
3030static void TryReferenceInitializationCore(Sema &S,
3031 const InitializedEntity &Entity,
3032 const InitializationKind &Kind,
3033 Expr *Initializer,
3034 QualType cv1T1, QualType T1,
3035 Qualifiers T1Quals,
3036 QualType cv2T2, QualType T2,
3037 Qualifiers T2Quals,
3038 InitializationSequence &Sequence);
3039
Richard Smithf4bb8d02012-07-05 08:39:21 +00003040static void TryValueInitialization(Sema &S,
3041 const InitializedEntity &Entity,
3042 const InitializationKind &Kind,
3043 InitializationSequence &Sequence,
3044 InitListExpr *InitList = 0);
3045
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003046static void TryListInitialization(Sema &S,
3047 const InitializedEntity &Entity,
3048 const InitializationKind &Kind,
3049 InitListExpr *InitList,
3050 InitializationSequence &Sequence);
3051
3052/// \brief Attempt list initialization of a reference.
3053static void TryReferenceListInitialization(Sema &S,
3054 const InitializedEntity &Entity,
3055 const InitializationKind &Kind,
3056 InitListExpr *InitList,
3057 InitializationSequence &Sequence)
3058{
3059 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003060 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003061 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3062 return;
3063 }
3064
3065 QualType DestType = Entity.getType();
3066 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3067 Qualifiers T1Quals;
3068 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3069
3070 // Reference initialization via an initializer list works thus:
3071 // If the initializer list consists of a single element that is
3072 // reference-related to the referenced type, bind directly to that element
3073 // (possibly creating temporaries).
3074 // Otherwise, initialize a temporary with the initializer list and
3075 // bind to that.
3076 if (InitList->getNumInits() == 1) {
3077 Expr *Initializer = InitList->getInit(0);
3078 QualType cv2T2 = Initializer->getType();
3079 Qualifiers T2Quals;
3080 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3081
3082 // If this fails, creating a temporary wouldn't work either.
3083 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3084 T1, Sequence))
3085 return;
3086
3087 SourceLocation DeclLoc = Initializer->getLocStart();
3088 bool dummy1, dummy2, dummy3;
3089 Sema::ReferenceCompareResult RefRelationship
3090 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3091 dummy2, dummy3);
3092 if (RefRelationship >= Sema::Ref_Related) {
3093 // Try to bind the reference here.
3094 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3095 T1Quals, cv2T2, T2, T2Quals, Sequence);
3096 if (Sequence)
3097 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3098 return;
3099 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003100
3101 // Update the initializer if we've resolved an overloaded function.
3102 if (Sequence.step_begin() != Sequence.step_end())
3103 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003104 }
3105
3106 // Not reference-related. Create a temporary and bind to that.
3107 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3108
3109 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3110 if (Sequence) {
3111 if (DestType->isRValueReferenceType() ||
3112 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3113 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3114 else
3115 Sequence.SetFailed(
3116 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3117 }
3118}
3119
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003120/// \brief Attempt list initialization (C++0x [dcl.init.list])
3121static void TryListInitialization(Sema &S,
3122 const InitializedEntity &Entity,
3123 const InitializationKind &Kind,
3124 InitListExpr *InitList,
3125 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003126 QualType DestType = Entity.getType();
3127
Sebastian Redl14b0c192011-09-24 17:48:00 +00003128 // C++ doesn't allow scalar initialization with more than one argument.
3129 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003130 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003131 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3132 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3133 return;
3134 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003135 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003136 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003137 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003138 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003139 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003140 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003141 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003142 return;
3143 }
3144
Richard Smithf4bb8d02012-07-05 08:39:21 +00003145 // C++11 [dcl.init.list]p3:
3146 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003147 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003148 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003149 // - Otherwise, if the initializer list has no elements and T is a
3150 // class type with a default constructor, the object is
3151 // value-initialized.
3152 if (InitList->getNumInits() == 0) {
3153 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003154 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003155 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3156 return;
3157 }
3158 }
3159
3160 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3161 // an initializer_list object constructed [...]
3162 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3163 return;
3164
3165 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003166 Expr *InitListAsExpr = InitList;
3167 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003168 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003169 } else
3170 Sequence.SetFailed(
3171 InitializationSequence::FK_InitListBadDestinationType);
3172 return;
3173 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003174 }
3175
Sebastian Redl14b0c192011-09-24 17:48:00 +00003176 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003177 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003178 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00003179 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003180 if (CheckInitList.HadError()) {
3181 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3182 return;
3183 }
3184
3185 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003186 Sequence.AddListInitializationStep(DestType);
3187}
Douglas Gregor20093b42009-12-09 23:02:17 +00003188
3189/// \brief Try a reference initialization that involves calling a conversion
3190/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003191static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3192 const InitializedEntity &Entity,
3193 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003194 Expr *Initializer,
3195 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003196 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003197 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003198 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3199 QualType T1 = cv1T1.getUnqualifiedType();
3200 QualType cv2T2 = Initializer->getType();
3201 QualType T2 = cv2T2.getUnqualifiedType();
3202
3203 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003204 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003205 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003206 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003207 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003208 ObjCConversion,
3209 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003210 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003211 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003212 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003213 (void)ObjCLifetimeConversion;
3214
Douglas Gregor20093b42009-12-09 23:02:17 +00003215 // Build the candidate set directly in the initialization sequence
3216 // structure, so that it will persist if we fail.
3217 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3218 CandidateSet.clear();
3219
3220 // Determine whether we are allowed to call explicit constructors or
3221 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003222 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003223 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3224
Douglas Gregor20093b42009-12-09 23:02:17 +00003225 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003226 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3227 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003228 // The type we're converting to is a class type. Enumerate its constructors
3229 // to see if there is a suitable conversion.
3230 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003231
David Blaikie3bc93e32012-12-19 00:45:41 +00003232 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003233 // The container holding the constructors can under certain conditions
3234 // be changed while iterating (e.g. because of deserialization).
3235 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003236 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003237 for (SmallVector<NamedDecl*, 16>::iterator
3238 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3239 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003240 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3241
Douglas Gregor20093b42009-12-09 23:02:17 +00003242 // Find the constructor (which may be a template).
3243 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003244 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003245 if (ConstructorTmpl)
3246 Constructor = cast<CXXConstructorDecl>(
3247 ConstructorTmpl->getTemplatedDecl());
3248 else
John McCall9aa472c2010-03-19 07:35:19 +00003249 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003250
Douglas Gregor20093b42009-12-09 23:02:17 +00003251 if (!Constructor->isInvalidDecl() &&
3252 Constructor->isConvertingConstructor(AllowExplicit)) {
3253 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003254 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003255 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003256 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003257 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003258 else
John McCall9aa472c2010-03-19 07:35:19 +00003259 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003260 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003261 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003262 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003264 }
John McCall572fc622010-08-17 07:23:57 +00003265 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3266 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003267
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003268 const RecordType *T2RecordType = 0;
3269 if ((T2RecordType = T2->getAs<RecordType>()) &&
3270 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003271 // The type we're converting from is a class type, enumerate its conversion
3272 // functions.
3273 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3274
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003275 std::pair<CXXRecordDecl::conversion_iterator,
3276 CXXRecordDecl::conversion_iterator>
3277 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3278 for (CXXRecordDecl::conversion_iterator
3279 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003280 NamedDecl *D = *I;
3281 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3282 if (isa<UsingShadowDecl>(D))
3283 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003284
Douglas Gregor20093b42009-12-09 23:02:17 +00003285 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3286 CXXConversionDecl *Conv;
3287 if (ConvTemplate)
3288 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3289 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003290 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003291
Douglas Gregor20093b42009-12-09 23:02:17 +00003292 // If the conversion function doesn't return a reference type,
3293 // it can't be considered for this conversion unless we're allowed to
3294 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003295 // FIXME: Do we need to make sure that we only consider conversion
3296 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003297 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003298 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003299 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3300 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003301 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003302 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003303 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003304 else
John McCall9aa472c2010-03-19 07:35:19 +00003305 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003306 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003307 }
3308 }
3309 }
John McCall572fc622010-08-17 07:23:57 +00003310 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3311 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003312
Douglas Gregor20093b42009-12-09 23:02:17 +00003313 SourceLocation DeclLoc = Initializer->getLocStart();
3314
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003315 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003316 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003317 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003318 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003319 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003320
Douglas Gregor20093b42009-12-09 23:02:17 +00003321 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003322 // This is the overload that will be used for this initialization step if we
3323 // use this initialization. Mark it as referenced.
3324 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003325
Eli Friedman03981012009-12-11 02:42:07 +00003326 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003327 if (isa<CXXConversionDecl>(Function))
3328 T2 = Function->getResultType();
3329 else
3330 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003331
3332 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003333 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003334 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003335 T2.getNonLValueExprType(S.Context),
3336 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003337
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003339 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003340 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003341 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003342 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003343 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003344 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003345
Douglas Gregor20093b42009-12-09 23:02:17 +00003346 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003347 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003348 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003349 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003350 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003351 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003352 NewDerivedToBase, NewObjCConversion,
3353 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003354 if (NewRefRelationship == Sema::Ref_Incompatible) {
3355 // If the type we've converted to is not reference-related to the
3356 // type we're looking for, then there is another conversion step
3357 // we need to perform to produce a temporary of the right type
3358 // that we'll be binding to.
3359 ImplicitConversionSequence ICS;
3360 ICS.setStandard();
3361 ICS.Standard = Best->FinalConversion;
3362 T2 = ICS.Standard.getToType(2);
3363 Sequence.AddConversionSequenceStep(ICS, T2);
3364 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003365 Sequence.AddDerivedToBaseCastStep(
3366 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003367 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003368 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003369 else if (NewObjCConversion)
3370 Sequence.AddObjCObjectConversionStep(
3371 S.Context.getQualifiedType(T1,
3372 T2.getNonReferenceType().getQualifiers()));
3373
Douglas Gregor20093b42009-12-09 23:02:17 +00003374 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003375 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003376
Douglas Gregor20093b42009-12-09 23:02:17 +00003377 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3378 return OR_Success;
3379}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003380
Richard Smith83da2e72011-10-19 16:55:56 +00003381static void CheckCXX98CompatAccessibleCopy(Sema &S,
3382 const InitializedEntity &Entity,
3383 Expr *CurInitExpr);
3384
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3386static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003387 const InitializedEntity &Entity,
3388 const InitializationKind &Kind,
3389 Expr *Initializer,
3390 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003391 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003392 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003393 Qualifiers T1Quals;
3394 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003395 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003396 Qualifiers T2Quals;
3397 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003398
Douglas Gregor20093b42009-12-09 23:02:17 +00003399 // If the initializer is the address of an overloaded function, try
3400 // to resolve the overloaded function. If all goes well, T2 is the
3401 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003402 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3403 T1, Sequence))
3404 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003405
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003406 // Delegate everything else to a subfunction.
3407 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3408 T1Quals, cv2T2, T2, T2Quals, Sequence);
3409}
3410
Jordan Rose1fd1e282013-04-11 00:58:58 +00003411/// Converts the target of reference initialization so that it has the
3412/// appropriate qualifiers and value kind.
3413///
3414/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3415/// \code
3416/// int x;
3417/// const int &r = x;
3418/// \endcode
3419///
3420/// In this case the reference is binding to a bitfield lvalue, which isn't
3421/// valid. Perform a load to create a lifetime-extended temporary instead.
3422/// \code
3423/// const int &r = someStruct.bitfield;
3424/// \endcode
3425static ExprValueKind
3426convertQualifiersAndValueKindIfNecessary(Sema &S,
3427 InitializationSequence &Sequence,
3428 Expr *Initializer,
3429 QualType cv1T1,
3430 Qualifiers T1Quals,
3431 Qualifiers T2Quals,
3432 bool IsLValueRef) {
3433 bool IsNonAddressableType = Initializer->getBitField() ||
3434 Initializer->refersToVectorElement();
3435
3436 if (IsNonAddressableType) {
3437 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3438 // lvalue reference to a non-volatile const type, or the reference shall be
3439 // an rvalue reference.
3440 //
3441 // If not, we can't make a temporary and bind to that. Give up and allow the
3442 // error to be diagnosed later.
3443 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3444 assert(Initializer->isGLValue());
3445 return Initializer->getValueKind();
3446 }
3447
3448 // Force a load so we can materialize a temporary.
3449 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3450 return VK_RValue;
3451 }
3452
3453 if (T1Quals != T2Quals) {
3454 Sequence.AddQualificationConversionStep(cv1T1,
3455 Initializer->getValueKind());
3456 }
3457
3458 return Initializer->getValueKind();
3459}
3460
3461
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003462/// \brief Reference initialization without resolving overloaded functions.
3463static void TryReferenceInitializationCore(Sema &S,
3464 const InitializedEntity &Entity,
3465 const InitializationKind &Kind,
3466 Expr *Initializer,
3467 QualType cv1T1, QualType T1,
3468 Qualifiers T1Quals,
3469 QualType cv2T2, QualType T2,
3470 Qualifiers T2Quals,
3471 InitializationSequence &Sequence) {
3472 QualType DestType = Entity.getType();
3473 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003474 // Compute some basic properties of the types and the initializer.
3475 bool isLValueRef = DestType->isLValueReferenceType();
3476 bool isRValueRef = !isLValueRef;
3477 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003478 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003479 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003480 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003481 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003482 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003483 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003484
Douglas Gregor20093b42009-12-09 23:02:17 +00003485 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003487 // "cv2 T2" as follows:
3488 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003489 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003490 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003491 // Note the analogous bullet points for rvlaue refs to functions. Because
3492 // there are no function rvalues in C++, rvalue refs to functions are treated
3493 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003494 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003495 bool T1Function = T1->isFunctionType();
3496 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003497 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003498 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003499 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003500 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003501 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003502 // reference-compatible with "cv2 T2," or
3503 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003505 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003506 // can occur. However, we do pay attention to whether it is a bit-field
3507 // to decide whether we're actually binding to a temporary created from
3508 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003509 if (DerivedToBase)
3510 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003511 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003512 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003513 else if (ObjCConversion)
3514 Sequence.AddObjCObjectConversionStep(
3515 S.Context.getQualifiedType(T1, T2Quals));
3516
Jordan Rose1fd1e282013-04-11 00:58:58 +00003517 ExprValueKind ValueKind =
3518 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3519 cv1T1, T1Quals, T2Quals,
3520 isLValueRef);
3521 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003522 return;
3523 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003524
3525 // - has a class type (i.e., T2 is a class type), where T1 is not
3526 // reference-related to T2, and can be implicitly converted to an
3527 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3528 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003529 // applicable conversion functions (13.3.1.6) and choosing the best
3530 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003531 // If we have an rvalue ref to function type here, the rhs must be
3532 // an rvalue.
3533 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3534 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003535 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003536 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003537 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003538 Sequence);
3539 if (ConvOvlResult == OR_Success)
3540 return;
John McCall1d318332010-01-12 00:44:57 +00003541 if (ConvOvlResult != OR_No_Viable_Function) {
3542 Sequence.SetOverloadFailure(
3543 InitializationSequence::FK_ReferenceInitOverloadFailed,
3544 ConvOvlResult);
3545 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003546 }
3547 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003548
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003550 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003551 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003552 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003553 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3554 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3555 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003556 Sequence.SetOverloadFailure(
3557 InitializationSequence::FK_ReferenceInitOverloadFailed,
3558 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003559 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003560 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003561 ? (RefRelationship == Sema::Ref_Related
3562 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3563 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3564 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003565
Douglas Gregor20093b42009-12-09 23:02:17 +00003566 return;
3567 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003568
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003569 // - If the initializer expression
3570 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3571 // "cv1 T1" is reference-compatible with "cv2 T2"
3572 // Note: functions are handled below.
3573 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003574 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003575 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003576 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003577 (InitCategory.isXValue() ||
3578 (InitCategory.isPRValue() && T2->isRecordType()) ||
3579 (InitCategory.isPRValue() && T2->isArrayType()))) {
3580 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3581 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003582 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3583 // compiler the freedom to perform a copy here or bind to the
3584 // object, while C++0x requires that we bind directly to the
3585 // object. Hence, we always bind to the object without making an
3586 // extra copy. However, in C++03 requires that we check for the
3587 // presence of a suitable copy constructor:
3588 //
3589 // The constructor that would be used to make the copy shall
3590 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003591 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003592 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003593 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003594 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003595 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003597 if (DerivedToBase)
3598 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3599 ValueKind);
3600 else if (ObjCConversion)
3601 Sequence.AddObjCObjectConversionStep(
3602 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003603
Jordan Rose1fd1e282013-04-11 00:58:58 +00003604 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3605 Initializer, cv1T1,
3606 T1Quals, T2Quals,
3607 isLValueRef);
3608
3609 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003610 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003611 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003612
3613 // - has a class type (i.e., T2 is a class type), where T1 is not
3614 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003615 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3616 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003617 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003618 if (RefRelationship == Sema::Ref_Incompatible) {
3619 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3620 Kind, Initializer,
3621 /*AllowRValues=*/true,
3622 Sequence);
3623 if (ConvOvlResult)
3624 Sequence.SetOverloadFailure(
3625 InitializationSequence::FK_ReferenceInitOverloadFailed,
3626 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003627
Douglas Gregor20093b42009-12-09 23:02:17 +00003628 return;
3629 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003630
Douglas Gregordefa32e2013-03-26 23:59:23 +00003631 if ((RefRelationship == Sema::Ref_Compatible ||
3632 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3633 isRValueRef && InitCategory.isLValue()) {
3634 Sequence.SetFailed(
3635 InitializationSequence::FK_RValueReferenceBindingToLValue);
3636 return;
3637 }
3638
Douglas Gregor20093b42009-12-09 23:02:17 +00003639 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3640 return;
3641 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003642
3643 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003644 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003645 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003646 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003647
Douglas Gregor20093b42009-12-09 23:02:17 +00003648 // Determine whether we are allowed to call explicit constructors or
3649 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003650 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003651
3652 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3653
John McCallf85e1932011-06-15 23:02:42 +00003654 ImplicitConversionSequence ICS
3655 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003656 /*SuppressUserConversions*/ false,
3657 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003658 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003659 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3660 /*AllowObjCWritebackConversion=*/false);
3661
3662 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003663 // FIXME: Use the conversion function set stored in ICS to turn
3664 // this into an overloading ambiguity diagnostic. However, we need
3665 // to keep that set as an OverloadCandidateSet rather than as some
3666 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003667 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3668 Sequence.SetOverloadFailure(
3669 InitializationSequence::FK_ReferenceInitOverloadFailed,
3670 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003671 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3672 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003673 else
3674 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003675 return;
John McCallf85e1932011-06-15 23:02:42 +00003676 } else {
3677 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003678 }
3679
3680 // [...] If T1 is reference-related to T2, cv1 must be the
3681 // same cv-qualification as, or greater cv-qualification
3682 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003683 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3684 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003685 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003686 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003687 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3688 return;
3689 }
3690
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003691 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003692 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003693 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003694 InitCategory.isLValue()) {
3695 Sequence.SetFailed(
3696 InitializationSequence::FK_RValueReferenceBindingToLValue);
3697 return;
3698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699
Douglas Gregor20093b42009-12-09 23:02:17 +00003700 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3701 return;
3702}
3703
3704/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003705/// (C++ [dcl.init.string], C99 6.7.8).
3706static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003707 const InitializedEntity &Entity,
3708 const InitializationKind &Kind,
3709 Expr *Initializer,
3710 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003711 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003712}
3713
Douglas Gregor71d17402009-12-15 00:01:57 +00003714/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003715static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003716 const InitializedEntity &Entity,
3717 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003718 InitializationSequence &Sequence,
3719 InitListExpr *InitList) {
3720 assert((!InitList || InitList->getNumInits() == 0) &&
3721 "Shouldn't use value-init for non-empty init lists");
3722
Richard Smith1d0c9a82012-02-14 21:14:13 +00003723 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003724 //
3725 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003726 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003727
Douglas Gregor71d17402009-12-15 00:01:57 +00003728 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003729 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003730
Douglas Gregor71d17402009-12-15 00:01:57 +00003731 if (const RecordType *RT = T->getAs<RecordType>()) {
3732 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003733 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003734 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003735 // C++98:
3736 // -- if T is a class type (clause 9) with a user-declared constructor
3737 // (12.1), then the default constructor for T is called (and the
3738 // initialization is ill-formed if T has no accessible default
3739 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003740 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003741 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003742 } else {
3743 // C++11:
3744 // -- if T is a class type (clause 9) with either no default constructor
3745 // (12.1 [class.ctor]) or a default constructor that is user-provided
3746 // or deleted, then the object is default-initialized;
3747 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3748 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003749 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003751
Richard Smith1d0c9a82012-02-14 21:14:13 +00003752 // -- if T is a (possibly cv-qualified) non-union class type without a
3753 // user-provided or deleted default constructor, then the object is
3754 // zero-initialized and, if T has a non-trivial default constructor,
3755 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003756 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3757 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003758 if (NeedZeroInitialization)
3759 Sequence.AddZeroInitializationStep(Entity.getType());
3760
Richard Smithd5bc8672012-12-08 02:01:17 +00003761 // C++03:
3762 // -- if T is a non-union class type without a user-declared constructor,
3763 // then every non-static data member and base class component of T is
3764 // value-initialized;
3765 // [...] A program that calls for [...] value-initialization of an
3766 // entity of reference type is ill-formed.
3767 //
3768 // C++11 doesn't need this handling, because value-initialization does not
3769 // occur recursively there, and the implicit default constructor is
3770 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003771 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003772 ClassDecl->hasUninitializedReferenceMember()) {
3773 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3774 return;
3775 }
3776
Richard Smithf4bb8d02012-07-05 08:39:21 +00003777 // If this is list-value-initialization, pass the empty init list on when
3778 // building the constructor call. This affects the semantics of a few
3779 // things (such as whether an explicit default constructor can be called).
3780 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003781 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003782 bool InitListSyntax = InitList;
3783
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003784 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3785 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003786 }
3787 }
3788
Douglas Gregord6542d82009-12-22 15:35:07 +00003789 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003790}
3791
Douglas Gregor99a2e602009-12-16 01:38:02 +00003792/// \brief Attempt default initialization (C++ [dcl.init]p6).
3793static void TryDefaultInitialization(Sema &S,
3794 const InitializedEntity &Entity,
3795 const InitializationKind &Kind,
3796 InitializationSequence &Sequence) {
3797 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798
Douglas Gregor99a2e602009-12-16 01:38:02 +00003799 // C++ [dcl.init]p6:
3800 // To default-initialize an object of type T means:
3801 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003802 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3803
Douglas Gregor99a2e602009-12-16 01:38:02 +00003804 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3805 // constructor for T is called (and the initialization is ill-formed if
3806 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003807 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003808 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003809 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811
Douglas Gregor99a2e602009-12-16 01:38:02 +00003812 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003813
Douglas Gregor99a2e602009-12-16 01:38:02 +00003814 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003815 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003816 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003817 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003818 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003819 return;
3820 }
3821
3822 // If the destination type has a lifetime property, zero-initialize it.
3823 if (DestType.getQualifiers().hasObjCLifetime()) {
3824 Sequence.AddZeroInitializationStep(Entity.getType());
3825 return;
3826 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003827}
3828
Douglas Gregor20093b42009-12-09 23:02:17 +00003829/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3830/// which enumerates all conversion functions and performs overload resolution
3831/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003832static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003833 const InitializedEntity &Entity,
3834 const InitializationKind &Kind,
3835 Expr *Initializer,
3836 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003837 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003838 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3839 QualType SourceType = Initializer->getType();
3840 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3841 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842
Douglas Gregor4a520a22009-12-14 17:27:33 +00003843 // Build the candidate set directly in the initialization sequence
3844 // structure, so that it will persist if we fail.
3845 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3846 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003847
Douglas Gregor4a520a22009-12-14 17:27:33 +00003848 // Determine whether we are allowed to call explicit constructors or
3849 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003850 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003851
Douglas Gregor4a520a22009-12-14 17:27:33 +00003852 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3853 // The type we're converting to is a class type. Enumerate its constructors
3854 // to see if there is a suitable conversion.
3855 CXXRecordDecl *DestRecordDecl
3856 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003858 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003859 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003860 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003861 // The container holding the constructors can under certain conditions
3862 // be changed while iterating. To be safe we copy the lookup results
3863 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003864 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003865 for (SmallVector<NamedDecl*, 8>::iterator
3866 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003867 Con != ConEnd; ++Con) {
3868 NamedDecl *D = *Con;
3869 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003870
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003871 // Find the constructor (which may be a template).
3872 CXXConstructorDecl *Constructor = 0;
3873 FunctionTemplateDecl *ConstructorTmpl
3874 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003875 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003876 Constructor = cast<CXXConstructorDecl>(
3877 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003878 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003879 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003880
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003881 if (!Constructor->isInvalidDecl() &&
3882 Constructor->isConvertingConstructor(AllowExplicit)) {
3883 if (ConstructorTmpl)
3884 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3885 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003886 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003887 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003888 else
3889 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003890 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003891 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003892 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003893 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003894 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003895 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003896
3897 SourceLocation DeclLoc = Initializer->getLocStart();
3898
Douglas Gregor4a520a22009-12-14 17:27:33 +00003899 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3900 // The type we're converting from is a class type, enumerate its conversion
3901 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003902
Eli Friedman33c2da92009-12-20 22:12:03 +00003903 // We can only enumerate the conversion functions for a complete type; if
3904 // the type isn't complete, simply skip this step.
3905 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3906 CXXRecordDecl *SourceRecordDecl
3907 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003908
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003909 std::pair<CXXRecordDecl::conversion_iterator,
3910 CXXRecordDecl::conversion_iterator>
3911 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3912 for (CXXRecordDecl::conversion_iterator
3913 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003914 NamedDecl *D = *I;
3915 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3916 if (isa<UsingShadowDecl>(D))
3917 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003918
Eli Friedman33c2da92009-12-20 22:12:03 +00003919 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3920 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003921 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003922 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003923 else
John McCall32daa422010-03-31 01:36:47 +00003924 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925
Eli Friedman33c2da92009-12-20 22:12:03 +00003926 if (AllowExplicit || !Conv->isExplicit()) {
3927 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003928 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003929 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003930 CandidateSet);
3931 else
John McCall9aa472c2010-03-19 07:35:19 +00003932 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003933 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003934 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003935 }
3936 }
3937 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938
3939 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003940 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003941 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003942 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003943 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003945 Result);
3946 return;
3947 }
John McCall1d318332010-01-12 00:44:57 +00003948
Douglas Gregor4a520a22009-12-14 17:27:33 +00003949 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003950 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003951 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003952
Douglas Gregor4a520a22009-12-14 17:27:33 +00003953 if (isa<CXXConstructorDecl>(Function)) {
3954 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003955 // subsumed by the initialization. Per DR5, the created temporary is of the
3956 // cv-unqualified type of the destination.
3957 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3958 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003959 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003960 return;
3961 }
3962
3963 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003964 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003965 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003966 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003967 // the resulting temporary object (possible to create an object of
3968 // a base class type). That copy is not a separate conversion, so
3969 // we just make a note of the actual destination type (possibly a
3970 // base class of the type returned by the conversion function) and
3971 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003972 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3973 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003974 return;
3975 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003976
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003977 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3978 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003979
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003980 // If the conversion following the call to the conversion function
3981 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003982 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3983 Best->FinalConversion.Third) {
3984 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003985 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003986 ICS.Standard = Best->FinalConversion;
3987 Sequence.AddConversionSequenceStep(ICS, DestType);
3988 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003989}
3990
John McCallf85e1932011-06-15 23:02:42 +00003991/// The non-zero enum values here are indexes into diagnostic alternatives.
3992enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3993
3994/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003995static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003996 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00003997 // Skip parens.
3998 e = e->IgnoreParens();
3999
4000 // Skip address-of nodes.
4001 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4002 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004003 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4004 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004005
4006 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004007 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4008 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004009 case CK_Dependent:
4010 case CK_BitCast:
4011 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004012 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004013 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004014
4015 case CK_ArrayToPointerDecay:
4016 return IIK_nonscalar;
4017
4018 case CK_NullToPointer:
4019 return IIK_okay;
4020
4021 default:
4022 break;
4023 }
4024
4025 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004026 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004027 // set isWeakAccess to true, to mean that there will be an implicit
4028 // load which requires a cleanup.
4029 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4030 isWeakAccess = true;
4031
John McCallc03fa492011-06-27 23:59:58 +00004032 if (!isAddressOf) return IIK_nonlocal;
4033
John McCallf4b88a42012-03-10 09:33:50 +00004034 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4035 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004036
4037 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004038
4039 // If we have a conditional operator, check both sides.
4040 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004041 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4042 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004043 return iik;
4044
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004045 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004046
4047 // These are never scalar.
4048 } else if (isa<ArraySubscriptExpr>(e)) {
4049 return IIK_nonscalar;
4050
4051 // Otherwise, it needs to be a null pointer constant.
4052 } else {
4053 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4054 ? IIK_okay : IIK_nonlocal);
4055 }
4056
4057 return IIK_nonlocal;
4058}
4059
4060/// Check whether the given expression is a valid operand for an
4061/// indirect copy/restore.
4062static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4063 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004064 bool isWeakAccess = false;
4065 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4066 // If isWeakAccess to true, there will be an implicit
4067 // load which requires a cleanup.
4068 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4069 S.ExprNeedsCleanups = true;
4070
John McCallf85e1932011-06-15 23:02:42 +00004071 if (iik == IIK_okay) return;
4072
4073 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4074 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4075 << src->getSourceRange();
4076}
4077
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004078/// \brief Determine whether we have compatible array types for the
4079/// purposes of GNU by-copy array initialization.
4080static bool hasCompatibleArrayTypes(ASTContext &Context,
4081 const ArrayType *Dest,
4082 const ArrayType *Source) {
4083 // If the source and destination array types are equivalent, we're
4084 // done.
4085 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4086 return true;
4087
4088 // Make sure that the element types are the same.
4089 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4090 return false;
4091
4092 // The only mismatch we allow is when the destination is an
4093 // incomplete array type and the source is a constant array type.
4094 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4095}
4096
John McCallf85e1932011-06-15 23:02:42 +00004097static bool tryObjCWritebackConversion(Sema &S,
4098 InitializationSequence &Sequence,
4099 const InitializedEntity &Entity,
4100 Expr *Initializer) {
4101 bool ArrayDecay = false;
4102 QualType ArgType = Initializer->getType();
4103 QualType ArgPointee;
4104 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4105 ArrayDecay = true;
4106 ArgPointee = ArgArrayType->getElementType();
4107 ArgType = S.Context.getPointerType(ArgPointee);
4108 }
4109
4110 // Handle write-back conversion.
4111 QualType ConvertedArgType;
4112 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4113 ConvertedArgType))
4114 return false;
4115
4116 // We should copy unless we're passing to an argument explicitly
4117 // marked 'out'.
4118 bool ShouldCopy = true;
4119 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4120 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4121
4122 // Do we need an lvalue conversion?
4123 if (ArrayDecay || Initializer->isGLValue()) {
4124 ImplicitConversionSequence ICS;
4125 ICS.setStandard();
4126 ICS.Standard.setAsIdentityConversion();
4127
4128 QualType ResultType;
4129 if (ArrayDecay) {
4130 ICS.Standard.First = ICK_Array_To_Pointer;
4131 ResultType = S.Context.getPointerType(ArgPointee);
4132 } else {
4133 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4134 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4135 }
4136
4137 Sequence.AddConversionSequenceStep(ICS, ResultType);
4138 }
4139
4140 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4141 return true;
4142}
4143
Guy Benyei21f18c42013-02-07 10:55:47 +00004144static bool TryOCLSamplerInitialization(Sema &S,
4145 InitializationSequence &Sequence,
4146 QualType DestType,
4147 Expr *Initializer) {
4148 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4149 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4150 return false;
4151
4152 Sequence.AddOCLSamplerInitStep(DestType);
4153 return true;
4154}
4155
Guy Benyeie6b9d802013-01-20 12:31:11 +00004156//
4157// OpenCL 1.2 spec, s6.12.10
4158//
4159// The event argument can also be used to associate the
4160// async_work_group_copy with a previous async copy allowing
4161// an event to be shared by multiple async copies; otherwise
4162// event should be zero.
4163//
4164static bool TryOCLZeroEventInitialization(Sema &S,
4165 InitializationSequence &Sequence,
4166 QualType DestType,
4167 Expr *Initializer) {
4168 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4169 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4170 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4171 return false;
4172
4173 Sequence.AddOCLZeroEventStep(DestType);
4174 return true;
4175}
4176
Douglas Gregor20093b42009-12-09 23:02:17 +00004177InitializationSequence::InitializationSequence(Sema &S,
4178 const InitializedEntity &Entity,
4179 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004180 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004181 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004182 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004183
John McCall76da55d2013-04-16 07:28:30 +00004184 // Eliminate non-overload placeholder types in the arguments. We
4185 // need to do this before checking whether types are dependent
4186 // because lowering a pseudo-object expression might well give us
4187 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004188 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004189 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4190 // FIXME: should we be doing this here?
4191 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4192 if (result.isInvalid()) {
4193 SetFailed(FK_PlaceholderType);
4194 return;
4195 }
4196 Args[I] = result.take();
4197 }
4198
Douglas Gregor20093b42009-12-09 23:02:17 +00004199 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004200 // The semantics of initializers are as follows. The destination type is
4201 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004202 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004203 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004204 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004205 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004206
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004207 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004208 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004209 SequenceKind = DependentSequence;
4210 return;
4211 }
4212
Sebastian Redl7491c492011-06-05 13:59:11 +00004213 // Almost everything is a normal sequence.
4214 setSequenceKind(NormalSequence);
4215
Douglas Gregor20093b42009-12-09 23:02:17 +00004216 QualType SourceType;
4217 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004218 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004219 Initializer = Args[0];
4220 if (!isa<InitListExpr>(Initializer))
4221 SourceType = Initializer->getType();
4222 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004224 // - If the initializer is a (non-parenthesized) braced-init-list, the
4225 // object is list-initialized (8.5.4).
4226 if (Kind.getKind() != InitializationKind::IK_Direct) {
4227 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4228 TryListInitialization(S, Entity, Kind, InitList, *this);
4229 return;
4230 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004231 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004232
Douglas Gregor20093b42009-12-09 23:02:17 +00004233 // - If the destination type is a reference type, see 8.5.3.
4234 if (DestType->isReferenceType()) {
4235 // C++0x [dcl.init.ref]p1:
4236 // A variable declared to be a T& or T&&, that is, "reference to type T"
4237 // (8.3.2), shall be initialized by an object, or function, of type T or
4238 // by an object that can be converted into a T.
4239 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004240 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004241 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004242 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004243 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004244 return;
4245 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246
Douglas Gregor20093b42009-12-09 23:02:17 +00004247 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004248 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004249 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004250 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004251 return;
4252 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004253
Douglas Gregor99a2e602009-12-16 01:38:02 +00004254 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004255 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004256 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004257 return;
4258 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004259
John McCallce6c9b72011-02-21 07:22:22 +00004260 // - If the destination type is an array of characters, an array of
4261 // char16_t, an array of char32_t, or an array of wchar_t, and the
4262 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004264 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004265 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004266 if (Initializer && isa<VariableArrayType>(DestAT)) {
4267 SetFailed(FK_VariableLengthArrayHasInitializer);
4268 return;
4269 }
4270
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004271 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004272 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004273 return;
4274 }
4275
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004276 // Note: as an GNU C extension, we allow initialization of an
4277 // array from a compound literal that creates an array of the same
4278 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004279 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004280 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4281 Initializer->getType()->isArrayType()) {
4282 const ArrayType *SourceAT
4283 = Context.getAsArrayType(Initializer->getType());
4284 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004285 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004286 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004287 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004288 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004289 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004290 }
Richard Smith0f163e92012-02-15 22:38:09 +00004291 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004292 // Note: as a GNU C++ extension, we allow list-initialization of a
4293 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004294 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004295 Entity.getKind() == InitializedEntity::EK_Member &&
4296 Initializer && isa<InitListExpr>(Initializer)) {
4297 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4298 *this);
4299 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004300 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004301 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004302 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004303 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004304
Douglas Gregor20093b42009-12-09 23:02:17 +00004305 return;
4306 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004307
John McCallf85e1932011-06-15 23:02:42 +00004308 // Determine whether we should consider writeback conversions for
4309 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004310 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004311 Entity.getKind() == InitializedEntity::EK_Parameter;
4312
4313 // We're at the end of the line for C: it's either a write-back conversion
4314 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004315 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004316 // If allowed, check whether this is an Objective-C writeback conversion.
4317 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004318 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004319 return;
4320 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004321
4322 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4323 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004324
4325 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4326 return;
4327
John McCallf85e1932011-06-15 23:02:42 +00004328 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004329 AddCAssignmentStep(DestType);
4330 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004331 return;
4332 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004333
David Blaikie4e4d0842012-03-11 07:00:24 +00004334 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004335
Douglas Gregor20093b42009-12-09 23:02:17 +00004336 // - If the destination type is a (possibly cv-qualified) class type:
4337 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004338 // - If the initialization is direct-initialization, or if it is
4339 // copy-initialization where the cv-unqualified version of the
4340 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004341 // class of the destination, constructors are considered. [...]
4342 if (Kind.getKind() == InitializationKind::IK_Direct ||
4343 (Kind.getKind() == InitializationKind::IK_Copy &&
4344 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4345 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004346 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004347 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004348 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004349 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004350 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004351 // used) to a derived class thereof are enumerated as described in
4352 // 13.3.1.4, and the best one is chosen through overload resolution
4353 // (13.3).
4354 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004355 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004356 return;
4357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004358
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004359 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004360 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004361 return;
4362 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004363 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004364
4365 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004366 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004367 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004368 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4369 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004370 return;
4371 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004372
Douglas Gregor20093b42009-12-09 23:02:17 +00004373 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004374 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004375 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004376 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004377 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004378
4379 ImplicitConversionSequence ICS
4380 = S.TryImplicitConversion(Initializer, Entity.getType(),
4381 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004382 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004383 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004384 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4385 allowObjCWritebackConversion);
4386
4387 if (ICS.isStandard() &&
4388 ICS.Standard.Second == ICK_Writeback_Conversion) {
4389 // Objective-C ARC writeback conversion.
4390
4391 // We should copy unless we're passing to an argument explicitly
4392 // marked 'out'.
4393 bool ShouldCopy = true;
4394 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4395 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4396
4397 // If there was an lvalue adjustment, add it as a separate conversion.
4398 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4399 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4400 ImplicitConversionSequence LvalueICS;
4401 LvalueICS.setStandard();
4402 LvalueICS.Standard.setAsIdentityConversion();
4403 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4404 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004405 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004406 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004407
4408 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004409 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004410 DeclAccessPair dap;
4411 if (Initializer->getType() == Context.OverloadTy &&
4412 !S.ResolveAddressOfOverloadedFunction(Initializer
4413 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004414 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004415 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004416 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004417 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004418 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004419
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004420 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004421 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004422}
4423
4424InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004425 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004426 StepEnd = Steps.end();
4427 Step != StepEnd; ++Step)
4428 Step->Destroy();
4429}
4430
4431//===----------------------------------------------------------------------===//
4432// Perform initialization
4433//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004435getAssignmentAction(const InitializedEntity &Entity) {
4436 switch(Entity.getKind()) {
4437 case InitializedEntity::EK_Variable:
4438 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004439 case InitializedEntity::EK_Exception:
4440 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004441 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004442 return Sema::AA_Initializing;
4443
4444 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004445 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004446 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4447 return Sema::AA_Sending;
4448
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004449 return Sema::AA_Passing;
4450
4451 case InitializedEntity::EK_Result:
4452 return Sema::AA_Returning;
4453
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004454 case InitializedEntity::EK_Temporary:
4455 // FIXME: Can we tell apart casting vs. converting?
4456 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004458 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004459 case InitializedEntity::EK_ArrayElement:
4460 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004461 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004462 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004463 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004464 return Sema::AA_Initializing;
4465 }
4466
David Blaikie7530c032012-01-17 06:56:22 +00004467 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004468}
4469
Richard Smith774d8b42013-01-08 00:08:23 +00004470/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004471/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004472static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004473 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004474 case InitializedEntity::EK_ArrayElement:
4475 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004476 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004477 case InitializedEntity::EK_New:
4478 case InitializedEntity::EK_Variable:
4479 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004480 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004481 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004482 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004483 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004484 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004485 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004486 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004488 case InitializedEntity::EK_Parameter:
4489 case InitializedEntity::EK_Temporary:
4490 return true;
4491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004493 llvm_unreachable("missed an InitializedEntity kind?");
4494}
4495
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004496/// \brief Whether the given entity, when initialized with an object
4497/// created for that initialization, requires destruction.
4498static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4499 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004500 case InitializedEntity::EK_Result:
4501 case InitializedEntity::EK_New:
4502 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004503 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004504 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004505 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004506 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004507 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004508 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004509
Richard Smith774d8b42013-01-08 00:08:23 +00004510 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004511 case InitializedEntity::EK_Variable:
4512 case InitializedEntity::EK_Parameter:
4513 case InitializedEntity::EK_Temporary:
4514 case InitializedEntity::EK_ArrayElement:
4515 case InitializedEntity::EK_Exception:
4516 return true;
4517 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004518
4519 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004520}
4521
Richard Smith83da2e72011-10-19 16:55:56 +00004522/// \brief Look for copy and move constructors and constructor templates, for
4523/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4524static void LookupCopyAndMoveConstructors(Sema &S,
4525 OverloadCandidateSet &CandidateSet,
4526 CXXRecordDecl *Class,
4527 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004528 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004529 // The container holding the constructors can under certain conditions
4530 // be changed while iterating (e.g. because of deserialization).
4531 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004532 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004533 for (SmallVector<NamedDecl*, 16>::iterator
4534 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4535 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004536 CXXConstructorDecl *Constructor = 0;
4537
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004538 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004539 // Handle copy/moveconstructors, only.
4540 if (!Constructor || Constructor->isInvalidDecl() ||
4541 !Constructor->isCopyOrMoveConstructor() ||
4542 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4543 continue;
4544
4545 DeclAccessPair FoundDecl
4546 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4547 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004548 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004549 continue;
4550 }
4551
4552 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004553 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004554 if (ConstructorTmpl->isInvalidDecl())
4555 continue;
4556
4557 Constructor = cast<CXXConstructorDecl>(
4558 ConstructorTmpl->getTemplatedDecl());
4559 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4560 continue;
4561
4562 // FIXME: Do we need to limit this to copy-constructor-like
4563 // candidates?
4564 DeclAccessPair FoundDecl
4565 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4566 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004567 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004568 }
4569}
4570
4571/// \brief Get the location at which initialization diagnostics should appear.
4572static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4573 Expr *Initializer) {
4574 switch (Entity.getKind()) {
4575 case InitializedEntity::EK_Result:
4576 return Entity.getReturnLoc();
4577
4578 case InitializedEntity::EK_Exception:
4579 return Entity.getThrowLoc();
4580
4581 case InitializedEntity::EK_Variable:
4582 return Entity.getDecl()->getLocation();
4583
Douglas Gregor47736542012-02-15 16:57:26 +00004584 case InitializedEntity::EK_LambdaCapture:
4585 return Entity.getCaptureLoc();
4586
Richard Smith83da2e72011-10-19 16:55:56 +00004587 case InitializedEntity::EK_ArrayElement:
4588 case InitializedEntity::EK_Member:
4589 case InitializedEntity::EK_Parameter:
4590 case InitializedEntity::EK_Temporary:
4591 case InitializedEntity::EK_New:
4592 case InitializedEntity::EK_Base:
4593 case InitializedEntity::EK_Delegating:
4594 case InitializedEntity::EK_VectorElement:
4595 case InitializedEntity::EK_ComplexElement:
4596 case InitializedEntity::EK_BlockElement:
4597 return Initializer->getLocStart();
4598 }
4599 llvm_unreachable("missed an InitializedEntity kind?");
4600}
4601
Douglas Gregor523d46a2010-04-18 07:40:54 +00004602/// \brief Make a (potentially elidable) temporary copy of the object
4603/// provided by the given initializer by calling the appropriate copy
4604/// constructor.
4605///
4606/// \param S The Sema object used for type-checking.
4607///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004608/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004609/// the type of the initializer expression or a superclass thereof.
4610///
James Dennett1dfbd922012-06-14 21:40:34 +00004611/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004612///
4613/// \param CurInit The initializer expression.
4614///
4615/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4616/// is permitted in C++03 (but not C++0x) when binding a reference to
4617/// an rvalue.
4618///
4619/// \returns An expression that copies the initializer expression into
4620/// a temporary object, or an error expression if a copy could not be
4621/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004622static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004623 QualType T,
4624 const InitializedEntity &Entity,
4625 ExprResult CurInit,
4626 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004627 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004628 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004629 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004630 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004631 Class = cast<CXXRecordDecl>(Record->getDecl());
4632 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004633 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004634
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004635 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004636 // When certain criteria are met, an implementation is allowed to
4637 // omit the copy/move construction of a class object, even if the
4638 // copy/move constructor and/or destructor for the object have
4639 // side effects. [...]
4640 // - when a temporary class object that has not been bound to a
4641 // reference (12.2) would be copied/moved to a class object
4642 // with the same cv-unqualified type, the copy/move operation
4643 // can be omitted by constructing the temporary object
4644 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004645 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004646 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004647 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004648 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004649 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004650 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004651 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004652
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004653 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004654 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004655 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004656
Douglas Gregorcc15f012011-01-21 19:38:21 +00004657 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004658 // Only consider constructors and constructor templates. Per
4659 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4660 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004661 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004662 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004663
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004664 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4665
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004666 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004667 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004668 case OR_Success:
4669 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004670
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004671 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004672 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4673 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4674 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004675 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004676 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004677 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004678 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004679 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004680 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004681
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004682 case OR_Ambiguous:
4683 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004684 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004685 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004686 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004687 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004688
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004689 case OR_Deleted:
4690 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004691 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004692 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004693 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004694 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004695 }
4696
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004697 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004698 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004699 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004700
Anders Carlsson9a68a672010-04-21 18:47:17 +00004701 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004702 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004703
4704 if (IsExtraneousCopy) {
4705 // If this is a totally extraneous copy for C++03 reference
4706 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004707 // expression. We don't generate an (elided) copy operation here
4708 // because doing so would require us to pass down a flag to avoid
4709 // infinite recursion, where each step adds another extraneous,
4710 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004711
Douglas Gregor2559a702010-04-18 07:57:34 +00004712 // Instantiate the default arguments of any extra parameters in
4713 // the selected copy constructor, as if we were going to create a
4714 // proper call to the copy constructor.
4715 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4716 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4717 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004718 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004719 break;
4720
4721 // Build the default argument expression; we don't actually care
4722 // if this succeeds or not, because this routine will complain
4723 // if there was a problem.
4724 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4725 }
4726
Douglas Gregor523d46a2010-04-18 07:40:54 +00004727 return S.Owned(CurInitExpr);
4728 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004729
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004730 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004731 // constructor call (we might have derived-to-base conversions, or
4732 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004733 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004734 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004735
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004736 // Actually perform the constructor call.
4737 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004738 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004739 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004740 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004741 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004742 CXXConstructExpr::CK_Complete,
4743 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004744
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004745 // If we're supposed to bind temporaries, do so.
4746 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4747 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004748 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004749}
Douglas Gregor20093b42009-12-09 23:02:17 +00004750
Richard Smith83da2e72011-10-19 16:55:56 +00004751/// \brief Check whether elidable copy construction for binding a reference to
4752/// a temporary would have succeeded if we were building in C++98 mode, for
4753/// -Wc++98-compat.
4754static void CheckCXX98CompatAccessibleCopy(Sema &S,
4755 const InitializedEntity &Entity,
4756 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004757 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004758
4759 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4760 if (!Record)
4761 return;
4762
4763 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4764 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4765 == DiagnosticsEngine::Ignored)
4766 return;
4767
4768 // Find constructors which would have been considered.
4769 OverloadCandidateSet CandidateSet(Loc);
4770 LookupCopyAndMoveConstructors(
4771 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4772
4773 // Perform overload resolution.
4774 OverloadCandidateSet::iterator Best;
4775 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4776
4777 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4778 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4779 << CurInitExpr->getSourceRange();
4780
4781 switch (OR) {
4782 case OR_Success:
4783 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004784 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004785 // FIXME: Check default arguments as far as that's possible.
4786 break;
4787
4788 case OR_No_Viable_Function:
4789 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004790 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004791 break;
4792
4793 case OR_Ambiguous:
4794 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004795 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004796 break;
4797
4798 case OR_Deleted:
4799 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004800 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004801 break;
4802 }
4803}
4804
Douglas Gregora41a8c52010-04-22 00:20:18 +00004805void InitializationSequence::PrintInitLocationNote(Sema &S,
4806 const InitializedEntity &Entity) {
4807 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4808 if (Entity.getDecl()->getLocation().isInvalid())
4809 return;
4810
4811 if (Entity.getDecl()->getDeclName())
4812 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4813 << Entity.getDecl()->getDeclName();
4814 else
4815 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4816 }
4817}
4818
Sebastian Redl3b802322011-07-14 19:07:55 +00004819static bool isReferenceBinding(const InitializationSequence::Step &s) {
4820 return s.Kind == InitializationSequence::SK_BindReference ||
4821 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4822}
4823
Sebastian Redl10f04a62011-12-22 14:44:04 +00004824static ExprResult
4825PerformConstructorInitialization(Sema &S,
4826 const InitializedEntity &Entity,
4827 const InitializationKind &Kind,
4828 MultiExprArg Args,
4829 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004830 bool &ConstructorInitRequiresZeroInit,
4831 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004832 unsigned NumArgs = Args.size();
4833 CXXConstructorDecl *Constructor
4834 = cast<CXXConstructorDecl>(Step.Function.Function);
4835 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4836
4837 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004838 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004839 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4840 ? Kind.getEqualLoc()
4841 : Kind.getLocation();
4842
4843 if (Kind.getKind() == InitializationKind::IK_Default) {
4844 // Force even a trivial, implicit default constructor to be
4845 // semantically checked. We do this explicitly because we don't build
4846 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004847 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004848 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004849 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004850 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4851 }
4852
4853 ExprResult CurInit = S.Owned((Expr *)0);
4854
Douglas Gregored878af2012-02-24 23:56:31 +00004855 // C++ [over.match.copy]p1:
4856 // - When initializing a temporary to be bound to the first parameter
4857 // of a constructor that takes a reference to possibly cv-qualified
4858 // T as its first argument, called with a single argument in the
4859 // context of direct-initialization, explicit conversion functions
4860 // are also considered.
4861 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4862 Args.size() == 1 &&
4863 Constructor->isCopyOrMoveConstructor();
4864
Sebastian Redl10f04a62011-12-22 14:44:04 +00004865 // Determine the arguments required to actually perform the constructor
4866 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004867 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004868 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004869 AllowExplicitConv,
4870 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004871 return ExprError();
4872
4873
4874 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Sebastian Redl188158d2012-03-08 21:05:45 +00004875 (Kind.getKind() == InitializationKind::IK_DirectList ||
4876 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4877 (Kind.getKind() == InitializationKind::IK_Direct ||
4878 Kind.getKind() == InitializationKind::IK_Value)))) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004879 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004880 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00004881 if (S.DiagnoseUseOfDecl(Constructor, Loc))
4882 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004883
4884 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4885 if (!TSInfo)
4886 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004887 SourceRange ParenRange;
4888 if (Kind.getKind() != InitializationKind::IK_DirectList)
4889 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004890
Richard Smithc83c2302012-12-19 01:39:02 +00004891 CurInit = S.Owned(
4892 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4893 TSInfo, ConstructorArgs,
4894 ParenRange, IsListInitialization,
4895 HadMultipleCandidates,
4896 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00004897 } else {
4898 CXXConstructExpr::ConstructionKind ConstructKind =
4899 CXXConstructExpr::CK_Complete;
4900
4901 if (Entity.getKind() == InitializedEntity::EK_Base) {
4902 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4903 CXXConstructExpr::CK_VirtualBase :
4904 CXXConstructExpr::CK_NonVirtualBase;
4905 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4906 ConstructKind = CXXConstructExpr::CK_Delegating;
4907 }
4908
4909 // Only get the parenthesis range if it is a direct construction.
4910 SourceRange parenRange =
4911 Kind.getKind() == InitializationKind::IK_Direct ?
4912 Kind.getParenRange() : SourceRange();
4913
4914 // If the entity allows NRVO, mark the construction as elidable
4915 // unconditionally.
4916 if (Entity.allowsNRVO())
4917 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4918 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004919 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004920 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004921 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004922 ConstructorInitRequiresZeroInit,
4923 ConstructKind,
4924 parenRange);
4925 else
4926 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4927 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004928 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004929 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004930 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004931 ConstructorInitRequiresZeroInit,
4932 ConstructKind,
4933 parenRange);
4934 }
4935 if (CurInit.isInvalid())
4936 return ExprError();
4937
4938 // Only check access if all of that succeeded.
4939 S.CheckConstructorAccess(Loc, Constructor, Entity,
4940 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00004941 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
4942 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004943
4944 if (shouldBindAsTemporary(Entity))
4945 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4946
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004947 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004948}
4949
Richard Smith36d02af2012-06-04 22:27:30 +00004950/// Determine whether the specified InitializedEntity definitely has a lifetime
4951/// longer than the current full-expression. Conservatively returns false if
4952/// it's unclear.
4953static bool
4954InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4955 const InitializedEntity *Top = &Entity;
4956 while (Top->getParent())
4957 Top = Top->getParent();
4958
4959 switch (Top->getKind()) {
4960 case InitializedEntity::EK_Variable:
4961 case InitializedEntity::EK_Result:
4962 case InitializedEntity::EK_Exception:
4963 case InitializedEntity::EK_Member:
4964 case InitializedEntity::EK_New:
4965 case InitializedEntity::EK_Base:
4966 case InitializedEntity::EK_Delegating:
4967 return true;
4968
4969 case InitializedEntity::EK_ArrayElement:
4970 case InitializedEntity::EK_VectorElement:
4971 case InitializedEntity::EK_BlockElement:
4972 case InitializedEntity::EK_ComplexElement:
4973 // Could not determine what the full initialization is. Assume it might not
4974 // outlive the full-expression.
4975 return false;
4976
4977 case InitializedEntity::EK_Parameter:
4978 case InitializedEntity::EK_Temporary:
4979 case InitializedEntity::EK_LambdaCapture:
4980 // The entity being initialized might not outlive the full-expression.
4981 return false;
4982 }
4983
4984 llvm_unreachable("unknown entity kind");
4985}
4986
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004987ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004988InitializationSequence::Perform(Sema &S,
4989 const InitializedEntity &Entity,
4990 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004991 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004992 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004993 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004994 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00004995 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004996 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004997
Sebastian Redl7491c492011-06-05 13:59:11 +00004998 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004999 // If the declaration is a non-dependent, incomplete array type
5000 // that has an initializer, then its type will be completed once
5001 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005002 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005003 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005004 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005005 if (const IncompleteArrayType *ArrayT
5006 = S.Context.getAsIncompleteArrayType(DeclType)) {
5007 // FIXME: We don't currently have the ability to accurately
5008 // compute the length of an initializer list without
5009 // performing full type-checking of the initializer list
5010 // (since we have to determine where braces are implicitly
5011 // introduced and such). So, we fall back to making the array
5012 // type a dependently-sized array type with no specified
5013 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005014 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005015 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005016
Douglas Gregord87b61f2009-12-10 17:56:55 +00005017 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005018 if (DeclaratorDecl *DD = Entity.getDecl()) {
5019 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5020 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005021 if (IncompleteArrayTypeLoc ArrayLoc =
5022 TL.getAs<IncompleteArrayTypeLoc>())
5023 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005024 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005025 }
5026
5027 *ResultType
5028 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5029 /*NumElts=*/0,
5030 ArrayT->getSizeModifier(),
5031 ArrayT->getIndexTypeCVRQualifiers(),
5032 Brackets);
5033 }
5034
5035 }
5036 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005037 if (Kind.getKind() == InitializationKind::IK_Direct &&
5038 !Kind.isExplicitCast()) {
5039 // Rebuild the ParenListExpr.
5040 SourceRange ParenRange = Kind.getParenRange();
5041 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005042 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005043 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005044 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005045 Kind.isExplicitCast() ||
5046 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005047 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005048 }
5049
Sebastian Redl7491c492011-06-05 13:59:11 +00005050 // No steps means no initialization.
5051 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005052 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005053
Richard Smith80ad52f2013-01-02 11:42:31 +00005054 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005055 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005056 Entity.getKind() != InitializedEntity::EK_Parameter) {
5057 // Produce a C++98 compatibility warning if we are initializing a reference
5058 // from an initializer list. For parameters, we produce a better warning
5059 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005060 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005061 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5062 << Init->getSourceRange();
5063 }
5064
Richard Smith36d02af2012-06-04 22:27:30 +00005065 // Diagnose cases where we initialize a pointer to an array temporary, and the
5066 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005067 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005068 Entity.getType()->isPointerType() &&
5069 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005070 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005071 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5072 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5073 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5074 << Init->getSourceRange();
5075 }
5076
Douglas Gregord6542d82009-12-22 15:35:07 +00005077 QualType DestType = Entity.getType().getNonReferenceType();
5078 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005079 // the same as Entity.getDecl()->getType() in cases involving type merging,
5080 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005081 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005082 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005083 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005084
John McCall60d7b3a2010-08-24 06:29:42 +00005085 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005086
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005087 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005088 // grab the only argument out the Args and place it into the "current"
5089 // initializer.
5090 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005091 case SK_ResolveAddressOfOverloadedFunction:
5092 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005093 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005094 case SK_CastDerivedToBaseLValue:
5095 case SK_BindReference:
5096 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005097 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005098 case SK_UserConversion:
5099 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005100 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005101 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005102 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005103 case SK_ConversionSequence:
5104 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005105 case SK_UnwrapInitList:
5106 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005107 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005108 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005109 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005110 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005111 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005112 case SK_PassByIndirectCopyRestore:
5113 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005114 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005115 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005116 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005117 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005118 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005119 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005120 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005121 break;
John McCallf6a16482010-12-04 03:47:34 +00005122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005123
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005124 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005125 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005126 case SK_ZeroInitialization:
5127 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005128 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005129
5130 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005131 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005132 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005133 for (step_iterator Step = step_begin(), StepEnd = step_end();
5134 Step != StepEnd; ++Step) {
5135 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005136 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005137
John Wiegley429bb272011-04-08 18:41:53 +00005138 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005139
Douglas Gregor20093b42009-12-09 23:02:17 +00005140 switch (Step->Kind) {
5141 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005142 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005143 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005144 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005145 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5146 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005147 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005148 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005149 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005150 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005151
Douglas Gregor20093b42009-12-09 23:02:17 +00005152 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005153 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005154 case SK_CastDerivedToBaseLValue: {
5155 // We have a derived-to-base cast that produces either an rvalue or an
5156 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005157
John McCallf871d0c2010-08-07 06:22:56 +00005158 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005159
Douglas Gregor20093b42009-12-09 23:02:17 +00005160 // Casts to inaccessible base classes are allowed with C-style casts.
5161 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5162 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005163 CurInit.get()->getLocStart(),
5164 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005165 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005166 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005167
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005168 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5169 QualType T = SourceType;
5170 if (const PointerType *Pointer = T->getAs<PointerType>())
5171 T = Pointer->getPointeeType();
5172 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005173 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005174 cast<CXXRecordDecl>(RecordTy->getDecl()));
5175 }
5176
John McCall5baba9d2010-08-25 10:28:54 +00005177 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005178 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005179 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005180 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005181 VK_XValue :
5182 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005183 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5184 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005185 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005186 CurInit.get(),
5187 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005188 break;
5189 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005190
Douglas Gregor20093b42009-12-09 23:02:17 +00005191 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00005192 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005193 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
5194 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005195 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005196 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00005197 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00005198 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00005199 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005200 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005201
John Wiegley429bb272011-04-08 18:41:53 +00005202 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005203 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005204 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5205 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005206 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005207 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005208 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005210
Douglas Gregor20093b42009-12-09 23:02:17 +00005211 // Reference binding does not have any corresponding ASTs.
5212
5213 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005214 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005215 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005216
Douglas Gregor20093b42009-12-09 23:02:17 +00005217 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005218
Douglas Gregor20093b42009-12-09 23:02:17 +00005219 case SK_BindReferenceToTemporary:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005220 // Make sure the "temporary" is actually an rvalue.
5221 assert(CurInit.get()->isRValue() && "not a temporary");
5222
Douglas Gregor20093b42009-12-09 23:02:17 +00005223 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005224 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005225 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005226
Douglas Gregor03e80032011-06-21 17:03:29 +00005227 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005228 CurInit = new (S.Context) MaterializeTemporaryExpr(
5229 Entity.getType().getNonReferenceType(),
5230 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005231 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005232
5233 // If we're binding to an Objective-C object that has lifetime, we
5234 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005235 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005236 CurInit.get()->getType()->isObjCLifetimeType())
5237 S.ExprNeedsCleanups = true;
5238
Douglas Gregor20093b42009-12-09 23:02:17 +00005239 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005240
Douglas Gregor523d46a2010-04-18 07:40:54 +00005241 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005242 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005243 /*IsExtraneousCopy=*/true);
5244 break;
5245
Douglas Gregor20093b42009-12-09 23:02:17 +00005246 case SK_UserConversion: {
5247 // We have a user-defined conversion that invokes either a constructor
5248 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005249 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005250 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005251 FunctionDecl *Fn = Step->Function.Function;
5252 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005253 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005254 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005255 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005256 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005257 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005258 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005259 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005260
Douglas Gregor20093b42009-12-09 23:02:17 +00005261 // Determine the arguments required to actually perform the constructor
5262 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005263 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005264 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005265 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005266 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005267 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005268
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005269 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005270 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005271 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005272 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005273 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005274 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005275 CXXConstructExpr::CK_Complete,
5276 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005277 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005278 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005279
Anders Carlsson9a68a672010-04-21 18:47:17 +00005280 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005281 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005282 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5283 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005284
John McCall2de56d12010-08-25 11:45:40 +00005285 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005286 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5287 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5288 S.IsDerivedFrom(SourceType, Class))
5289 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005290
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005291 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005292 } else {
5293 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005294 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005295 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005296 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005297 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5298 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005299
5300 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005301 // derived-to-base conversion? I believe the answer is "no", because
5302 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005303 ExprResult CurInitExprRes =
5304 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5305 FoundFn, Conversion);
5306 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005307 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005308 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005309
Douglas Gregor20093b42009-12-09 23:02:17 +00005310 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005311 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5312 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005313 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005314 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005315
John McCall2de56d12010-08-25 11:45:40 +00005316 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005317
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005318 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005319 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005320
Sebastian Redl3b802322011-07-14 19:07:55 +00005321 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005322 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5323
5324 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005325 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005326 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005327 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005328 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005329 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005330 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005331 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005332 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5333 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005334 }
5335 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005336
John McCallf871d0c2010-08-07 06:22:56 +00005337 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005338 CurInit.get()->getType(),
5339 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005340 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005341 if (MaybeBindToTemp)
5342 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005343 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005344 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005345 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005346 break;
5347 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005348
Douglas Gregor20093b42009-12-09 23:02:17 +00005349 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005350 case SK_QualificationConversionXValue:
5351 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005352 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005353 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005354 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005355 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005356 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005357 VK_XValue :
5358 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005359 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005360 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005361 }
5362
Jordan Rose1fd1e282013-04-11 00:58:58 +00005363 case SK_LValueToRValue: {
5364 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5365 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5366 CK_LValueToRValue,
5367 CurInit.take(),
5368 /*BasePath=*/0,
5369 VK_RValue));
5370 break;
5371 }
5372
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005373 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005374 Sema::CheckedConversionKind CCK
5375 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5376 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005377 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005378 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005379 ExprResult CurInitExprRes =
5380 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005381 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005382 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005383 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005384 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005385 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005386 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005387
Douglas Gregord87b61f2009-12-10 17:56:55 +00005388 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005389 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005390 // Hack: We must pass *ResultType if available in order to set the type
5391 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5392 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5393 // temporary, not a reference, so we should pass Ty.
5394 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5395 // Since this step is never used for a reference directly, we explicitly
5396 // unwrap references here and rewrap them afterwards.
5397 // We also need to create a InitializeTemporary entity for this.
5398 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005399 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005400 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005401 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5402 InitListChecker PerformInitList(S, InitEntity,
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005403 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005404 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00005405 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005406 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005407 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005408
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005409 if (ResultType) {
5410 if ((*ResultType)->isRValueReferenceType())
5411 Ty = S.Context.getRValueReferenceType(Ty);
5412 else if ((*ResultType)->isLValueReferenceType())
5413 Ty = S.Context.getLValueReferenceType(Ty,
5414 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5415 *ResultType = Ty;
5416 }
5417
5418 InitListExpr *StructuredInitList =
5419 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005420 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005421 CurInit = shouldBindAsTemporary(InitEntity)
5422 ? S.MaybeBindToTemporary(StructuredInitList)
5423 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005424 break;
5425 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005426
Sebastian Redl10f04a62011-12-22 14:44:04 +00005427 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005428 // When an initializer list is passed for a parameter of type "reference
5429 // to object", we don't get an EK_Temporary entity, but instead an
5430 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005431 // FIXME: This is a hack. What we really should do is create a user
5432 // conversion step for this case, but this makes it considerably more
5433 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005434 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5435 Entity.getType().getNonReferenceType());
5436 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005437 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005438 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005439 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5440 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005441 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005442 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5443 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005444 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005445 ConstructorInitRequiresZeroInit,
5446 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005447 break;
5448 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005449
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005450 case SK_UnwrapInitList:
5451 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5452 break;
5453
5454 case SK_RewrapInitList: {
5455 Expr *E = CurInit.take();
5456 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5457 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005458 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005459 ILE->setSyntacticForm(Syntactic);
5460 ILE->setType(E->getType());
5461 ILE->setValueKind(E->getValueKind());
5462 CurInit = S.Owned(ILE);
5463 break;
5464 }
5465
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005466 case SK_ConstructorInitialization: {
5467 // When an initializer list is passed for a parameter of type "reference
5468 // to object", we don't get an EK_Temporary entity, but instead an
5469 // EK_Parameter entity with reference type.
5470 // FIXME: This is a hack. What we really should do is create a user
5471 // conversion step for this case, but this makes it considerably more
5472 // complicated. For now, this will do.
5473 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5474 Entity.getType().getNonReferenceType());
5475 bool UseTemporary = Entity.getType()->isReferenceType();
5476 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5477 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005478 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005479 ConstructorInitRequiresZeroInit,
5480 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005481 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005482 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005483
Douglas Gregor71d17402009-12-15 00:01:57 +00005484 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005485 step_iterator NextStep = Step;
5486 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005487 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005488 (NextStep->Kind == SK_ConstructorInitialization ||
5489 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005490 // The need for zero-initialization is recorded directly into
5491 // the call to the object's constructor within the next step.
5492 ConstructorInitRequiresZeroInit = true;
5493 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005494 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005495 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005496 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5497 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005498 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005499 Kind.getRange().getBegin());
5500
5501 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5502 TSInfo->getType().getNonLValueExprType(S.Context),
5503 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005504 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005505 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005506 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005507 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005508 break;
5509 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005510
5511 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005512 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005513 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005514 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005515 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5516 if (Result.isInvalid())
5517 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005518 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005519
5520 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005521 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005522 if (ConvTy != Sema::Compatible &&
5523 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005524 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005525 == Sema::Compatible)
5526 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005527 if (CurInitExprRes.isInvalid())
5528 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005529 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005530
Douglas Gregora41a8c52010-04-22 00:20:18 +00005531 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005532 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5533 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005534 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005535 getAssignmentAction(Entity),
5536 &Complained)) {
5537 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005538 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005539 } else if (Complained)
5540 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005541 break;
5542 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005543
5544 case SK_StringInit: {
5545 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005546 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005547 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005548 break;
5549 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005550
5551 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005552 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005553 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005554 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005555 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005556
5557 case SK_ArrayInit:
5558 // Okay: we checked everything before creating this step. Note that
5559 // this is a GNU extension.
5560 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005561 << Step->Type << CurInit.get()->getType()
5562 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005563
5564 // If the destination type is an incomplete array type, update the
5565 // type accordingly.
5566 if (ResultType) {
5567 if (const IncompleteArrayType *IncompleteDest
5568 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5569 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005570 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005571 *ResultType = S.Context.getConstantArrayType(
5572 IncompleteDest->getElementType(),
5573 ConstantSource->getSize(),
5574 ArrayType::Normal, 0);
5575 }
5576 }
5577 }
John McCallf85e1932011-06-15 23:02:42 +00005578 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005579
Richard Smith0f163e92012-02-15 22:38:09 +00005580 case SK_ParenthesizedArrayInit:
5581 // Okay: we checked everything before creating this step. Note that
5582 // this is a GNU extension.
5583 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5584 << CurInit.get()->getSourceRange();
5585 break;
5586
John McCallf85e1932011-06-15 23:02:42 +00005587 case SK_PassByIndirectCopyRestore:
5588 case SK_PassByIndirectRestore:
5589 checkIndirectCopyRestoreSource(S, CurInit.get());
5590 CurInit = S.Owned(new (S.Context)
5591 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5592 Step->Kind == SK_PassByIndirectCopyRestore));
5593 break;
5594
5595 case SK_ProduceObjCObject:
5596 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005597 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005598 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005599 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005600
5601 case SK_StdInitializerList: {
5602 QualType Dest = Step->Type;
5603 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005604 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005605 (void)Success;
5606 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005607
5608 // If the element type has a destructor, check it.
5609 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5610 if (!RD->hasIrrelevantDestructor()) {
5611 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5612 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5613 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5614 S.PDiag(diag::err_access_dtor_temp) << E);
Richard Smith82f145d2013-05-04 06:44:46 +00005615 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5616 return ExprError();
Sebastian Redl28357452012-03-05 19:35:43 +00005617 }
5618 }
5619 }
5620
Sebastian Redl2b916b82012-01-17 22:49:42 +00005621 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005622 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5623 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005624 unsigned NumInits = ILE->getNumInits();
5625 SmallVector<Expr*, 16> Converted(NumInits);
5626 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5627 S.Context.getConstantArrayType(E,
5628 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5629 NumInits),
5630 ArrayType::Normal, 0));
5631 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5632 0, HiddenArray);
5633 for (unsigned i = 0; i < NumInits; ++i) {
5634 Element.setElementIndex(i);
5635 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005636 ExprResult Res = S.PerformCopyInitialization(
5637 Element, Init.get()->getExprLoc(), Init,
5638 /*TopLevelOfInitList=*/ true);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005639 assert(!Res.isInvalid() && "Result changed since try phase.");
5640 Converted[i] = Res.take();
5641 }
5642 InitListExpr *Semantic = new (S.Context)
5643 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005644 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005645 Semantic->setSyntacticForm(ILE);
5646 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005647 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005648 CurInit = S.Owned(Semantic);
5649 break;
5650 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005651 case SK_OCLSamplerInit: {
5652 assert(Step->Type->isSamplerT() &&
5653 "Sampler initialization on non sampler type.");
5654
5655 QualType SourceType = CurInit.get()->getType();
5656 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5657
5658 if (EntityKind == InitializedEntity::EK_Parameter) {
5659 if (!SourceType->isSamplerT())
5660 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5661 << SourceType;
5662 } else if (EntityKind != InitializedEntity::EK_Variable) {
5663 llvm_unreachable("Invalid EntityKind!");
5664 }
5665
5666 break;
5667 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005668 case SK_OCLZeroEvent: {
5669 assert(Step->Type->isEventT() &&
5670 "Event initialization on non event type.");
5671
5672 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5673 CK_ZeroToOCLEvent,
5674 CurInit.get()->getValueKind());
5675 break;
5676 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005677 }
5678 }
John McCall15d7d122010-11-11 03:21:53 +00005679
5680 // Diagnose non-fatal problems with the completed initialization.
5681 if (Entity.getKind() == InitializedEntity::EK_Member &&
5682 cast<FieldDecl>(Entity.getDecl())->isBitField())
5683 S.CheckBitFieldInitialization(Kind.getLocation(),
5684 cast<FieldDecl>(Entity.getDecl()),
5685 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005686
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005687 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005688}
5689
Richard Smithd5bc8672012-12-08 02:01:17 +00005690/// Somewhere within T there is an uninitialized reference subobject.
5691/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005692static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5693 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005694 if (T->isReferenceType()) {
5695 S.Diag(Loc, diag::err_reference_without_init)
5696 << T.getNonReferenceType();
5697 return true;
5698 }
5699
5700 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5701 if (!RD || !RD->hasUninitializedReferenceMember())
5702 return false;
5703
5704 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5705 FE = RD->field_end(); FI != FE; ++FI) {
5706 if (FI->isUnnamedBitfield())
5707 continue;
5708
5709 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5710 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5711 return true;
5712 }
5713 }
5714
5715 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5716 BE = RD->bases_end();
5717 BI != BE; ++BI) {
5718 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5719 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5720 return true;
5721 }
5722 }
5723
5724 return false;
5725}
5726
5727
Douglas Gregor20093b42009-12-09 23:02:17 +00005728//===----------------------------------------------------------------------===//
5729// Diagnose initialization failures
5730//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00005731
5732/// Emit notes associated with an initialization that failed due to a
5733/// "simple" conversion failure.
5734static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5735 Expr *op) {
5736 QualType destType = entity.getType();
5737 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5738 op->getType()->isObjCObjectPointerType()) {
5739
5740 // Emit a possible note about the conversion failing because the
5741 // operand is a message send with a related result type.
5742 S.EmitRelatedResultTypeNote(op);
5743
5744 // Emit a possible note about a return failing because we're
5745 // expecting a related result type.
5746 if (entity.getKind() == InitializedEntity::EK_Result)
5747 S.EmitRelatedResultTypeNoteForReturn(destType);
5748 }
5749}
5750
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005751bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005752 const InitializedEntity &Entity,
5753 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005754 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005755 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005756 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005757
Douglas Gregord6542d82009-12-22 15:35:07 +00005758 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005759 switch (Failure) {
5760 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005761 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005762 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005763 // Dig out the reference subobject which is uninitialized and diagnose it.
5764 // If this is value-initialization, this could be nested some way within
5765 // the target type.
5766 assert(Kind.getKind() == InitializationKind::IK_Value ||
5767 DestType->isReferenceType());
5768 bool Diagnosed =
5769 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5770 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5771 (void)Diagnosed;
5772 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005773 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005774 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005775 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005776
Douglas Gregor20093b42009-12-09 23:02:17 +00005777 case FK_ArrayNeedsInitList:
5778 case FK_ArrayNeedsInitListOrStringLiteral:
5779 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5780 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5781 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005782
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005783 case FK_ArrayTypeMismatch:
5784 case FK_NonConstantArrayInit:
5785 S.Diag(Kind.getLocation(),
5786 (Failure == FK_ArrayTypeMismatch
5787 ? diag::err_array_init_different_type
5788 : diag::err_array_init_non_constant_array))
5789 << DestType.getNonReferenceType()
5790 << Args[0]->getType()
5791 << Args[0]->getSourceRange();
5792 break;
5793
John McCall73076432012-01-05 00:13:19 +00005794 case FK_VariableLengthArrayHasInitializer:
5795 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5796 << Args[0]->getSourceRange();
5797 break;
5798
John McCall6bb80172010-03-30 21:47:33 +00005799 case FK_AddressOfOverloadFailed: {
5800 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005801 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005802 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005803 true,
5804 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005805 break;
John McCall6bb80172010-03-30 21:47:33 +00005806 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005807
Douglas Gregor20093b42009-12-09 23:02:17 +00005808 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005809 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005810 switch (FailedOverloadResult) {
5811 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005812 if (Failure == FK_UserConversionOverloadFailed)
5813 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5814 << Args[0]->getType() << DestType
5815 << Args[0]->getSourceRange();
5816 else
5817 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5818 << DestType << Args[0]->getType()
5819 << Args[0]->getSourceRange();
5820
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005821 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005822 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005823
Douglas Gregor20093b42009-12-09 23:02:17 +00005824 case OR_No_Viable_Function:
5825 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5826 << Args[0]->getType() << DestType.getNonReferenceType()
5827 << Args[0]->getSourceRange();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005828 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005829 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005830
Douglas Gregor20093b42009-12-09 23:02:17 +00005831 case OR_Deleted: {
5832 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5833 << Args[0]->getType() << DestType.getNonReferenceType()
5834 << Args[0]->getSourceRange();
5835 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005836 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005837 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5838 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005839 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005840 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005841 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005842 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005843 }
5844 break;
5845 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005846
Douglas Gregor20093b42009-12-09 23:02:17 +00005847 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005848 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005849 }
5850 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005851
Douglas Gregor20093b42009-12-09 23:02:17 +00005852 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005853 if (isa<InitListExpr>(Args[0])) {
5854 S.Diag(Kind.getLocation(),
5855 diag::err_lvalue_reference_bind_to_initlist)
5856 << DestType.getNonReferenceType().isVolatileQualified()
5857 << DestType.getNonReferenceType()
5858 << Args[0]->getSourceRange();
5859 break;
5860 }
5861 // Intentional fallthrough
5862
Douglas Gregor20093b42009-12-09 23:02:17 +00005863 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005864 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005865 Failure == FK_NonConstLValueReferenceBindingToTemporary
5866 ? diag::err_lvalue_reference_bind_to_temporary
5867 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005868 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005869 << DestType.getNonReferenceType()
5870 << Args[0]->getType()
5871 << Args[0]->getSourceRange();
5872 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005873
Douglas Gregor20093b42009-12-09 23:02:17 +00005874 case FK_RValueReferenceBindingToLValue:
5875 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005876 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005877 << Args[0]->getSourceRange();
5878 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005879
Douglas Gregor20093b42009-12-09 23:02:17 +00005880 case FK_ReferenceInitDropsQualifiers:
5881 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5882 << DestType.getNonReferenceType()
5883 << Args[0]->getType()
5884 << Args[0]->getSourceRange();
5885 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005886
Douglas Gregor20093b42009-12-09 23:02:17 +00005887 case FK_ReferenceInitFailed:
5888 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5889 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005890 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005891 << Args[0]->getType()
5892 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00005893 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005894 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005895
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005896 case FK_ConversionFailed: {
5897 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005898 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005899 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005900 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005901 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005902 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005903 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005904 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5905 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00005906 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005907 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005908 }
John Wiegley429bb272011-04-08 18:41:53 +00005909
5910 case FK_ConversionFromPropertyFailed:
5911 // No-op. This error has already been reported.
5912 break;
5913
Douglas Gregord87b61f2009-12-10 17:56:55 +00005914 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005915 SourceRange R;
5916
5917 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005918 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005919 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005920 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005921 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005922
Douglas Gregor19311e72010-09-08 21:40:08 +00005923 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5924 if (Kind.isCStyleOrFunctionalCast())
5925 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5926 << R;
5927 else
5928 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5929 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005930 break;
5931 }
5932
5933 case FK_ReferenceBindingToInitList:
5934 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5935 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5936 break;
5937
5938 case FK_InitListBadDestinationType:
5939 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5940 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5941 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005942
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005943 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005944 case FK_ConstructorOverloadFailed: {
5945 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005946 if (Args.size())
5947 ArgsRange = SourceRange(Args.front()->getLocStart(),
5948 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005949
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005950 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005951 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005952 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005953 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005954 }
5955
Douglas Gregor51c56d62009-12-14 20:49:26 +00005956 // FIXME: Using "DestType" for the entity we're printing is probably
5957 // bad.
5958 switch (FailedOverloadResult) {
5959 case OR_Ambiguous:
5960 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5961 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005962 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005963 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005964
Douglas Gregor51c56d62009-12-14 20:49:26 +00005965 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005966 if (Kind.getKind() == InitializationKind::IK_Default &&
5967 (Entity.getKind() == InitializedEntity::EK_Base ||
5968 Entity.getKind() == InitializedEntity::EK_Member) &&
5969 isa<CXXConstructorDecl>(S.CurContext)) {
5970 // This is implicit default initialization of a member or
5971 // base within a constructor. If no viable function was
5972 // found, notify the user that she needs to explicitly
5973 // initialize this base/member.
5974 CXXConstructorDecl *Constructor
5975 = cast<CXXConstructorDecl>(S.CurContext);
5976 if (Entity.getKind() == InitializedEntity::EK_Base) {
5977 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00005978 << (Constructor->getInheritedConstructor() ? 2 :
5979 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005980 << S.Context.getTypeDeclType(Constructor->getParent())
5981 << /*base=*/0
5982 << Entity.getType();
5983
5984 RecordDecl *BaseDecl
5985 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5986 ->getDecl();
5987 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5988 << S.Context.getTagDeclType(BaseDecl);
5989 } else {
5990 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00005991 << (Constructor->getInheritedConstructor() ? 2 :
5992 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005993 << S.Context.getTypeDeclType(Constructor->getParent())
5994 << /*member=*/1
5995 << Entity.getName();
5996 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5997
5998 if (const RecordType *Record
5999 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006000 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006001 diag::note_previous_decl)
6002 << S.Context.getTagDeclType(Record->getDecl());
6003 }
6004 break;
6005 }
6006
Douglas Gregor51c56d62009-12-14 20:49:26 +00006007 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6008 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006009 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006010 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006011
Douglas Gregor51c56d62009-12-14 20:49:26 +00006012 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006013 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006014 OverloadingResult Ovl
6015 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006016 if (Ovl != OR_Deleted) {
6017 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6018 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006019 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006020 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006021 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006022
6023 // If this is a defaulted or implicitly-declared function, then
6024 // it was implicitly deleted. Make it clear that the deletion was
6025 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006026 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006027 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006028 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006029 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006030 else
6031 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6032 << true << DestType << ArgsRange;
6033
6034 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006035 break;
6036 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006037
Douglas Gregor51c56d62009-12-14 20:49:26 +00006038 case OR_Success:
6039 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006040 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006041 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006042 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006043
Douglas Gregor99a2e602009-12-16 01:38:02 +00006044 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006045 if (Entity.getKind() == InitializedEntity::EK_Member &&
6046 isa<CXXConstructorDecl>(S.CurContext)) {
6047 // This is implicit default-initialization of a const member in
6048 // a constructor. Complain that it needs to be explicitly
6049 // initialized.
6050 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6051 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006052 << (Constructor->getInheritedConstructor() ? 2 :
6053 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006054 << S.Context.getTypeDeclType(Constructor->getParent())
6055 << /*const=*/1
6056 << Entity.getName();
6057 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6058 << Entity.getName();
6059 } else {
6060 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6061 << DestType << (bool)DestType->getAs<RecordType>();
6062 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006063 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006064
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006065 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006066 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006067 diag::err_init_incomplete_type);
6068 break;
6069
Sebastian Redl14b0c192011-09-24 17:48:00 +00006070 case FK_ListInitializationFailed: {
6071 // Run the init list checker again to emit diagnostics.
6072 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6073 QualType DestType = Entity.getType();
6074 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00006075 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00006076 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00006077 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006078 assert(DiagnoseInitList.HadError() &&
6079 "Inconsistent init list check result.");
6080 break;
6081 }
John McCall5acb0c92011-10-17 18:40:02 +00006082
6083 case FK_PlaceholderType: {
6084 // FIXME: Already diagnosed!
6085 break;
6086 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006087
6088 case FK_InitListElementCopyFailure: {
6089 // Try to perform all copies again.
6090 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6091 unsigned NumInits = InitList->getNumInits();
6092 QualType DestType = Entity.getType();
6093 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006094 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006095 (void)Success;
6096 assert(Success && "Where did the std::initializer_list go?");
6097 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6098 S.Context.getConstantArrayType(E,
6099 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6100 NumInits),
6101 ArrayType::Normal, 0));
6102 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6103 0, HiddenArray);
6104 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6105 // where the init list type is wrong, e.g.
6106 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6107 // FIXME: Emit a note if we hit the limit?
6108 int ErrorCount = 0;
6109 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6110 Element.setElementIndex(i);
6111 ExprResult Init = S.Owned(InitList->getInit(i));
6112 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6113 .isInvalid())
6114 ++ErrorCount;
6115 }
6116 break;
6117 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006118
6119 case FK_ExplicitConstructor: {
6120 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6121 << Args[0]->getSourceRange();
6122 OverloadCandidateSet::iterator Best;
6123 OverloadingResult Ovl
6124 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006125 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006126 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6127 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6128 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6129 break;
6130 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006131 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006132
Douglas Gregora41a8c52010-04-22 00:20:18 +00006133 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006134 return true;
6135}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006136
Chris Lattner5f9e2722011-07-23 10:55:15 +00006137void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006138 switch (SequenceKind) {
6139 case FailedSequence: {
6140 OS << "Failed sequence: ";
6141 switch (Failure) {
6142 case FK_TooManyInitsForReference:
6143 OS << "too many initializers for reference";
6144 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006145
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006146 case FK_ArrayNeedsInitList:
6147 OS << "array requires initializer list";
6148 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006149
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006150 case FK_ArrayNeedsInitListOrStringLiteral:
6151 OS << "array requires initializer list or string literal";
6152 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006153
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006154 case FK_ArrayTypeMismatch:
6155 OS << "array type mismatch";
6156 break;
6157
6158 case FK_NonConstantArrayInit:
6159 OS << "non-constant array initializer";
6160 break;
6161
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006162 case FK_AddressOfOverloadFailed:
6163 OS << "address of overloaded function failed";
6164 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006165
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006166 case FK_ReferenceInitOverloadFailed:
6167 OS << "overload resolution for reference initialization failed";
6168 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006169
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006170 case FK_NonConstLValueReferenceBindingToTemporary:
6171 OS << "non-const lvalue reference bound to temporary";
6172 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006173
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006174 case FK_NonConstLValueReferenceBindingToUnrelated:
6175 OS << "non-const lvalue reference bound to unrelated type";
6176 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006177
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006178 case FK_RValueReferenceBindingToLValue:
6179 OS << "rvalue reference bound to an lvalue";
6180 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006181
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006182 case FK_ReferenceInitDropsQualifiers:
6183 OS << "reference initialization drops qualifiers";
6184 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006185
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006186 case FK_ReferenceInitFailed:
6187 OS << "reference initialization failed";
6188 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006189
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006190 case FK_ConversionFailed:
6191 OS << "conversion failed";
6192 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006193
John Wiegley429bb272011-04-08 18:41:53 +00006194 case FK_ConversionFromPropertyFailed:
6195 OS << "conversion from property failed";
6196 break;
6197
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006198 case FK_TooManyInitsForScalar:
6199 OS << "too many initializers for scalar";
6200 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006201
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006202 case FK_ReferenceBindingToInitList:
6203 OS << "referencing binding to initializer list";
6204 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006205
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006206 case FK_InitListBadDestinationType:
6207 OS << "initializer list for non-aggregate, non-scalar type";
6208 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006209
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006210 case FK_UserConversionOverloadFailed:
6211 OS << "overloading failed for user-defined conversion";
6212 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006213
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006214 case FK_ConstructorOverloadFailed:
6215 OS << "constructor overloading failed";
6216 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006217
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006218 case FK_DefaultInitOfConst:
6219 OS << "default initialization of a const variable";
6220 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006221
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006222 case FK_Incomplete:
6223 OS << "initialization of incomplete type";
6224 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006225
6226 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006227 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006228 break;
6229
John McCall73076432012-01-05 00:13:19 +00006230 case FK_VariableLengthArrayHasInitializer:
6231 OS << "variable length array has an initializer";
6232 break;
6233
John McCall5acb0c92011-10-17 18:40:02 +00006234 case FK_PlaceholderType:
6235 OS << "initializer expression isn't contextually valid";
6236 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006237
6238 case FK_ListConstructorOverloadFailed:
6239 OS << "list constructor overloading failed";
6240 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006241
6242 case FK_InitListElementCopyFailure:
6243 OS << "copy construction of initializer list element failed";
6244 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006245
6246 case FK_ExplicitConstructor:
6247 OS << "list copy initialization chose explicit constructor";
6248 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006249 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006250 OS << '\n';
6251 return;
6252 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006253
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006254 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006255 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006256 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006257
Sebastian Redl7491c492011-06-05 13:59:11 +00006258 case NormalSequence:
6259 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006260 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006261 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006262
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006263 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6264 if (S != step_begin()) {
6265 OS << " -> ";
6266 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006267
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006268 switch (S->Kind) {
6269 case SK_ResolveAddressOfOverloadedFunction:
6270 OS << "resolve address of overloaded function";
6271 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006272
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006273 case SK_CastDerivedToBaseRValue:
6274 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6275 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006276
Sebastian Redl906082e2010-07-20 04:20:21 +00006277 case SK_CastDerivedToBaseXValue:
6278 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6279 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006280
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006281 case SK_CastDerivedToBaseLValue:
6282 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6283 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006284
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006285 case SK_BindReference:
6286 OS << "bind reference to lvalue";
6287 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006288
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006289 case SK_BindReferenceToTemporary:
6290 OS << "bind reference to a temporary";
6291 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006292
Douglas Gregor523d46a2010-04-18 07:40:54 +00006293 case SK_ExtraneousCopyToTemporary:
6294 OS << "extraneous C++03 copy to temporary";
6295 break;
6296
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006297 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006298 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006299 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006300
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006301 case SK_QualificationConversionRValue:
6302 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006303 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006304
Sebastian Redl906082e2010-07-20 04:20:21 +00006305 case SK_QualificationConversionXValue:
6306 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006307 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006308
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006309 case SK_QualificationConversionLValue:
6310 OS << "qualification conversion (lvalue)";
6311 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006312
Jordan Rose1fd1e282013-04-11 00:58:58 +00006313 case SK_LValueToRValue:
6314 OS << "load (lvalue to rvalue)";
6315 break;
6316
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006317 case SK_ConversionSequence:
6318 OS << "implicit conversion sequence (";
6319 S->ICS->DebugPrint(); // FIXME: use OS
6320 OS << ")";
6321 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006322
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006323 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006324 OS << "list aggregate initialization";
6325 break;
6326
6327 case SK_ListConstructorCall:
6328 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006329 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006330
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006331 case SK_UnwrapInitList:
6332 OS << "unwrap reference initializer list";
6333 break;
6334
6335 case SK_RewrapInitList:
6336 OS << "rewrap reference initializer list";
6337 break;
6338
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006339 case SK_ConstructorInitialization:
6340 OS << "constructor initialization";
6341 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006342
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006343 case SK_ZeroInitialization:
6344 OS << "zero initialization";
6345 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006346
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006347 case SK_CAssignment:
6348 OS << "C assignment";
6349 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006350
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006351 case SK_StringInit:
6352 OS << "string initialization";
6353 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006354
6355 case SK_ObjCObjectConversion:
6356 OS << "Objective-C object conversion";
6357 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006358
6359 case SK_ArrayInit:
6360 OS << "array initialization";
6361 break;
John McCallf85e1932011-06-15 23:02:42 +00006362
Richard Smith0f163e92012-02-15 22:38:09 +00006363 case SK_ParenthesizedArrayInit:
6364 OS << "parenthesized array initialization";
6365 break;
6366
John McCallf85e1932011-06-15 23:02:42 +00006367 case SK_PassByIndirectCopyRestore:
6368 OS << "pass by indirect copy and restore";
6369 break;
6370
6371 case SK_PassByIndirectRestore:
6372 OS << "pass by indirect restore";
6373 break;
6374
6375 case SK_ProduceObjCObject:
6376 OS << "Objective-C object retension";
6377 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006378
6379 case SK_StdInitializerList:
6380 OS << "std::initializer_list from initializer list";
6381 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006382
Guy Benyei21f18c42013-02-07 10:55:47 +00006383 case SK_OCLSamplerInit:
6384 OS << "OpenCL sampler_t from integer constant";
6385 break;
6386
Guy Benyeie6b9d802013-01-20 12:31:11 +00006387 case SK_OCLZeroEvent:
6388 OS << "OpenCL event_t from zero";
6389 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006390 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006391
6392 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006393 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006394
6395 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006396}
6397
6398void InitializationSequence::dump() const {
6399 dump(llvm::errs());
6400}
6401
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006402static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6403 QualType EntityType,
6404 const Expr *PreInit,
6405 const Expr *PostInit) {
6406 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6407 return;
6408
6409 // A narrowing conversion can only appear as the final implicit conversion in
6410 // an initialization sequence.
6411 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6412 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6413 return;
6414
6415 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6416 const StandardConversionSequence *SCS = 0;
6417 switch (ICS.getKind()) {
6418 case ImplicitConversionSequence::StandardConversion:
6419 SCS = &ICS.Standard;
6420 break;
6421 case ImplicitConversionSequence::UserDefinedConversion:
6422 SCS = &ICS.UserDefined.After;
6423 break;
6424 case ImplicitConversionSequence::AmbiguousConversion:
6425 case ImplicitConversionSequence::EllipsisConversion:
6426 case ImplicitConversionSequence::BadConversion:
6427 return;
6428 }
6429
6430 // Determine the type prior to the narrowing conversion. If a conversion
6431 // operator was used, this may be different from both the type of the entity
6432 // and of the pre-initialization expression.
6433 QualType PreNarrowingType = PreInit->getType();
6434 if (Seq.step_begin() + 1 != Seq.step_end())
6435 PreNarrowingType = Seq.step_end()[-2].Type;
6436
6437 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6438 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006439 QualType ConstantType;
6440 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6441 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006442 case NK_Not_Narrowing:
6443 // No narrowing occurred.
6444 return;
6445
6446 case NK_Type_Narrowing:
6447 // This was a floating-to-integer conversion, which is always considered a
6448 // narrowing conversion even if the value is a constant and can be
6449 // represented exactly as an integer.
6450 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006451 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006452 diag::warn_init_list_type_narrowing
6453 : S.isSFINAEContext()?
6454 diag::err_init_list_type_narrowing_sfinae
6455 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006456 << PostInit->getSourceRange()
6457 << PreNarrowingType.getLocalUnqualifiedType()
6458 << EntityType.getLocalUnqualifiedType();
6459 break;
6460
6461 case NK_Constant_Narrowing:
6462 // A constant value was narrowed.
6463 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006464 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006465 diag::warn_init_list_constant_narrowing
6466 : S.isSFINAEContext()?
6467 diag::err_init_list_constant_narrowing_sfinae
6468 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006469 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006470 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006471 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006472 break;
6473
6474 case NK_Variable_Narrowing:
6475 // A variable's value may have been narrowed.
6476 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006477 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006478 diag::warn_init_list_variable_narrowing
6479 : S.isSFINAEContext()?
6480 diag::err_init_list_variable_narrowing_sfinae
6481 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006482 << PostInit->getSourceRange()
6483 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006484 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006485 break;
6486 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006487
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006488 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006489 llvm::raw_svector_ostream OS(StaticCast);
6490 OS << "static_cast<";
6491 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6492 // It's important to use the typedef's name if there is one so that the
6493 // fixit doesn't break code using types like int64_t.
6494 //
6495 // FIXME: This will break if the typedef requires qualification. But
6496 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006497 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006498 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006499 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006500 else {
6501 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6502 // with a broken cast.
6503 return;
6504 }
6505 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006506 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6507 << PostInit->getSourceRange()
6508 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006509 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006510 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006511}
6512
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006513//===----------------------------------------------------------------------===//
6514// Initialization helper functions
6515//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006516bool
6517Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6518 ExprResult Init) {
6519 if (Init.isInvalid())
6520 return false;
6521
6522 Expr *InitE = Init.get();
6523 assert(InitE && "No initialization expression");
6524
Douglas Gregor3c394c52012-07-31 22:15:04 +00006525 InitializationKind Kind
6526 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006527 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006528 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006529}
6530
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006531ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006532Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6533 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006534 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006535 bool TopLevelOfInitList,
6536 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006537 if (Init.isInvalid())
6538 return ExprError();
6539
John McCall15d7d122010-11-11 03:21:53 +00006540 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006541 assert(InitE && "No initialization expression?");
6542
6543 if (EqualLoc.isInvalid())
6544 EqualLoc = InitE->getLocStart();
6545
6546 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006547 EqualLoc,
6548 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006549 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006550 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006551
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006552 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006553
6554 if (!Result.isInvalid() && TopLevelOfInitList)
6555 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6556 InitE, Result.get());
6557
6558 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006559}