blob: a3b78787e43ed1f543eb0fbb2de819339e1ae069 [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
Hans Wennborg0ff50742013-05-15 11:03:04 +000035/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38 if (Context.typesAreCompatible(Context.getWideCharType(), T))
39 return true;
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
43 }
44 return false;
45}
46
47enum StringInitFailureKind {
48 SIF_None,
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
52 SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000061 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg0ff50742013-05-15 11:03:04 +000062 return SIF_Other;
Eli Friedman8718a6a2009-05-29 18:22:49 +000063
Chris Lattner8879e3b2009-02-26 23:26:43 +000064 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner8879e3b2009-02-26 23:26:43 +000067 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg0ff50742013-05-15 11:03:04 +000069 return SIF_None;
Chris Lattner8879e3b2009-02-26 23:26:43 +000070
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Hans Wennborg0ff50742013-05-15 11:03:04 +000073 if (SL == 0)
74 return SIF_Other;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000075
Hans Wennborg0ff50742013-05-15 11:03:04 +000076 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregor5cee1192011-07-27 05:40:30 +000078
79 switch (SL->getKind()) {
80 case StringLiteral::Ascii:
81 case StringLiteral::UTF8:
82 // char array can be initialized with a narrow string.
83 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg0ff50742013-05-15 11:03:04 +000084 if (ElemTy->isCharType())
85 return SIF_None;
86 if (IsWideCharCompatible(ElemTy, Context))
87 return SIF_NarrowStringIntoWideChar;
88 return SIF_Other;
89 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90 // "An array with element type compatible with a qualified or unqualified
91 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92 // string literal with the corresponding encoding prefix (L, u, or U,
93 // respectively), optionally enclosed in braces.
Douglas Gregor5cee1192011-07-27 05:40:30 +000094 case StringLiteral::UTF16:
Hans Wennborg0ff50742013-05-15 11:03:04 +000095 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96 return SIF_None;
97 if (ElemTy->isCharType())
98 return SIF_WideStringIntoChar;
99 if (IsWideCharCompatible(ElemTy, Context))
100 return SIF_IncompatWideStringIntoWideChar;
101 return SIF_Other;
Douglas Gregor5cee1192011-07-27 05:40:30 +0000102 case StringLiteral::UTF32:
Hans Wennborg0ff50742013-05-15 11:03:04 +0000103 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104 return SIF_None;
105 if (ElemTy->isCharType())
106 return SIF_WideStringIntoChar;
107 if (IsWideCharCompatible(ElemTy, Context))
108 return SIF_IncompatWideStringIntoWideChar;
109 return SIF_Other;
Douglas Gregor5cee1192011-07-27 05:40:30 +0000110 case StringLiteral::Wide:
Hans Wennborg0ff50742013-05-15 11:03:04 +0000111 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112 return SIF_None;
113 if (ElemTy->isCharType())
114 return SIF_WideStringIntoChar;
115 if (IsWideCharCompatible(ElemTy, Context))
116 return SIF_IncompatWideStringIntoWideChar;
117 return SIF_Other;
Douglas Gregor5cee1192011-07-27 05:40:30 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Douglas Gregor5cee1192011-07-27 05:40:30 +0000120 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000121}
122
Hans Wennborg0ff50742013-05-15 11:03:04 +0000123static bool IsStringInit(Expr* init, QualType declType, ASTContext& Context) {
John McCallce6c9b72011-02-21 07:22:22 +0000124 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg0ff50742013-05-15 11:03:04 +0000125 if (!arrayType)
126 return false;
127 return IsStringInit(init, arrayType, Context) == SIF_None;
John McCallce6c9b72011-02-21 07:22:22 +0000128}
129
Richard Smith30ae1ed2013-05-05 16:40:13 +0000130/// Update the type of a string literal, including any surrounding parentheses,
131/// to match the type of the object which it is initializing.
132static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smith27f9cf32013-05-06 00:35:47 +0000133 while (true) {
Richard Smith30ae1ed2013-05-05 16:40:13 +0000134 E->setType(Ty);
Richard Smith27f9cf32013-05-06 00:35:47 +0000135 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
136 break;
137 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
138 E = PE->getSubExpr();
139 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
140 E = UO->getSubExpr();
141 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
142 E = GSE->getResultExpr();
143 else
144 llvm_unreachable("unexpected expr in string literal init");
Richard Smith30ae1ed2013-05-05 16:40:13 +0000145 }
Richard Smith30ae1ed2013-05-05 16:40:13 +0000146}
147
John McCallfef8b342011-02-21 07:57:55 +0000148static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
149 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000150 // Get the length of the string as parsed.
151 uint64_t StrLength =
152 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
153
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000155 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000156 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000157 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +0000158 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000159 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000160 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
161 ConstVal,
162 ArrayType::Normal, 0);
Richard Smith30ae1ed2013-05-05 16:40:13 +0000163 updateStringLiteralType(Str, DeclT);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000164 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000165 }
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Eli Friedman8718a6a2009-05-29 18:22:49 +0000167 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000169 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000170 // the size may be smaller or larger than the string we are initializing.
171 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000172 if (S.getLangOpts().CPlusPlus) {
Richard Smith30ae1ed2013-05-05 16:40:13 +0000173 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000174 // For Pascal strings it's OK to strip off the terminating null character,
175 // so the example below is valid:
176 //
177 // unsigned char a[2] = "\pa";
178 if (SL->isPascal())
179 StrLength--;
180 }
181
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000182 // [dcl.init.string]p2
183 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000184 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000185 diag::err_initializer_string_for_char_array_too_long)
186 << Str->getSourceRange();
187 } else {
188 // C99 6.7.8p14.
189 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000190 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000191 diag::warn_initializer_string_for_char_array_too_long)
192 << Str->getSourceRange();
193 }
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Eli Friedman8718a6a2009-05-29 18:22:49 +0000195 // Set the type to the actual size that we are initializing. If we have
196 // something like:
197 // char x[1] = "foo";
198 // then this will set the string literal's type to char[1].
Richard Smith30ae1ed2013-05-05 16:40:13 +0000199 updateStringLiteralType(Str, DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000200}
201
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000202//===----------------------------------------------------------------------===//
203// Semantic checking for initializer lists.
204//===----------------------------------------------------------------------===//
205
Douglas Gregor9e80f722009-01-29 01:05:33 +0000206/// @brief Semantic checking for initializer lists.
207///
208/// The InitListChecker class contains a set of routines that each
209/// handle the initialization of a certain kind of entity, e.g.,
210/// arrays, vectors, struct/union types, scalars, etc. The
211/// InitListChecker itself performs a recursive walk of the subobject
212/// structure of the type to be initialized, while stepping through
213/// the initializer list one element at a time. The IList and Index
214/// parameters to each of the Check* routines contain the active
215/// (syntactic) initializer list and the index into that initializer
216/// list that represents the current initializer. Each routine is
217/// responsible for moving that Index forward as it consumes elements.
218///
219/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000220/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000221/// initializer list and the index into that initializer list where we
222/// are copying initializers as we map them over to the semantic
223/// list. Once we have completed our recursive walk of the subobject
224/// structure, we will have constructed a full semantic initializer
225/// list.
226///
227/// C99 designators cause changes in the initializer list traversal,
228/// because they make the initialization "jump" into a specific
229/// subobject and then continue the initialization from that
230/// point. CheckDesignatedInitializer() recursively steps into the
231/// designated subobject and manages backing out the recursion to
232/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000233namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000234class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000235 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000237 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000238 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000249 unsigned &StructuredIndex,
250 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000251 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000252 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000253 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000254 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000255 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000256 unsigned &StructuredIndex,
257 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000258 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000259 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000260 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000261 InitListExpr *StructuredList,
262 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000263 void CheckComplexType(const InitializedEntity &Entity,
264 InitListExpr *IList, QualType DeclType,
265 unsigned &Index,
266 InitListExpr *StructuredList,
267 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000268 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000269 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000270 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000271 InitListExpr *StructuredList,
272 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000273 void CheckReferenceType(const InitializedEntity &Entity,
274 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000275 unsigned &Index,
276 InitListExpr *StructuredList,
277 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000278 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000279 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000280 InitListExpr *StructuredList,
281 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000282 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000283 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000284 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000285 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000286 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000287 unsigned &StructuredIndex,
288 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000289 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000290 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000291 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000292 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000293 InitListExpr *StructuredList,
294 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000295 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000296 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000297 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000298 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000299 RecordDecl::field_iterator *NextField,
300 llvm::APSInt *NextElementIndex,
301 unsigned &Index,
302 InitListExpr *StructuredList,
303 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000304 bool FinishSubobjectInit,
305 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000306 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
307 QualType CurrentObjectType,
308 InitListExpr *StructuredList,
309 unsigned StructuredIndex,
310 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000311 void UpdateStructuredListElement(InitListExpr *StructuredList,
312 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000313 Expr *expr);
314 int numArrayElements(QualType DeclType);
315 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000316
Douglas Gregord6d37de2009-12-22 00:05:34 +0000317 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
318 const InitializedEntity &ParentEntity,
319 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000320 void FillInValueInitializations(const InitializedEntity &Entity,
321 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000322 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
323 Expr *InitExpr, FieldDecl *Field,
324 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000325 void CheckValueInitializable(const InitializedEntity &Entity);
326
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000327public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000329 InitListExpr *IL, QualType &T, bool VerifyOnly,
330 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000331 bool HadError() { return hadError; }
332
333 // @brief Retrieves the fully-structured initializer list used for
334 // semantic analysis and code generation.
335 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
336};
Chris Lattner8b419b92009-02-24 22:48:58 +0000337} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000338
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000339void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
340 assert(VerifyOnly &&
341 "CheckValueInitializable is only inteded for verification mode.");
342
343 SourceLocation Loc;
344 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
345 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000346 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000347 if (InitSeq.Failed())
348 hadError = true;
349}
350
Douglas Gregord6d37de2009-12-22 00:05:34 +0000351void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
352 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000353 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000354 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000355 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000356 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000358 = InitializedEntity::InitializeMember(Field, &ParentEntity);
359 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000360 // If there's no explicit initializer but we have a default initializer, use
361 // that. This only happens in C++1y, since classes with default
362 // initializers are not aggregates in C++11.
363 if (Field->hasInClassInitializer()) {
364 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
365 ILE->getRBraceLoc(), Field);
366 if (Init < NumInits)
367 ILE->setInit(Init, DIE);
368 else {
369 ILE->updateInit(SemaRef.Context, Init, DIE);
370 RequiresSecondPass = true;
371 }
372 return;
373 }
374
Douglas Gregord6d37de2009-12-22 00:05:34 +0000375 // FIXME: We probably don't need to handle references
376 // specially here, since value-initialization of references is
377 // handled in InitializationSequence.
378 if (Field->getType()->isReferenceType()) {
379 // C++ [dcl.init.aggr]p9:
380 // If an incomplete or empty initializer-list leaves a
381 // member of reference type uninitialized, the program is
382 // ill-formed.
383 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
384 << Field->getType()
385 << ILE->getSyntacticForm()->getSourceRange();
386 SemaRef.Diag(Field->getLocation(),
387 diag::note_uninit_reference_member);
388 hadError = true;
389 return;
390 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000391
Douglas Gregord6d37de2009-12-22 00:05:34 +0000392 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
393 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000394 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000395 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000396 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000397 hadError = true;
398 return;
399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000400
John McCall60d7b3a2010-08-24 06:29:42 +0000401 ExprResult MemberInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000402 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000403 if (MemberInit.isInvalid()) {
404 hadError = true;
405 return;
406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000407
Douglas Gregord6d37de2009-12-22 00:05:34 +0000408 if (hadError) {
409 // Do nothing
410 } else if (Init < NumInits) {
411 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000412 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000413 // Value-initialization requires a constructor call, so
414 // extend the initializer list to include the constructor
415 // call and make a note that we'll need to take another pass
416 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000417 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000418 RequiresSecondPass = true;
419 }
420 } else if (InitListExpr *InnerILE
421 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000422 FillInValueInitializations(MemberEntity, InnerILE,
423 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000424}
425
Douglas Gregor4c678342009-01-28 21:54:33 +0000426/// Recursively replaces NULL values within the given initializer list
427/// with expressions that perform value-initialization of the
428/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000429void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000430InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
431 InitListExpr *ILE,
432 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000433 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000434 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000435 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000436 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000437 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Ted Kremenek6217b802009-07-29 21:53:49 +0000439 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000440 const RecordDecl *RDecl = RType->getDecl();
441 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000442 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
443 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000444 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
445 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
446 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
447 FieldEnd = RDecl->field_end();
448 Field != FieldEnd; ++Field) {
449 if (Field->hasInClassInitializer()) {
450 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
451 break;
452 }
453 }
454 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000455 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000456 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
457 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000458 Field != FieldEnd; ++Field) {
459 if (Field->isUnnamedBitfield())
460 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000461
Douglas Gregord6d37de2009-12-22 00:05:34 +0000462 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000463 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000464
David Blaikie581deb32012-06-06 20:45:41 +0000465 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000466 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000467 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000468
Douglas Gregord6d37de2009-12-22 00:05:34 +0000469 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000470
Douglas Gregord6d37de2009-12-22 00:05:34 +0000471 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000472 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000473 break;
474 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000475 }
476
477 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000478 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000479
480 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000482 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000483 unsigned NumInits = ILE->getNumInits();
484 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000485 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000486 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000487 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
488 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000489 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000490 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000491 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000492 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000493 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000494 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000495 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000496 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000497 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000498
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000499
Douglas Gregor87fd7032009-02-02 17:43:21 +0000500 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000501 if (hadError)
502 return;
503
Anders Carlssond3d824d2010-01-23 04:34:47 +0000504 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
505 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000506 ElementEntity.setElementIndex(Init);
507
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000508 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
509 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000510 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
511 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000512 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000513 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000514 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000515 hadError = true;
516 return;
517 }
518
John McCall60d7b3a2010-08-24 06:29:42 +0000519 ExprResult ElementInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000520 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000521 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000522 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000523 return;
524 }
525
526 if (hadError) {
527 // Do nothing
528 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000529 // For arrays, just set the expression used for value-initialization
530 // of the "holes" in the array.
531 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
532 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
533 else
534 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000535 } else {
536 // For arrays, just set the expression used for value-initialization
537 // of the rest of elements and exit.
538 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
539 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
540 return;
541 }
542
Sebastian Redl7491c492011-06-05 13:59:11 +0000543 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000544 // Value-initialization requires a constructor call, so
545 // extend the initializer list to include the constructor
546 // call and make a note that we'll need to take another pass
547 // through the initializer list.
548 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
549 RequiresSecondPass = true;
550 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000551 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000552 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000553 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000554 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000555 }
556}
557
Chris Lattner68355a52009-01-29 05:10:57 +0000558
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000559InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000560 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000561 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000562 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000563 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000564
Eli Friedmanb85f7072008-05-19 19:16:24 +0000565 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000566 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000567 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000568 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000569 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000570 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000571 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000572
Sebastian Redl14b0c192011-09-24 17:48:00 +0000573 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000574 bool RequiresSecondPass = false;
575 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000576 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000577 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000578 RequiresSecondPass);
579 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000580}
581
582int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000583 // FIXME: use a proper constant
584 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000585 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000586 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000587 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
588 }
589 return maxElements;
590}
591
592int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000593 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000595 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000596 Field = structDecl->field_begin(),
597 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000598 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000599 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000600 ++InitializableMembers;
601 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000602 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000603 return std::min(InitializableMembers, 1);
604 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000605}
606
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000607void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000608 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000609 QualType T, unsigned &Index,
610 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000611 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000612 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Steve Naroff0cca7492008-05-01 22:18:59 +0000614 if (T->isArrayType())
615 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000616 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000617 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000618 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000619 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000620 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000621 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000622
Eli Friedman402256f2008-05-25 13:49:22 +0000623 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000624 if (!VerifyOnly)
625 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
626 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000627 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000628 hadError = true;
629 return;
630 }
631
Douglas Gregor4c678342009-01-28 21:54:33 +0000632 // Build a structured initializer list corresponding to this subobject.
633 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000634 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
635 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000636 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000637 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000639
Douglas Gregor4c678342009-01-28 21:54:33 +0000640 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000641 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000643 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000644 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000645 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000646
647 if (VerifyOnly) {
648 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
649 hadError = true;
650 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000651 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000652
Sebastian Redlc2235182011-10-16 18:19:28 +0000653 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000654 // Update the structured sub-object initializer so that it's ending
655 // range corresponds with the end of the last initializer it used.
656 if (EndIndex < ParentIList->getNumInits()) {
657 SourceLocation EndLoc
658 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
659 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
660 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661
Sebastian Redlc2235182011-10-16 18:19:28 +0000662 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000663 if (T->isArrayType() || T->isRecordType()) {
664 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000665 AllowBraceElision ? diag::warn_missing_braces :
666 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000667 << StructuredSubobjectInitList->getSourceRange()
668 << FixItHint::CreateInsertion(
669 StructuredSubobjectInitList->getLocStart(), "{")
670 << FixItHint::CreateInsertion(
671 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000672 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000673 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000674 if (!AllowBraceElision)
675 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000676 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000677 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000678}
679
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000680void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000681 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000682 unsigned &Index,
683 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000684 unsigned &StructuredIndex,
685 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000686 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000687 if (!VerifyOnly) {
688 SyntacticToSemantic[IList] = StructuredList;
689 StructuredList->setSyntacticForm(IList);
690 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000691 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000692 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000693 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000694 QualType ExprTy = T;
695 if (!ExprTy->isArrayType())
696 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000697 IList->setType(ExprTy);
698 StructuredList->setType(ExprTy);
699 }
Eli Friedman638e1442008-05-25 13:22:35 +0000700 if (hadError)
701 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000702
Eli Friedman638e1442008-05-25 13:22:35 +0000703 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000704 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000705 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000706 if (SemaRef.getLangOpts().CPlusPlus ||
707 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000708 IList->getType()->isVectorType())) {
709 hadError = true;
710 }
711 return;
712 }
713
Eli Friedmane5408582009-05-29 20:20:05 +0000714 if (StructuredIndex == 1 &&
715 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000716 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000717 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000718 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000719 hadError = true;
720 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000721 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000722 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000723 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000724 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000725 // Don't complain for incomplete types, since we'll get an error
726 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000727 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000728 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000729 CurrentObjectType->isArrayType()? 0 :
730 CurrentObjectType->isVectorType()? 1 :
731 CurrentObjectType->isScalarType()? 2 :
732 CurrentObjectType->isUnionType()? 3 :
733 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000734
735 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000736 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000737 DK = diag::err_excess_initializers;
738 hadError = true;
739 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000740 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000741 DK = diag::err_excess_initializers;
742 hadError = true;
743 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000744
Chris Lattner08202542009-02-24 22:50:46 +0000745 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000746 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000747 }
748 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000749
Sebastian Redl14b0c192011-09-24 17:48:00 +0000750 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
751 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000752 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000753 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000754 << FixItHint::CreateRemoval(IList->getLocStart())
755 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000756}
757
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000758void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000759 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000760 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000761 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000762 unsigned &Index,
763 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000764 unsigned &StructuredIndex,
765 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000766 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
767 // Explicitly braced initializer for complex type can be real+imaginary
768 // parts.
769 CheckComplexType(Entity, IList, DeclType, Index,
770 StructuredList, StructuredIndex);
771 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000772 CheckScalarType(Entity, IList, DeclType, Index,
773 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000774 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000775 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000776 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000777 } else if (DeclType->isRecordType()) {
778 assert(DeclType->isAggregateType() &&
779 "non-aggregate records should be handed in CheckSubElementType");
780 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
781 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
782 SubobjectIsDesignatorContext, Index,
783 StructuredList, StructuredIndex,
784 TopLevelObject);
785 } else if (DeclType->isArrayType()) {
786 llvm::APSInt Zero(
787 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
788 false);
789 CheckArrayType(Entity, IList, DeclType, Zero,
790 SubobjectIsDesignatorContext, Index,
791 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000792 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
793 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000794 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000795 if (!VerifyOnly)
796 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
797 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000798 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000799 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000800 CheckReferenceType(Entity, IList, DeclType, Index,
801 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000802 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000803 if (!VerifyOnly)
804 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
805 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000806 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000807 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000808 if (!VerifyOnly)
809 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
810 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000811 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000812 }
813}
814
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000815void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000816 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000817 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000818 unsigned &Index,
819 InitListExpr *StructuredList,
820 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000821 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000822 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000823 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
824 unsigned newIndex = 0;
825 unsigned newStructuredIndex = 0;
826 InitListExpr *newStructuredList
827 = getStructuredSubobjectInit(IList, Index, ElemType,
828 StructuredList, StructuredIndex,
829 SubInitList->getSourceRange());
830 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
831 newStructuredList, newStructuredIndex);
832 ++StructuredIndex;
833 ++Index;
834 return;
835 }
836 assert(SemaRef.getLangOpts().CPlusPlus &&
837 "non-aggregate records are only possible in C++");
838 // C++ initialization is handled later.
839 }
840
841 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000842 return CheckScalarType(Entity, IList, ElemType, Index,
843 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000844 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000845 return CheckReferenceType(Entity, IList, ElemType, Index,
846 StructuredList, StructuredIndex);
847 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000848
John McCallfef8b342011-02-21 07:57:55 +0000849 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
850 // arrayType can be incomplete if we're initializing a flexible
851 // array member. There's nothing we can do with the completed
852 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000853
Hans Wennborg0ff50742013-05-15 11:03:04 +0000854 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000855 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000856 CheckStringInit(expr, ElemType, arrayType, SemaRef);
857 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000858 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000859 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000860 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000861 }
John McCallfef8b342011-02-21 07:57:55 +0000862
863 // Fall through for subaggregate initialization.
864
David Blaikie4e4d0842012-03-11 07:00:24 +0000865 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000866 // C++ [dcl.init.aggr]p12:
867 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000868 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000869 // an initializer-list. If the initializer can initialize a
870 // member, the member is initialized. [...]
871
872 // FIXME: Better EqualLoc?
873 InitializationKind Kind =
874 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000875 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000876
877 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000878 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000879 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000880 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000881 if (Result.isInvalid())
882 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000883
Sebastian Redl14b0c192011-09-24 17:48:00 +0000884 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000885 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000886 }
John McCallfef8b342011-02-21 07:57:55 +0000887 ++Index;
888 return;
889 }
890
891 // Fall through for subaggregate initialization
892 } else {
893 // C99 6.7.8p13:
894 //
895 // The initializer for a structure or union object that has
896 // automatic storage duration shall be either an initializer
897 // list as described below, or a single expression that has
898 // compatible structure or union type. In the latter case, the
899 // initial value of the object, including unnamed members, is
900 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000901 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000902 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000903 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
904 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000905 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000906 if (ExprRes.isInvalid())
907 hadError = true;
908 else {
909 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000910 if (ExprRes.isInvalid())
911 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000912 }
913 UpdateStructuredListElement(StructuredList, StructuredIndex,
914 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000915 ++Index;
916 return;
917 }
John Wiegley429bb272011-04-08 18:41:53 +0000918 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000919 // Fall through for subaggregate initialization
920 }
921
922 // C++ [dcl.init.aggr]p12:
923 //
924 // [...] Otherwise, if the member is itself a non-empty
925 // subaggregate, brace elision is assumed and the initializer is
926 // considered for the initialization of the first member of
927 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000928 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000929 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000930 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
931 StructuredIndex);
932 ++StructuredIndex;
933 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000934 if (!VerifyOnly) {
935 // We cannot initialize this element, so let
936 // PerformCopyInitialization produce the appropriate diagnostic.
937 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
938 SemaRef.Owned(expr),
939 /*TopLevelOfInitList=*/true);
940 }
John McCallfef8b342011-02-21 07:57:55 +0000941 hadError = true;
942 ++Index;
943 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000944 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000945}
946
Eli Friedman0c706c22011-09-19 23:17:44 +0000947void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
948 InitListExpr *IList, QualType DeclType,
949 unsigned &Index,
950 InitListExpr *StructuredList,
951 unsigned &StructuredIndex) {
952 assert(Index == 0 && "Index in explicit init list must be zero");
953
954 // As an extension, clang supports complex initializers, which initialize
955 // a complex number component-wise. When an explicit initializer list for
956 // a complex number contains two two initializers, this extension kicks in:
957 // it exepcts the initializer list to contain two elements convertible to
958 // the element type of the complex type. The first element initializes
959 // the real part, and the second element intitializes the imaginary part.
960
961 if (IList->getNumInits() != 2)
962 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
963 StructuredIndex);
964
965 // This is an extension in C. (The builtin _Complex type does not exist
966 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000967 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000968 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
969 << IList->getSourceRange();
970
971 // Initialize the complex number.
972 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
973 InitializedEntity ElementEntity =
974 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
975
976 for (unsigned i = 0; i < 2; ++i) {
977 ElementEntity.setElementIndex(Index);
978 CheckSubElementType(ElementEntity, IList, elementType, Index,
979 StructuredList, StructuredIndex);
980 }
981}
982
983
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000984void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000985 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000986 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000987 InitListExpr *StructuredList,
988 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000989 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000990 if (!VerifyOnly)
991 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000992 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000993 diag::warn_cxx98_compat_empty_scalar_initializer :
994 diag::err_empty_scalar_initializer)
995 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000996 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000997 ++Index;
998 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000999 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001000 }
John McCallb934c2d2010-11-11 00:46:36 +00001001
1002 Expr *expr = IList->getInit(Index);
1003 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001004 if (!VerifyOnly)
1005 SemaRef.Diag(SubIList->getLocStart(),
1006 diag::warn_many_braces_around_scalar_init)
1007 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001008
1009 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1010 StructuredIndex);
1011 return;
1012 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001013 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001014 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001015 diag::err_designator_for_scalar_init)
1016 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001017 hadError = true;
1018 ++Index;
1019 ++StructuredIndex;
1020 return;
1021 }
1022
Sebastian Redl14b0c192011-09-24 17:48:00 +00001023 if (VerifyOnly) {
1024 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1025 hadError = true;
1026 ++Index;
1027 return;
1028 }
1029
John McCallb934c2d2010-11-11 00:46:36 +00001030 ExprResult Result =
1031 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001032 SemaRef.Owned(expr),
1033 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001034
1035 Expr *ResultExpr = 0;
1036
1037 if (Result.isInvalid())
1038 hadError = true; // types weren't compatible.
1039 else {
1040 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001041
John McCallb934c2d2010-11-11 00:46:36 +00001042 if (ResultExpr != expr) {
1043 // The type was promoted, update initializer list.
1044 IList->setInit(Index, ResultExpr);
1045 }
1046 }
1047 if (hadError)
1048 ++StructuredIndex;
1049 else
1050 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1051 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001052}
1053
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001054void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1055 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001056 unsigned &Index,
1057 InitListExpr *StructuredList,
1058 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001059 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001060 // FIXME: It would be wonderful if we could point at the actual member. In
1061 // general, it would be useful to pass location information down the stack,
1062 // so that we know the location (or decl) of the "current object" being
1063 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001064 if (!VerifyOnly)
1065 SemaRef.Diag(IList->getLocStart(),
1066 diag::err_init_reference_member_uninitialized)
1067 << DeclType
1068 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001069 hadError = true;
1070 ++Index;
1071 ++StructuredIndex;
1072 return;
1073 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001074
1075 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001076 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001077 if (!VerifyOnly)
1078 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1079 << DeclType << IList->getSourceRange();
1080 hadError = true;
1081 ++Index;
1082 ++StructuredIndex;
1083 return;
1084 }
1085
1086 if (VerifyOnly) {
1087 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1088 hadError = true;
1089 ++Index;
1090 return;
1091 }
1092
1093 ExprResult Result =
1094 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1095 SemaRef.Owned(expr),
1096 /*TopLevelOfInitList=*/true);
1097
1098 if (Result.isInvalid())
1099 hadError = true;
1100
1101 expr = Result.takeAs<Expr>();
1102 IList->setInit(Index, expr);
1103
1104 if (hadError)
1105 ++StructuredIndex;
1106 else
1107 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1108 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001109}
1110
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001111void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001112 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001113 unsigned &Index,
1114 InitListExpr *StructuredList,
1115 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001116 const VectorType *VT = DeclType->getAs<VectorType>();
1117 unsigned maxElements = VT->getNumElements();
1118 unsigned numEltsInit = 0;
1119 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001120
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001121 if (Index >= IList->getNumInits()) {
1122 // Make sure the element type can be value-initialized.
1123 if (VerifyOnly)
1124 CheckValueInitializable(
1125 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1126 return;
1127 }
1128
David Blaikie4e4d0842012-03-11 07:00:24 +00001129 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001130 // If the initializing element is a vector, try to copy-initialize
1131 // instead of breaking it apart (which is doomed to failure anyway).
1132 Expr *Init = IList->getInit(Index);
1133 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001134 if (VerifyOnly) {
1135 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1136 hadError = true;
1137 ++Index;
1138 return;
1139 }
1140
John McCall20e047a2010-10-30 00:11:39 +00001141 ExprResult Result =
1142 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001143 SemaRef.Owned(Init),
1144 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001145
1146 Expr *ResultExpr = 0;
1147 if (Result.isInvalid())
1148 hadError = true; // types weren't compatible.
1149 else {
1150 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001151
John McCall20e047a2010-10-30 00:11:39 +00001152 if (ResultExpr != Init) {
1153 // The type was promoted, update initializer list.
1154 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001155 }
1156 }
John McCall20e047a2010-10-30 00:11:39 +00001157 if (hadError)
1158 ++StructuredIndex;
1159 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001160 UpdateStructuredListElement(StructuredList, StructuredIndex,
1161 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001162 ++Index;
1163 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
John McCall20e047a2010-10-30 00:11:39 +00001166 InitializedEntity ElementEntity =
1167 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001168
John McCall20e047a2010-10-30 00:11:39 +00001169 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1170 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001171 if (Index >= IList->getNumInits()) {
1172 if (VerifyOnly)
1173 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001174 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001175 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001176
John McCall20e047a2010-10-30 00:11:39 +00001177 ElementEntity.setElementIndex(Index);
1178 CheckSubElementType(ElementEntity, IList, elementType, Index,
1179 StructuredList, StructuredIndex);
1180 }
1181 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001182 }
John McCall20e047a2010-10-30 00:11:39 +00001183
1184 InitializedEntity ElementEntity =
1185 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001186
John McCall20e047a2010-10-30 00:11:39 +00001187 // OpenCL initializers allows vectors to be constructed from vectors.
1188 for (unsigned i = 0; i < maxElements; ++i) {
1189 // Don't attempt to go past the end of the init list
1190 if (Index >= IList->getNumInits())
1191 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001192
John McCall20e047a2010-10-30 00:11:39 +00001193 ElementEntity.setElementIndex(Index);
1194
1195 QualType IType = IList->getInit(Index)->getType();
1196 if (!IType->isVectorType()) {
1197 CheckSubElementType(ElementEntity, IList, elementType, Index,
1198 StructuredList, StructuredIndex);
1199 ++numEltsInit;
1200 } else {
1201 QualType VecType;
1202 const VectorType *IVT = IType->getAs<VectorType>();
1203 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001204
John McCall20e047a2010-10-30 00:11:39 +00001205 if (IType->isExtVectorType())
1206 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1207 else
1208 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001209 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001210 CheckSubElementType(ElementEntity, IList, VecType, Index,
1211 StructuredList, StructuredIndex);
1212 numEltsInit += numIElts;
1213 }
1214 }
1215
1216 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001217 if (numEltsInit != maxElements) {
1218 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001219 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001220 diag::err_vector_incorrect_num_initializers)
1221 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1222 hadError = true;
1223 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001224}
1225
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001226void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001227 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001228 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001229 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001230 unsigned &Index,
1231 InitListExpr *StructuredList,
1232 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001233 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1234
Steve Naroff0cca7492008-05-01 22:18:59 +00001235 // Check for the special-case of initializing an array with a string.
1236 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001237 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1238 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001239 // We place the string literal directly into the resulting
1240 // initializer list. This is the only place where the structure
1241 // of the structured initializer list doesn't match exactly,
1242 // because doing so would involve allocating one character
1243 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001244 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001245 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1246 UpdateStructuredListElement(StructuredList, StructuredIndex,
1247 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001248 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1249 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001250 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001251 return;
1252 }
1253 }
John McCallce6c9b72011-02-21 07:22:22 +00001254 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001255 // Check for VLAs; in standard C it would be possible to check this
1256 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1257 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001258 if (!VerifyOnly)
1259 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1260 diag::err_variable_object_no_init)
1261 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001262 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001263 ++Index;
1264 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001265 return;
1266 }
1267
Douglas Gregor05c13a32009-01-22 00:58:24 +00001268 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001269 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1270 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001272 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001273 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001274 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001275 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001276 maxElementsKnown = true;
1277 }
1278
John McCallce6c9b72011-02-21 07:22:22 +00001279 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001280 while (Index < IList->getNumInits()) {
1281 Expr *Init = IList->getInit(Index);
1282 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001283 // If we're not the subobject that matches up with the '{' for
1284 // the designator, we shouldn't be handling the
1285 // designator. Return immediately.
1286 if (!SubobjectIsDesignatorContext)
1287 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001288
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001289 // Handle this designated initializer. elementIndex will be
1290 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001291 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001292 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001293 StructuredList, StructuredIndex, true,
1294 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001295 hadError = true;
1296 continue;
1297 }
1298
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001299 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001300 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001301 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001302 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001303 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001304
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001305 // If the array is of incomplete type, keep track of the number of
1306 // elements in the initializer.
1307 if (!maxElementsKnown && elementIndex > maxElements)
1308 maxElements = elementIndex;
1309
Douglas Gregor05c13a32009-01-22 00:58:24 +00001310 continue;
1311 }
1312
1313 // If we know the maximum number of elements, and we've already
1314 // hit it, stop consuming elements in the initializer list.
1315 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001316 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001317
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001318 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001319 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001320 Entity);
1321 // Check this element.
1322 CheckSubElementType(ElementEntity, IList, elementType, Index,
1323 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001324 ++elementIndex;
1325
1326 // If the array is of incomplete type, keep track of the number of
1327 // elements in the initializer.
1328 if (!maxElementsKnown && elementIndex > maxElements)
1329 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001330 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001331 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001332 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001333 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001334 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001335 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001336 // Sizing an array implicitly to zero is not allowed by ISO C,
1337 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001338 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001339 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001340 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001341
Mike Stump1eb44332009-09-09 15:08:12 +00001342 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001343 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001344 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001345 if (!hadError && VerifyOnly) {
1346 // Check if there are any members of the array that get value-initialized.
1347 // If so, check if doing that is possible.
1348 // FIXME: This needs to detect holes left by designated initializers too.
1349 if (maxElementsKnown && elementIndex < maxElements)
1350 CheckValueInitializable(InitializedEntity::InitializeElement(
1351 SemaRef.Context, 0, Entity));
1352 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001353}
1354
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001355bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1356 Expr *InitExpr,
1357 FieldDecl *Field,
1358 bool TopLevelObject) {
1359 // Handle GNU flexible array initializers.
1360 unsigned FlexArrayDiag;
1361 if (isa<InitListExpr>(InitExpr) &&
1362 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1363 // Empty flexible array init always allowed as an extension
1364 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001365 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001366 // Disallow flexible array init in C++; it is not required for gcc
1367 // compatibility, and it needs work to IRGen correctly in general.
1368 FlexArrayDiag = diag::err_flexible_array_init;
1369 } else if (!TopLevelObject) {
1370 // Disallow flexible array init on non-top-level object
1371 FlexArrayDiag = diag::err_flexible_array_init;
1372 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1373 // Disallow flexible array init on anything which is not a variable.
1374 FlexArrayDiag = diag::err_flexible_array_init;
1375 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1376 // Disallow flexible array init on local variables.
1377 FlexArrayDiag = diag::err_flexible_array_init;
1378 } else {
1379 // Allow other cases.
1380 FlexArrayDiag = diag::ext_flexible_array_init;
1381 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001382
1383 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001384 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001385 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001386 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001387 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1388 << Field;
1389 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001390
1391 return FlexArrayDiag != diag::ext_flexible_array_init;
1392}
1393
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001394void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001395 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001396 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001397 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001398 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001399 unsigned &Index,
1400 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001401 unsigned &StructuredIndex,
1402 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001403 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Eli Friedmanb85f7072008-05-19 19:16:24 +00001405 // If the record is invalid, some of it's members are invalid. To avoid
1406 // confusion, we forgo checking the intializer for the entire record.
1407 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001408 // Assume it was supposed to consume a single initializer.
1409 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001410 hadError = true;
1411 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001412 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001413
1414 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001415 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001416
1417 // If there's a default initializer, use it.
1418 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1419 if (VerifyOnly)
1420 return;
1421 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1422 Field != FieldEnd; ++Field) {
1423 if (Field->hasInClassInitializer()) {
1424 StructuredList->setInitializedFieldInUnion(*Field);
1425 // FIXME: Actually build a CXXDefaultInitExpr?
1426 return;
1427 }
1428 }
1429 }
1430
1431 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001432 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1433 Field != FieldEnd; ++Field) {
1434 if (Field->getDeclName()) {
1435 if (VerifyOnly)
1436 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001437 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001438 else
David Blaikie581deb32012-06-06 20:45:41 +00001439 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001440 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001441 }
1442 }
1443 return;
1444 }
1445
Douglas Gregor05c13a32009-01-22 00:58:24 +00001446 // If structDecl is a forward declaration, this loop won't do
1447 // anything except look at designated initializers; That's okay,
1448 // because an error should get printed out elsewhere. It might be
1449 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001450 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001451 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001452 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001453 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001454 while (Index < IList->getNumInits()) {
1455 Expr *Init = IList->getInit(Index);
1456
1457 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001458 // If we're not the subobject that matches up with the '{' for
1459 // the designator, we shouldn't be handling the
1460 // designator. Return immediately.
1461 if (!SubobjectIsDesignatorContext)
1462 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001463
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001464 // Handle this designated initializer. Field will be updated to
1465 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001466 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001467 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001468 StructuredList, StructuredIndex,
1469 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001470 hadError = true;
1471
Douglas Gregordfb5e592009-02-12 19:00:39 +00001472 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001473
1474 // Disable check for missing fields when designators are used.
1475 // This matches gcc behaviour.
1476 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001477 continue;
1478 }
1479
1480 if (Field == FieldEnd) {
1481 // We've run out of fields. We're done.
1482 break;
1483 }
1484
Douglas Gregordfb5e592009-02-12 19:00:39 +00001485 // We've already initialized a member of a union. We're done.
1486 if (InitializedSomething && DeclType->isUnionType())
1487 break;
1488
Douglas Gregor44b43212008-12-11 16:49:14 +00001489 // If we've hit the flexible array member at the end, we're done.
1490 if (Field->getType()->isIncompleteArrayType())
1491 break;
1492
Douglas Gregor0bb76892009-01-29 16:53:55 +00001493 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001494 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001495 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001496 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001497 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001498
Douglas Gregor54001c12011-06-29 21:51:31 +00001499 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001500 bool InvalidUse;
1501 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001502 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001503 else
David Blaikie581deb32012-06-06 20:45:41 +00001504 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001505 IList->getInit(Index)->getLocStart());
1506 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001507 ++Index;
1508 ++Field;
1509 hadError = true;
1510 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001511 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001512
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001513 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001514 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001515 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1516 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001517 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001518
Sebastian Redl14b0c192011-09-24 17:48:00 +00001519 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001520 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001521 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001522 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001523
1524 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001525 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001526
John McCall80639de2010-03-11 19:32:38 +00001527 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001528 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1529 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1530 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001531 // It is possible we have one or more unnamed bitfields remaining.
1532 // Find first (if any) named field and emit warning.
1533 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1534 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001535 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001536 SemaRef.Diag(IList->getSourceRange().getEnd(),
1537 diag::warn_missing_field_initializers) << it->getName();
1538 break;
1539 }
1540 }
1541 }
1542
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001543 // Check that any remaining fields can be value-initialized.
1544 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1545 !Field->getType()->isIncompleteArrayType()) {
1546 // FIXME: Should check for holes left by designated initializers too.
1547 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001548 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001549 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001550 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001551 }
1552 }
1553
Mike Stump1eb44332009-09-09 15:08:12 +00001554 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001555 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001556 return;
1557
David Blaikie581deb32012-06-06 20:45:41 +00001558 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001559 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001560 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001561 ++Index;
1562 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001563 }
1564
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001565 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001566 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001567
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001568 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001569 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001570 StructuredList, StructuredIndex);
1571 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001572 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001573 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001574}
Steve Naroff0cca7492008-05-01 22:18:59 +00001575
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001576/// \brief Expand a field designator that refers to a member of an
1577/// anonymous struct or union into a series of field designators that
1578/// refers to the field within the appropriate subobject.
1579///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001580static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001581 DesignatedInitExpr *DIE,
1582 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001583 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001584 typedef DesignatedInitExpr::Designator Designator;
1585
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001586 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001587 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001588 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1589 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1590 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001591 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001592 DIE->getDesignator(DesigIdx)->getDotLoc(),
1593 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1594 else
1595 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1596 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001597 assert(isa<FieldDecl>(*PI));
1598 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001599 }
1600
1601 // Expand the current designator into the set of replacement
1602 // designators, so we have a full subobject path down to where the
1603 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001604 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001605 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001606}
Mike Stump1eb44332009-09-09 15:08:12 +00001607
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001608/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001609/// corresponds to FieldName.
1610static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1611 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001612 if (!FieldName)
1613 return 0;
1614
Francois Picheta0e27f02010-12-22 03:46:10 +00001615 assert(AnonField->isAnonymousStructOrUnion());
1616 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001617 while (IndirectFieldDecl *IF =
1618 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001619 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001620 return IF;
1621 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001622 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001623 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001624}
1625
Sebastian Redl14b0c192011-09-24 17:48:00 +00001626static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1627 DesignatedInitExpr *DIE) {
1628 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1629 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1630 for (unsigned I = 0; I < NumIndexExprs; ++I)
1631 IndexExprs[I] = DIE->getSubExpr(I + 1);
1632 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001633 DIE->size(), IndexExprs,
1634 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001635 DIE->usesGNUSyntax(), DIE->getInit());
1636}
1637
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001638namespace {
1639
1640// Callback to only accept typo corrections that are for field members of
1641// the given struct or union.
1642class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1643 public:
1644 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1645 : Record(RD) {}
1646
1647 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1648 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1649 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1650 }
1651
1652 private:
1653 RecordDecl *Record;
1654};
1655
1656}
1657
Douglas Gregor05c13a32009-01-22 00:58:24 +00001658/// @brief Check the well-formedness of a C99 designated initializer.
1659///
1660/// Determines whether the designated initializer @p DIE, which
1661/// resides at the given @p Index within the initializer list @p
1662/// IList, is well-formed for a current object of type @p DeclType
1663/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001664/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001665/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001666///
1667/// @param IList The initializer list in which this designated
1668/// initializer occurs.
1669///
Douglas Gregor71199712009-04-15 04:56:10 +00001670/// @param DIE The designated initializer expression.
1671///
1672/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001673///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001674/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001675/// into which the designation in @p DIE should refer.
1676///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001677/// @param NextField If non-NULL and the first designator in @p DIE is
1678/// a field, this will be set to the field declaration corresponding
1679/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001680///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001681/// @param NextElementIndex If non-NULL and the first designator in @p
1682/// DIE is an array designator or GNU array-range designator, this
1683/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001684///
1685/// @param Index Index into @p IList where the designated initializer
1686/// @p DIE occurs.
1687///
Douglas Gregor4c678342009-01-28 21:54:33 +00001688/// @param StructuredList The initializer list expression that
1689/// describes all of the subobject initializers in the order they'll
1690/// actually be initialized.
1691///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001692/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001693bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001694InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001695 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001696 DesignatedInitExpr *DIE,
1697 unsigned DesigIdx,
1698 QualType &CurrentObjectType,
1699 RecordDecl::field_iterator *NextField,
1700 llvm::APSInt *NextElementIndex,
1701 unsigned &Index,
1702 InitListExpr *StructuredList,
1703 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001704 bool FinishSubobjectInit,
1705 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001706 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001707 // Check the actual initialization for the designated object type.
1708 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001709
1710 // Temporarily remove the designator expression from the
1711 // initializer list that the child calls see, so that we don't try
1712 // to re-process the designator.
1713 unsigned OldIndex = Index;
1714 IList->setInit(OldIndex, DIE->getInit());
1715
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001716 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001717 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001718
1719 // Restore the designated initializer expression in the syntactic
1720 // form of the initializer list.
1721 if (IList->getInit(OldIndex) != DIE->getInit())
1722 DIE->setInit(IList->getInit(OldIndex));
1723 IList->setInit(OldIndex, DIE);
1724
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001725 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001726 }
1727
Douglas Gregor71199712009-04-15 04:56:10 +00001728 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001729 bool IsFirstDesignator = (DesigIdx == 0);
1730 if (!VerifyOnly) {
1731 assert((IsFirstDesignator || StructuredList) &&
1732 "Need a non-designated initializer list to start from");
1733
1734 // Determine the structural initializer list that corresponds to the
1735 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001736 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001737 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1738 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001739 SourceRange(D->getLocStart(),
1740 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001741 assert(StructuredList && "Expected a structured initializer list");
1742 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001743
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001744 if (D->isFieldDesignator()) {
1745 // C99 6.7.8p7:
1746 //
1747 // If a designator has the form
1748 //
1749 // . identifier
1750 //
1751 // then the current object (defined below) shall have
1752 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001753 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001754 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001755 if (!RT) {
1756 SourceLocation Loc = D->getDotLoc();
1757 if (Loc.isInvalid())
1758 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001759 if (!VerifyOnly)
1760 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001761 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001762 ++Index;
1763 return true;
1764 }
1765
Douglas Gregor4c678342009-01-28 21:54:33 +00001766 // Note: we perform a linear search of the fields here, despite
1767 // the fact that we have a faster lookup method, because we always
1768 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001769 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001770 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001771 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001772 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001773 Field = RT->getDecl()->field_begin(),
1774 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001775 for (; Field != FieldEnd; ++Field) {
1776 if (Field->isUnnamedBitfield())
1777 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001778
Francois Picheta0e27f02010-12-22 03:46:10 +00001779 // If we find a field representing an anonymous field, look in the
1780 // IndirectFieldDecl that follow for the designated initializer.
1781 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1782 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001783 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001784 // In verify mode, don't modify the original.
1785 if (VerifyOnly)
1786 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001787 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1788 D = DIE->getDesignator(DesigIdx);
1789 break;
1790 }
1791 }
David Blaikie581deb32012-06-06 20:45:41 +00001792 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001793 break;
1794 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001795 break;
1796
1797 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001798 }
1799
Douglas Gregor4c678342009-01-28 21:54:33 +00001800 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001801 if (VerifyOnly) {
1802 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001803 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001804 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001805
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001806 // There was no normal field in the struct with the designated
1807 // name. Perform another lookup for this name, which may find
1808 // something that we can't designate (e.g., a member function),
1809 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001810 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001811 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001812 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001813 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001814 // Name lookup didn't find anything. Determine whether this
1815 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001816 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001817 TypoCorrection Corrected = SemaRef.CorrectTypo(
1818 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001819 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001820 RT->getDecl());
1821 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001822 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001823 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001824 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001825 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001826 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001827 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001828 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001829 << FieldName << CurrentObjectType << CorrectedQuotedStr
1830 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001831 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001832 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001833 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001834 } else {
1835 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1836 << FieldName << CurrentObjectType;
1837 ++Index;
1838 return true;
1839 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001840 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001841
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001842 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001843 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001844 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001845 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001846 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001847 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001848 ++Index;
1849 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001850 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001851
Francois Picheta0e27f02010-12-22 03:46:10 +00001852 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001853 // The replacement field comes from typo correction; find it
1854 // in the list of fields.
1855 FieldIndex = 0;
1856 Field = RT->getDecl()->field_begin();
1857 for (; Field != FieldEnd; ++Field) {
1858 if (Field->isUnnamedBitfield())
1859 continue;
1860
David Blaikie581deb32012-06-06 20:45:41 +00001861 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001862 Field->getIdentifier() == ReplacementField->getIdentifier())
1863 break;
1864
1865 ++FieldIndex;
1866 }
1867 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001868 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001869
1870 // All of the fields of a union are located at the same place in
1871 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001872 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001873 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001874 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001875 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001876 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001877
Douglas Gregor54001c12011-06-29 21:51:31 +00001878 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001879 bool InvalidUse;
1880 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001881 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001882 else
David Blaikie581deb32012-06-06 20:45:41 +00001883 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001884 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001885 ++Index;
1886 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001887 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001888
Sebastian Redl14b0c192011-09-24 17:48:00 +00001889 if (!VerifyOnly) {
1890 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001891 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Sebastian Redl14b0c192011-09-24 17:48:00 +00001893 // Make sure that our non-designated initializer list has space
1894 // for a subobject corresponding to this field.
1895 if (FieldIndex >= StructuredList->getNumInits())
1896 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1897 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001898
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001899 // This designator names a flexible array member.
1900 if (Field->getType()->isIncompleteArrayType()) {
1901 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001902 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001903 // We can't designate an object within the flexible array
1904 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001905 if (!VerifyOnly) {
1906 DesignatedInitExpr::Designator *NextD
1907 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001908 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001909 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001910 << SourceRange(NextD->getLocStart(),
1911 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001912 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001913 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001914 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001915 Invalid = true;
1916 }
1917
Chris Lattner9046c222010-10-10 17:49:49 +00001918 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1919 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001920 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001921 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001922 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001923 diag::err_flexible_array_init_needs_braces)
1924 << DIE->getInit()->getSourceRange();
1925 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001926 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001927 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001928 Invalid = true;
1929 }
1930
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001931 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001932 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001933 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001934 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001935
1936 if (Invalid) {
1937 ++Index;
1938 return true;
1939 }
1940
1941 // Initialize the array.
1942 bool prevHadError = hadError;
1943 unsigned newStructuredIndex = FieldIndex;
1944 unsigned OldIndex = Index;
1945 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001946
1947 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001948 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001949 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001950 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001951
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001952 IList->setInit(OldIndex, DIE);
1953 if (hadError && !prevHadError) {
1954 ++Field;
1955 ++FieldIndex;
1956 if (NextField)
1957 *NextField = Field;
1958 StructuredIndex = FieldIndex;
1959 return true;
1960 }
1961 } else {
1962 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001963 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001964 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001965
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001966 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001967 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001968 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1969 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001970 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001971 true, false))
1972 return true;
1973 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001974
1975 // Find the position of the next field to be initialized in this
1976 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001977 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001978 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001979
1980 // If this the first designator, our caller will continue checking
1981 // the rest of this struct/class/union subobject.
1982 if (IsFirstDesignator) {
1983 if (NextField)
1984 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001985 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001986 return false;
1987 }
1988
Douglas Gregor34e79462009-01-28 23:36:17 +00001989 if (!FinishSubobjectInit)
1990 return false;
1991
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001992 // We've already initialized something in the union; we're done.
1993 if (RT->getDecl()->isUnion())
1994 return hadError;
1995
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001996 // Check the remaining fields within this class/struct/union subobject.
1997 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001998
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001999 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002000 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002001 return hadError && !prevHadError;
2002 }
2003
2004 // C99 6.7.8p6:
2005 //
2006 // If a designator has the form
2007 //
2008 // [ constant-expression ]
2009 //
2010 // then the current object (defined below) shall have array
2011 // type and the expression shall be an integer constant
2012 // expression. If the array is of unknown size, any
2013 // nonnegative value is valid.
2014 //
2015 // Additionally, cope with the GNU extension that permits
2016 // designators of the form
2017 //
2018 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002019 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002020 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002021 if (!VerifyOnly)
2022 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2023 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002024 ++Index;
2025 return true;
2026 }
2027
2028 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00002029 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2030 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002031 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002032 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002033 DesignatedEndIndex = DesignatedStartIndex;
2034 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002035 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002036
Mike Stump1eb44332009-09-09 15:08:12 +00002037 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002038 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002039 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002040 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002041 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002042
Chris Lattnere0fd8322011-02-19 22:28:58 +00002043 // Codegen can't handle evaluating array range designators that have side
2044 // effects, because we replicate the AST value for each initialized element.
2045 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2046 // elements with something that has a side effect, so codegen can emit an
2047 // "error unsupported" error instead of miscompiling the app.
2048 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002049 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002050 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002051 }
2052
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002053 if (isa<ConstantArrayType>(AT)) {
2054 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002055 DesignatedStartIndex
2056 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002057 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002058 DesignatedEndIndex
2059 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002060 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2061 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002062 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002063 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002064 diag::err_array_designator_too_large)
2065 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2066 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002067 ++Index;
2068 return true;
2069 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002070 } else {
2071 // Make sure the bit-widths and signedness match.
2072 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002073 DesignatedEndIndex
2074 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002075 else if (DesignatedStartIndex.getBitWidth() <
2076 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002077 DesignatedStartIndex
2078 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002079 DesignatedStartIndex.setIsUnsigned(true);
2080 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002081 }
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Douglas Gregor4c678342009-01-28 21:54:33 +00002083 // Make sure that our non-designated initializer list has space
2084 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002085 if (!VerifyOnly &&
2086 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002087 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002088 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002089
Douglas Gregor34e79462009-01-28 23:36:17 +00002090 // Repeatedly perform subobject initializations in the range
2091 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002092
Douglas Gregor34e79462009-01-28 23:36:17 +00002093 // Move to the next designator
2094 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2095 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002096
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002097 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002098 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002099
Douglas Gregor34e79462009-01-28 23:36:17 +00002100 while (DesignatedStartIndex <= DesignatedEndIndex) {
2101 // Recurse to check later designated subobjects.
2102 QualType ElementType = AT->getElementType();
2103 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002104
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002105 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002106 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2107 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002108 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002109 (DesignatedStartIndex == DesignatedEndIndex),
2110 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002111 return true;
2112
2113 // Move to the next index in the array that we'll be initializing.
2114 ++DesignatedStartIndex;
2115 ElementIndex = DesignatedStartIndex.getZExtValue();
2116 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002117
2118 // If this the first designator, our caller will continue checking
2119 // the rest of this array subobject.
2120 if (IsFirstDesignator) {
2121 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002122 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002123 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002124 return false;
2125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregor34e79462009-01-28 23:36:17 +00002127 if (!FinishSubobjectInit)
2128 return false;
2129
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002130 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002131 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002132 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002133 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002134 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002135 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002136}
2137
Douglas Gregor4c678342009-01-28 21:54:33 +00002138// Get the structured initializer list for a subobject of type
2139// @p CurrentObjectType.
2140InitListExpr *
2141InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2142 QualType CurrentObjectType,
2143 InitListExpr *StructuredList,
2144 unsigned StructuredIndex,
2145 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002146 if (VerifyOnly)
2147 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002148 Expr *ExistingInit = 0;
2149 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002150 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002151 else if (StructuredIndex < StructuredList->getNumInits())
2152 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Douglas Gregor4c678342009-01-28 21:54:33 +00002154 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2155 return Result;
2156
2157 if (ExistingInit) {
2158 // We are creating an initializer list that initializes the
2159 // subobjects of the current object, but there was already an
2160 // initialization that completely initialized the current
2161 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002162 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002163 // struct X { int a, b; };
2164 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002165 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002166 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2167 // designated initializer re-initializes the whole
2168 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002169 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002170 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002171 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002172 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002173 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002174 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002175 << ExistingInit->getSourceRange();
2176 }
2177
Mike Stump1eb44332009-09-09 15:08:12 +00002178 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002179 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002180 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002181 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002182
Eli Friedman5c89c392012-02-23 02:25:10 +00002183 QualType ResultType = CurrentObjectType;
2184 if (!ResultType->isArrayType())
2185 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2186 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002187
Douglas Gregorfa219202009-03-20 23:58:33 +00002188 // Pre-allocate storage for the structured initializer list.
2189 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002190 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002191 bool GotNumInits = false;
2192 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002193 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002194 GotNumInits = true;
2195 } else if (Index < IList->getNumInits()) {
2196 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002197 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002198 GotNumInits = true;
2199 }
Douglas Gregor08457732009-03-21 18:13:52 +00002200 }
2201
Mike Stump1eb44332009-09-09 15:08:12 +00002202 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002203 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2204 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2205 NumElements = CAType->getSize().getZExtValue();
2206 // Simple heuristic so that we don't allocate a very large
2207 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002208 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002209 NumElements = 0;
2210 }
John McCall183700f2009-09-21 23:43:11 +00002211 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002212 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002213 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002214 RecordDecl *RDecl = RType->getDecl();
2215 if (RDecl->isUnion())
2216 NumElements = 1;
2217 else
Mike Stump1eb44332009-09-09 15:08:12 +00002218 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002219 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002220 }
2221
Ted Kremenek709210f2010-04-13 23:39:13 +00002222 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002223
Douglas Gregor4c678342009-01-28 21:54:33 +00002224 // Link this new initializer list into the structured initializer
2225 // lists.
2226 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002227 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002228 else {
2229 Result->setSyntacticForm(IList);
2230 SyntacticToSemantic[IList] = Result;
2231 }
2232
2233 return Result;
2234}
2235
2236/// Update the initializer at index @p StructuredIndex within the
2237/// structured initializer list to the value @p expr.
2238void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2239 unsigned &StructuredIndex,
2240 Expr *expr) {
2241 // No structured initializer list to update
2242 if (!StructuredList)
2243 return;
2244
Ted Kremenek709210f2010-04-13 23:39:13 +00002245 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2246 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002247 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002248 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002249 diag::warn_initializer_overrides)
2250 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002251 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002252 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002253 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002254 << PrevInit->getSourceRange();
2255 }
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Douglas Gregor4c678342009-01-28 21:54:33 +00002257 ++StructuredIndex;
2258}
2259
Douglas Gregor05c13a32009-01-22 00:58:24 +00002260/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002261/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002262/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002263/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002264/// failure. Returns the index expression, possibly with an implicit cast
2265/// added, on success. If everything went okay, Value will receive the
2266/// value of the constant expression.
2267static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002268CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002269 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002270
2271 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002272 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2273 if (Result.isInvalid())
2274 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002275
Chris Lattner3bf68932009-04-25 21:59:05 +00002276 if (Value.isSigned() && Value.isNegative())
2277 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002278 << Value.toString(10) << Index->getSourceRange();
2279
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002280 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002281 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002282}
2283
John McCall60d7b3a2010-08-24 06:29:42 +00002284ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002285 SourceLocation Loc,
2286 bool GNUSyntax,
2287 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002288 typedef DesignatedInitExpr::Designator ASTDesignator;
2289
2290 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002291 SmallVector<ASTDesignator, 32> Designators;
2292 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002293
2294 // Build designators and check array designator expressions.
2295 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2296 const Designator &D = Desig.getDesignator(Idx);
2297 switch (D.getKind()) {
2298 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002299 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002300 D.getFieldLoc()));
2301 break;
2302
2303 case Designator::ArrayDesignator: {
2304 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2305 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002306 if (!Index->isTypeDependent() && !Index->isValueDependent())
2307 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2308 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002309 Invalid = true;
2310 else {
2311 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002312 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002313 D.getRBracketLoc()));
2314 InitExpressions.push_back(Index);
2315 }
2316 break;
2317 }
2318
2319 case Designator::ArrayRangeDesignator: {
2320 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2321 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2322 llvm::APSInt StartValue;
2323 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002324 bool StartDependent = StartIndex->isTypeDependent() ||
2325 StartIndex->isValueDependent();
2326 bool EndDependent = EndIndex->isTypeDependent() ||
2327 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002328 if (!StartDependent)
2329 StartIndex =
2330 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2331 if (!EndDependent)
2332 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2333
2334 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002335 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002336 else {
2337 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002338 if (StartDependent || EndDependent) {
2339 // Nothing to compute.
2340 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002341 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002342 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002343 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002344
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002345 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002346 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002347 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002348 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2349 Invalid = true;
2350 } else {
2351 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002352 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002353 D.getEllipsisLoc(),
2354 D.getRBracketLoc()));
2355 InitExpressions.push_back(StartIndex);
2356 InitExpressions.push_back(EndIndex);
2357 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002358 }
2359 break;
2360 }
2361 }
2362 }
2363
2364 if (Invalid || Init.isInvalid())
2365 return ExprError();
2366
2367 // Clear out the expressions within the designation.
2368 Desig.ClearExprs(*this);
2369
2370 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002371 = DesignatedInitExpr::Create(Context,
2372 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002373 InitExpressions, Loc, GNUSyntax,
2374 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002375
David Blaikie4e4d0842012-03-11 07:00:24 +00002376 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002377 Diag(DIE->getLocStart(), diag::ext_designated_init)
2378 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002379
Douglas Gregor05c13a32009-01-22 00:58:24 +00002380 return Owned(DIE);
2381}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002382
Douglas Gregor20093b42009-12-09 23:02:17 +00002383//===----------------------------------------------------------------------===//
2384// Initialization entity
2385//===----------------------------------------------------------------------===//
2386
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002387InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002388 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002389 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002390{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002391 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2392 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002393 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002394 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002395 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002396 Type = VT->getElementType();
2397 } else {
2398 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2399 assert(CT && "Unexpected type");
2400 Kind = EK_ComplexElement;
2401 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002402 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002403}
2404
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002405InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002406 CXXBaseSpecifier *Base,
2407 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002408{
2409 InitializedEntity Result;
2410 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002411 Result.Base = reinterpret_cast<uintptr_t>(Base);
2412 if (IsInheritedVirtualBase)
2413 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002414
Douglas Gregord6542d82009-12-22 15:35:07 +00002415 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002416 return Result;
2417}
2418
Douglas Gregor99a2e602009-12-16 01:38:02 +00002419DeclarationName InitializedEntity::getName() const {
2420 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002421 case EK_Parameter: {
2422 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2423 return (D ? D->getDeclName() : DeclarationName());
2424 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002425
2426 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002427 case EK_Member:
2428 return VariableOrMember->getDeclName();
2429
Douglas Gregor47736542012-02-15 16:57:26 +00002430 case EK_LambdaCapture:
2431 return Capture.Var->getDeclName();
2432
Douglas Gregor99a2e602009-12-16 01:38:02 +00002433 case EK_Result:
2434 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002435 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002436 case EK_Temporary:
2437 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002438 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002439 case EK_ArrayElement:
2440 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002441 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002442 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002443 case EK_CompoundLiteralInit:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002444 return DeclarationName();
2445 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002446
David Blaikie7530c032012-01-17 06:56:22 +00002447 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002448}
2449
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002450DeclaratorDecl *InitializedEntity::getDecl() const {
2451 switch (getKind()) {
2452 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002453 case EK_Member:
2454 return VariableOrMember;
2455
John McCallf85e1932011-06-15 23:02:42 +00002456 case EK_Parameter:
2457 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2458
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002459 case EK_Result:
2460 case EK_Exception:
2461 case EK_New:
2462 case EK_Temporary:
2463 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002464 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002465 case EK_ArrayElement:
2466 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002467 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002468 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002469 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002470 case EK_CompoundLiteralInit:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002471 return 0;
2472 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002473
David Blaikie7530c032012-01-17 06:56:22 +00002474 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002475}
2476
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002477bool InitializedEntity::allowsNRVO() const {
2478 switch (getKind()) {
2479 case EK_Result:
2480 case EK_Exception:
2481 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002482
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002483 case EK_Variable:
2484 case EK_Parameter:
2485 case EK_Member:
2486 case EK_New:
2487 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002488 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002489 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002490 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002491 case EK_ArrayElement:
2492 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002493 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002494 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002495 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002496 break;
2497 }
2498
2499 return false;
2500}
2501
Douglas Gregor20093b42009-12-09 23:02:17 +00002502//===----------------------------------------------------------------------===//
2503// Initialization sequence
2504//===----------------------------------------------------------------------===//
2505
2506void InitializationSequence::Step::Destroy() {
2507 switch (Kind) {
2508 case SK_ResolveAddressOfOverloadedFunction:
2509 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002510 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002511 case SK_CastDerivedToBaseLValue:
2512 case SK_BindReference:
2513 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002514 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002515 case SK_UserConversion:
2516 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002517 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002518 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002519 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002520 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002521 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002522 case SK_UnwrapInitList:
2523 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002524 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002525 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002526 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002527 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002528 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002529 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002530 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002531 case SK_PassByIndirectCopyRestore:
2532 case SK_PassByIndirectRestore:
2533 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002534 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002535 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002536 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002537 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002538
Douglas Gregor20093b42009-12-09 23:02:17 +00002539 case SK_ConversionSequence:
2540 delete ICS;
2541 }
2542}
2543
Douglas Gregorb70cf442010-03-26 20:14:36 +00002544bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002545 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002546}
2547
2548bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002549 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002550 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002551
Douglas Gregorb70cf442010-03-26 20:14:36 +00002552 switch (getFailureKind()) {
2553 case FK_TooManyInitsForReference:
2554 case FK_ArrayNeedsInitList:
2555 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002556 case FK_ArrayNeedsInitListOrWideStringLiteral:
2557 case FK_NarrowStringIntoWideCharArray:
2558 case FK_WideStringIntoCharArray:
2559 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002560 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2561 case FK_NonConstLValueReferenceBindingToTemporary:
2562 case FK_NonConstLValueReferenceBindingToUnrelated:
2563 case FK_RValueReferenceBindingToLValue:
2564 case FK_ReferenceInitDropsQualifiers:
2565 case FK_ReferenceInitFailed:
2566 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002567 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002568 case FK_TooManyInitsForScalar:
2569 case FK_ReferenceBindingToInitList:
2570 case FK_InitListBadDestinationType:
2571 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002572 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002573 case FK_ArrayTypeMismatch:
2574 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002575 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002576 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002577 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002578 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002579 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002580 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002581
Douglas Gregorb70cf442010-03-26 20:14:36 +00002582 case FK_ReferenceInitOverloadFailed:
2583 case FK_UserConversionOverloadFailed:
2584 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002585 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002586 return FailedOverloadResult == OR_Ambiguous;
2587 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002588
David Blaikie7530c032012-01-17 06:56:22 +00002589 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002590}
2591
Douglas Gregord6e44a32010-04-16 22:09:46 +00002592bool InitializationSequence::isConstructorInitialization() const {
2593 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2594}
2595
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002596void
2597InitializationSequence
2598::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2599 DeclAccessPair Found,
2600 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002601 Step S;
2602 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2603 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002604 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002605 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002606 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002607 Steps.push_back(S);
2608}
2609
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002610void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002611 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002613 switch (VK) {
2614 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2615 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2616 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002617 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002618 S.Type = BaseType;
2619 Steps.push_back(S);
2620}
2621
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002622void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002623 bool BindingTemporary) {
2624 Step S;
2625 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2626 S.Type = T;
2627 Steps.push_back(S);
2628}
2629
Douglas Gregor523d46a2010-04-18 07:40:54 +00002630void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2631 Step S;
2632 S.Kind = SK_ExtraneousCopyToTemporary;
2633 S.Type = T;
2634 Steps.push_back(S);
2635}
2636
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002637void
2638InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2639 DeclAccessPair FoundDecl,
2640 QualType T,
2641 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002642 Step S;
2643 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002644 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002645 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002646 S.Function.Function = Function;
2647 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002648 Steps.push_back(S);
2649}
2650
2651void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002652 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002653 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002654 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002655 switch (VK) {
2656 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002657 S.Kind = SK_QualificationConversionRValue;
2658 break;
John McCall5baba9d2010-08-25 10:28:54 +00002659 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002660 S.Kind = SK_QualificationConversionXValue;
2661 break;
John McCall5baba9d2010-08-25 10:28:54 +00002662 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002663 S.Kind = SK_QualificationConversionLValue;
2664 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002665 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002666 S.Type = Ty;
2667 Steps.push_back(S);
2668}
2669
Jordan Rose1fd1e282013-04-11 00:58:58 +00002670void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2671 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2672
2673 Step S;
2674 S.Kind = SK_LValueToRValue;
2675 S.Type = Ty;
2676 Steps.push_back(S);
2677}
2678
Douglas Gregor20093b42009-12-09 23:02:17 +00002679void InitializationSequence::AddConversionSequenceStep(
2680 const ImplicitConversionSequence &ICS,
2681 QualType T) {
2682 Step S;
2683 S.Kind = SK_ConversionSequence;
2684 S.Type = T;
2685 S.ICS = new ImplicitConversionSequence(ICS);
2686 Steps.push_back(S);
2687}
2688
Douglas Gregord87b61f2009-12-10 17:56:55 +00002689void InitializationSequence::AddListInitializationStep(QualType T) {
2690 Step S;
2691 S.Kind = SK_ListInitialization;
2692 S.Type = T;
2693 Steps.push_back(S);
2694}
2695
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002696void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002697InitializationSequence
2698::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2699 AccessSpecifier Access,
2700 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002701 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002702 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002703 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002704 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2705 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002706 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002707 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002708 S.Function.Function = Constructor;
2709 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002710 Steps.push_back(S);
2711}
2712
Douglas Gregor71d17402009-12-15 00:01:57 +00002713void InitializationSequence::AddZeroInitializationStep(QualType T) {
2714 Step S;
2715 S.Kind = SK_ZeroInitialization;
2716 S.Type = T;
2717 Steps.push_back(S);
2718}
2719
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002720void InitializationSequence::AddCAssignmentStep(QualType T) {
2721 Step S;
2722 S.Kind = SK_CAssignment;
2723 S.Type = T;
2724 Steps.push_back(S);
2725}
2726
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002727void InitializationSequence::AddStringInitStep(QualType T) {
2728 Step S;
2729 S.Kind = SK_StringInit;
2730 S.Type = T;
2731 Steps.push_back(S);
2732}
2733
Douglas Gregor569c3162010-08-07 11:51:51 +00002734void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2735 Step S;
2736 S.Kind = SK_ObjCObjectConversion;
2737 S.Type = T;
2738 Steps.push_back(S);
2739}
2740
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002741void InitializationSequence::AddArrayInitStep(QualType T) {
2742 Step S;
2743 S.Kind = SK_ArrayInit;
2744 S.Type = T;
2745 Steps.push_back(S);
2746}
2747
Richard Smith0f163e92012-02-15 22:38:09 +00002748void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2749 Step S;
2750 S.Kind = SK_ParenthesizedArrayInit;
2751 S.Type = T;
2752 Steps.push_back(S);
2753}
2754
John McCallf85e1932011-06-15 23:02:42 +00002755void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2756 bool shouldCopy) {
2757 Step s;
2758 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2759 : SK_PassByIndirectRestore);
2760 s.Type = type;
2761 Steps.push_back(s);
2762}
2763
2764void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2765 Step S;
2766 S.Kind = SK_ProduceObjCObject;
2767 S.Type = T;
2768 Steps.push_back(S);
2769}
2770
Sebastian Redl2b916b82012-01-17 22:49:42 +00002771void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2772 Step S;
2773 S.Kind = SK_StdInitializerList;
2774 S.Type = T;
2775 Steps.push_back(S);
2776}
2777
Guy Benyei21f18c42013-02-07 10:55:47 +00002778void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2779 Step S;
2780 S.Kind = SK_OCLSamplerInit;
2781 S.Type = T;
2782 Steps.push_back(S);
2783}
2784
Guy Benyeie6b9d802013-01-20 12:31:11 +00002785void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2786 Step S;
2787 S.Kind = SK_OCLZeroEvent;
2788 S.Type = T;
2789 Steps.push_back(S);
2790}
2791
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002792void InitializationSequence::RewrapReferenceInitList(QualType T,
2793 InitListExpr *Syntactic) {
2794 assert(Syntactic->getNumInits() == 1 &&
2795 "Can only rewrap trivial init lists.");
2796 Step S;
2797 S.Kind = SK_UnwrapInitList;
2798 S.Type = Syntactic->getInit(0)->getType();
2799 Steps.insert(Steps.begin(), S);
2800
2801 S.Kind = SK_RewrapInitList;
2802 S.Type = T;
2803 S.WrappingSyntacticList = Syntactic;
2804 Steps.push_back(S);
2805}
2806
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002807void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002808 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002809 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002810 this->Failure = Failure;
2811 this->FailedOverloadResult = Result;
2812}
2813
2814//===----------------------------------------------------------------------===//
2815// Attempt initialization
2816//===----------------------------------------------------------------------===//
2817
John McCallf85e1932011-06-15 23:02:42 +00002818static void MaybeProduceObjCObject(Sema &S,
2819 InitializationSequence &Sequence,
2820 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002821 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002822
2823 /// When initializing a parameter, produce the value if it's marked
2824 /// __attribute__((ns_consumed)).
2825 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2826 if (!Entity.isParameterConsumed())
2827 return;
2828
2829 assert(Entity.getType()->isObjCRetainableType() &&
2830 "consuming an object of unretainable type?");
2831 Sequence.AddProduceObjCObjectStep(Entity.getType());
2832
2833 /// When initializing a return value, if the return type is a
2834 /// retainable type, then returns need to immediately retain the
2835 /// object. If an autorelease is required, it will be done at the
2836 /// last instant.
2837 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2838 if (!Entity.getType()->isObjCRetainableType())
2839 return;
2840
2841 Sequence.AddProduceObjCObjectStep(Entity.getType());
2842 }
2843}
2844
Richard Smithf4bb8d02012-07-05 08:39:21 +00002845/// \brief When initializing from init list via constructor, handle
2846/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002847///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002848/// \return true if we have handled initialization of an object of type
2849/// std::initializer_list<T>, false otherwise.
2850static bool TryInitializerListConstruction(Sema &S,
2851 InitListExpr *List,
2852 QualType DestType,
2853 InitializationSequence &Sequence) {
2854 QualType E;
2855 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002856 return false;
2857
Richard Smithf4bb8d02012-07-05 08:39:21 +00002858 // Check that each individual element can be copy-constructed. But since we
2859 // have no place to store further information, we'll recalculate everything
2860 // later.
2861 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2862 S.Context.getConstantArrayType(E,
2863 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2864 List->getNumInits()),
2865 ArrayType::Normal, 0));
2866 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2867 0, HiddenArray);
2868 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2869 Element.setElementIndex(i);
2870 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2871 Sequence.SetFailed(
2872 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002873 return true;
2874 }
2875 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002876 Sequence.AddStdInitializerListConstructionStep(DestType);
2877 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002878}
2879
Sebastian Redl96715b22012-02-04 21:27:39 +00002880static OverloadingResult
2881ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002882 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002883 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002884 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002885 OverloadCandidateSet::iterator &Best,
2886 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002887 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002888 CandidateSet.clear();
2889
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002890 for (ArrayRef<NamedDecl *>::iterator
2891 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002892 NamedDecl *D = *Con;
2893 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2894 bool SuppressUserConversions = false;
2895
2896 // Find the constructor (which may be a template).
2897 CXXConstructorDecl *Constructor = 0;
2898 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2899 if (ConstructorTmpl)
2900 Constructor = cast<CXXConstructorDecl>(
2901 ConstructorTmpl->getTemplatedDecl());
2902 else {
2903 Constructor = cast<CXXConstructorDecl>(D);
2904
2905 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002906 // suppress user-defined conversions on the arguments. We do the same for
2907 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002908 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002909 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002910 SuppressUserConversions = true;
2911 }
2912
2913 if (!Constructor->isInvalidDecl() &&
2914 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002915 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002916 if (ConstructorTmpl)
2917 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002918 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002919 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002920 else {
2921 // C++ [over.match.copy]p1:
2922 // - When initializing a temporary to be bound to the first parameter
2923 // of a constructor that takes a reference to possibly cv-qualified
2924 // T as its first argument, called with a single argument in the
2925 // context of direct-initialization, explicit conversion functions
2926 // are also considered.
2927 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002928 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00002929 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002930 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002931 SuppressUserConversions,
2932 /*PartialOverloading=*/false,
2933 /*AllowExplicit=*/AllowExplicitConv);
2934 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002935 }
2936 }
2937
2938 // Perform overload resolution and return the result.
2939 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2940}
2941
Sebastian Redl10f04a62011-12-22 14:44:04 +00002942/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2943/// enumerates the constructors of the initialized entity and performs overload
2944/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002945/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002946/// class type.
2947static void TryConstructorInitialization(Sema &S,
2948 const InitializedEntity &Entity,
2949 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002950 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002951 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002952 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002953 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00002954 "InitListSyntax must come with a single initializer list argument.");
2955
Sebastian Redl10f04a62011-12-22 14:44:04 +00002956 // The type we're constructing needs to be complete.
2957 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002958 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002959 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002960 }
2961
2962 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2963 assert(DestRecordType && "Constructor initialization requires record type");
2964 CXXRecordDecl *DestRecordDecl
2965 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2966
Sebastian Redl96715b22012-02-04 21:27:39 +00002967 // Build the candidate set directly in the initialization sequence
2968 // structure, so that it will persist if we fail.
2969 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2970
2971 // Determine whether we are allowed to call explicit constructors or
2972 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002973 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002974 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002975
Sebastian Redl10f04a62011-12-22 14:44:04 +00002976 // - Otherwise, if T is a class type, constructors are considered. The
2977 // applicable constructors are enumerated, and the best one is chosen
2978 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00002979 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002980 // The container holding the constructors can under certain conditions
2981 // be changed while iterating (e.g. because of deserialization).
2982 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00002983 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00002984
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002985 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002986 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002987 bool AsInitializerList = false;
2988
2989 // C++11 [over.match.list]p1:
2990 // When objects of non-aggregate type T are list-initialized, overload
2991 // resolution selects the constructor in two phases:
2992 // - Initially, the candidate functions are the initializer-list
2993 // constructors of the class T and the argument list consists of the
2994 // initializer list as a single argument.
2995 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002996 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002997 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00002998
2999 // If the initializer list has no elements and T has a default constructor,
3000 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003001 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003002 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003003 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003004 CopyInitialization, AllowExplicit,
3005 /*OnlyListConstructor=*/true,
3006 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003007
3008 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003009 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003010 }
3011
3012 // C++11 [over.match.list]p1:
3013 // - If no viable initializer-list constructor is found, overload resolution
3014 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003015 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003016 // elements of the initializer list.
3017 if (Result == OR_No_Viable_Function) {
3018 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003019 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003020 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003021 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003022 /*OnlyListConstructors=*/false,
3023 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003024 }
3025 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003026 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003027 InitializationSequence::FK_ListConstructorOverloadFailed :
3028 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003029 Result);
3030 return;
3031 }
3032
Richard Smithf4bb8d02012-07-05 08:39:21 +00003033 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003034 // If a program calls for the default initialization of an object
3035 // of a const-qualified type T, T shall be a class type with a
3036 // user-provided default constructor.
3037 if (Kind.getKind() == InitializationKind::IK_Default &&
3038 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003039 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003040 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3041 return;
3042 }
3043
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003044 // C++11 [over.match.list]p1:
3045 // In copy-list-initialization, if an explicit constructor is chosen, the
3046 // initializer is ill-formed.
3047 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3048 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3049 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3050 return;
3051 }
3052
Sebastian Redl10f04a62011-12-22 14:44:04 +00003053 // Add the constructor initialization step. Any cv-qualification conversion is
3054 // subsumed by the initialization.
3055 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003056 Sequence.AddConstructorInitializationStep(CtorDecl,
3057 Best->FoundDecl.getAccess(),
3058 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003059 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003060}
3061
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003062static bool
3063ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3064 Expr *Initializer,
3065 QualType &SourceType,
3066 QualType &UnqualifiedSourceType,
3067 QualType UnqualifiedTargetType,
3068 InitializationSequence &Sequence) {
3069 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3070 S.Context.OverloadTy) {
3071 DeclAccessPair Found;
3072 bool HadMultipleCandidates = false;
3073 if (FunctionDecl *Fn
3074 = S.ResolveAddressOfOverloadedFunction(Initializer,
3075 UnqualifiedTargetType,
3076 false, Found,
3077 &HadMultipleCandidates)) {
3078 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3079 HadMultipleCandidates);
3080 SourceType = Fn->getType();
3081 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3082 } else if (!UnqualifiedTargetType->isRecordType()) {
3083 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3084 return true;
3085 }
3086 }
3087 return false;
3088}
3089
3090static void TryReferenceInitializationCore(Sema &S,
3091 const InitializedEntity &Entity,
3092 const InitializationKind &Kind,
3093 Expr *Initializer,
3094 QualType cv1T1, QualType T1,
3095 Qualifiers T1Quals,
3096 QualType cv2T2, QualType T2,
3097 Qualifiers T2Quals,
3098 InitializationSequence &Sequence);
3099
Richard Smithf4bb8d02012-07-05 08:39:21 +00003100static void TryValueInitialization(Sema &S,
3101 const InitializedEntity &Entity,
3102 const InitializationKind &Kind,
3103 InitializationSequence &Sequence,
3104 InitListExpr *InitList = 0);
3105
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003106static void TryListInitialization(Sema &S,
3107 const InitializedEntity &Entity,
3108 const InitializationKind &Kind,
3109 InitListExpr *InitList,
3110 InitializationSequence &Sequence);
3111
3112/// \brief Attempt list initialization of a reference.
3113static void TryReferenceListInitialization(Sema &S,
3114 const InitializedEntity &Entity,
3115 const InitializationKind &Kind,
3116 InitListExpr *InitList,
3117 InitializationSequence &Sequence)
3118{
3119 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003120 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003121 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3122 return;
3123 }
3124
3125 QualType DestType = Entity.getType();
3126 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3127 Qualifiers T1Quals;
3128 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3129
3130 // Reference initialization via an initializer list works thus:
3131 // If the initializer list consists of a single element that is
3132 // reference-related to the referenced type, bind directly to that element
3133 // (possibly creating temporaries).
3134 // Otherwise, initialize a temporary with the initializer list and
3135 // bind to that.
3136 if (InitList->getNumInits() == 1) {
3137 Expr *Initializer = InitList->getInit(0);
3138 QualType cv2T2 = Initializer->getType();
3139 Qualifiers T2Quals;
3140 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3141
3142 // If this fails, creating a temporary wouldn't work either.
3143 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3144 T1, Sequence))
3145 return;
3146
3147 SourceLocation DeclLoc = Initializer->getLocStart();
3148 bool dummy1, dummy2, dummy3;
3149 Sema::ReferenceCompareResult RefRelationship
3150 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3151 dummy2, dummy3);
3152 if (RefRelationship >= Sema::Ref_Related) {
3153 // Try to bind the reference here.
3154 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3155 T1Quals, cv2T2, T2, T2Quals, Sequence);
3156 if (Sequence)
3157 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3158 return;
3159 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003160
3161 // Update the initializer if we've resolved an overloaded function.
3162 if (Sequence.step_begin() != Sequence.step_end())
3163 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003164 }
3165
3166 // Not reference-related. Create a temporary and bind to that.
3167 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3168
3169 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3170 if (Sequence) {
3171 if (DestType->isRValueReferenceType() ||
3172 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3173 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3174 else
3175 Sequence.SetFailed(
3176 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3177 }
3178}
3179
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003180/// \brief Attempt list initialization (C++0x [dcl.init.list])
3181static void TryListInitialization(Sema &S,
3182 const InitializedEntity &Entity,
3183 const InitializationKind &Kind,
3184 InitListExpr *InitList,
3185 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003186 QualType DestType = Entity.getType();
3187
Sebastian Redl14b0c192011-09-24 17:48:00 +00003188 // C++ doesn't allow scalar initialization with more than one argument.
3189 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003190 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003191 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3192 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3193 return;
3194 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003195 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003196 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003197 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003198 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003199 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003200 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003201 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003202 return;
3203 }
3204
Richard Smithf4bb8d02012-07-05 08:39:21 +00003205 // C++11 [dcl.init.list]p3:
3206 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003207 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003208 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003209 // - Otherwise, if the initializer list has no elements and T is a
3210 // class type with a default constructor, the object is
3211 // value-initialized.
3212 if (InitList->getNumInits() == 0) {
3213 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003214 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003215 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3216 return;
3217 }
3218 }
3219
3220 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3221 // an initializer_list object constructed [...]
3222 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3223 return;
3224
3225 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003226 Expr *InitListAsExpr = InitList;
3227 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003228 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003229 } else
3230 Sequence.SetFailed(
3231 InitializationSequence::FK_InitListBadDestinationType);
3232 return;
3233 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003234 }
3235
Sebastian Redl14b0c192011-09-24 17:48:00 +00003236 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003237 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003238 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00003239 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003240 if (CheckInitList.HadError()) {
3241 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3242 return;
3243 }
3244
3245 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003246 Sequence.AddListInitializationStep(DestType);
3247}
Douglas Gregor20093b42009-12-09 23:02:17 +00003248
3249/// \brief Try a reference initialization that involves calling a conversion
3250/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003251static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3252 const InitializedEntity &Entity,
3253 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003254 Expr *Initializer,
3255 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003256 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003257 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003258 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3259 QualType T1 = cv1T1.getUnqualifiedType();
3260 QualType cv2T2 = Initializer->getType();
3261 QualType T2 = cv2T2.getUnqualifiedType();
3262
3263 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003264 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003265 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003266 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003267 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003268 ObjCConversion,
3269 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003270 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003271 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003272 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003273 (void)ObjCLifetimeConversion;
3274
Douglas Gregor20093b42009-12-09 23:02:17 +00003275 // Build the candidate set directly in the initialization sequence
3276 // structure, so that it will persist if we fail.
3277 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3278 CandidateSet.clear();
3279
3280 // Determine whether we are allowed to call explicit constructors or
3281 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003282 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003283 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3284
Douglas Gregor20093b42009-12-09 23:02:17 +00003285 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003286 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3287 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003288 // The type we're converting to is a class type. Enumerate its constructors
3289 // to see if there is a suitable conversion.
3290 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003291
David Blaikie3bc93e32012-12-19 00:45:41 +00003292 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003293 // The container holding the constructors can under certain conditions
3294 // be changed while iterating (e.g. because of deserialization).
3295 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003296 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003297 for (SmallVector<NamedDecl*, 16>::iterator
3298 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3299 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003300 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3301
Douglas Gregor20093b42009-12-09 23:02:17 +00003302 // Find the constructor (which may be a template).
3303 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003304 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003305 if (ConstructorTmpl)
3306 Constructor = cast<CXXConstructorDecl>(
3307 ConstructorTmpl->getTemplatedDecl());
3308 else
John McCall9aa472c2010-03-19 07:35:19 +00003309 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003310
Douglas Gregor20093b42009-12-09 23:02:17 +00003311 if (!Constructor->isInvalidDecl() &&
3312 Constructor->isConvertingConstructor(AllowExplicit)) {
3313 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003314 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003315 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003316 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003317 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003318 else
John McCall9aa472c2010-03-19 07:35:19 +00003319 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003320 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003321 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003322 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003323 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003324 }
John McCall572fc622010-08-17 07:23:57 +00003325 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3326 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003328 const RecordType *T2RecordType = 0;
3329 if ((T2RecordType = T2->getAs<RecordType>()) &&
3330 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003331 // The type we're converting from is a class type, enumerate its conversion
3332 // functions.
3333 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3334
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003335 std::pair<CXXRecordDecl::conversion_iterator,
3336 CXXRecordDecl::conversion_iterator>
3337 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3338 for (CXXRecordDecl::conversion_iterator
3339 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003340 NamedDecl *D = *I;
3341 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3342 if (isa<UsingShadowDecl>(D))
3343 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344
Douglas Gregor20093b42009-12-09 23:02:17 +00003345 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3346 CXXConversionDecl *Conv;
3347 if (ConvTemplate)
3348 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3349 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003350 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003351
Douglas Gregor20093b42009-12-09 23:02:17 +00003352 // If the conversion function doesn't return a reference type,
3353 // it can't be considered for this conversion unless we're allowed to
3354 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003355 // FIXME: Do we need to make sure that we only consider conversion
3356 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003357 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003358 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003359 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3360 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003361 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003362 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003363 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003364 else
John McCall9aa472c2010-03-19 07:35:19 +00003365 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003366 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003367 }
3368 }
3369 }
John McCall572fc622010-08-17 07:23:57 +00003370 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3371 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003372
Douglas Gregor20093b42009-12-09 23:02:17 +00003373 SourceLocation DeclLoc = Initializer->getLocStart();
3374
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003376 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003378 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003379 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003380
Douglas Gregor20093b42009-12-09 23:02:17 +00003381 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003382 // This is the overload that will be used for this initialization step if we
3383 // use this initialization. Mark it as referenced.
3384 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003385
Eli Friedman03981012009-12-11 02:42:07 +00003386 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003387 if (isa<CXXConversionDecl>(Function))
3388 T2 = Function->getResultType();
3389 else
3390 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003391
3392 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003393 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003394 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003395 T2.getNonLValueExprType(S.Context),
3396 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003397
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003398 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003399 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003400 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003401 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003402 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003403 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003404 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003405
Douglas Gregor20093b42009-12-09 23:02:17 +00003406 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003407 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003408 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003409 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003411 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003412 NewDerivedToBase, NewObjCConversion,
3413 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003414 if (NewRefRelationship == Sema::Ref_Incompatible) {
3415 // If the type we've converted to is not reference-related to the
3416 // type we're looking for, then there is another conversion step
3417 // we need to perform to produce a temporary of the right type
3418 // that we'll be binding to.
3419 ImplicitConversionSequence ICS;
3420 ICS.setStandard();
3421 ICS.Standard = Best->FinalConversion;
3422 T2 = ICS.Standard.getToType(2);
3423 Sequence.AddConversionSequenceStep(ICS, T2);
3424 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003425 Sequence.AddDerivedToBaseCastStep(
3426 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003428 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003429 else if (NewObjCConversion)
3430 Sequence.AddObjCObjectConversionStep(
3431 S.Context.getQualifiedType(T1,
3432 T2.getNonReferenceType().getQualifiers()));
3433
Douglas Gregor20093b42009-12-09 23:02:17 +00003434 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003435 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003436
Douglas Gregor20093b42009-12-09 23:02:17 +00003437 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3438 return OR_Success;
3439}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003440
Richard Smith83da2e72011-10-19 16:55:56 +00003441static void CheckCXX98CompatAccessibleCopy(Sema &S,
3442 const InitializedEntity &Entity,
3443 Expr *CurInitExpr);
3444
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003445/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3446static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003447 const InitializedEntity &Entity,
3448 const InitializationKind &Kind,
3449 Expr *Initializer,
3450 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003451 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003452 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003453 Qualifiers T1Quals;
3454 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003455 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003456 Qualifiers T2Quals;
3457 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003458
Douglas Gregor20093b42009-12-09 23:02:17 +00003459 // If the initializer is the address of an overloaded function, try
3460 // to resolve the overloaded function. If all goes well, T2 is the
3461 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003462 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3463 T1, Sequence))
3464 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003465
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003466 // Delegate everything else to a subfunction.
3467 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3468 T1Quals, cv2T2, T2, T2Quals, Sequence);
3469}
3470
Jordan Rose1fd1e282013-04-11 00:58:58 +00003471/// Converts the target of reference initialization so that it has the
3472/// appropriate qualifiers and value kind.
3473///
3474/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3475/// \code
3476/// int x;
3477/// const int &r = x;
3478/// \endcode
3479///
3480/// In this case the reference is binding to a bitfield lvalue, which isn't
3481/// valid. Perform a load to create a lifetime-extended temporary instead.
3482/// \code
3483/// const int &r = someStruct.bitfield;
3484/// \endcode
3485static ExprValueKind
3486convertQualifiersAndValueKindIfNecessary(Sema &S,
3487 InitializationSequence &Sequence,
3488 Expr *Initializer,
3489 QualType cv1T1,
3490 Qualifiers T1Quals,
3491 Qualifiers T2Quals,
3492 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003493 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003494 Initializer->refersToVectorElement();
3495
3496 if (IsNonAddressableType) {
3497 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3498 // lvalue reference to a non-volatile const type, or the reference shall be
3499 // an rvalue reference.
3500 //
3501 // If not, we can't make a temporary and bind to that. Give up and allow the
3502 // error to be diagnosed later.
3503 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3504 assert(Initializer->isGLValue());
3505 return Initializer->getValueKind();
3506 }
3507
3508 // Force a load so we can materialize a temporary.
3509 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3510 return VK_RValue;
3511 }
3512
3513 if (T1Quals != T2Quals) {
3514 Sequence.AddQualificationConversionStep(cv1T1,
3515 Initializer->getValueKind());
3516 }
3517
3518 return Initializer->getValueKind();
3519}
3520
3521
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003522/// \brief Reference initialization without resolving overloaded functions.
3523static void TryReferenceInitializationCore(Sema &S,
3524 const InitializedEntity &Entity,
3525 const InitializationKind &Kind,
3526 Expr *Initializer,
3527 QualType cv1T1, QualType T1,
3528 Qualifiers T1Quals,
3529 QualType cv2T2, QualType T2,
3530 Qualifiers T2Quals,
3531 InitializationSequence &Sequence) {
3532 QualType DestType = Entity.getType();
3533 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003534 // Compute some basic properties of the types and the initializer.
3535 bool isLValueRef = DestType->isLValueReferenceType();
3536 bool isRValueRef = !isLValueRef;
3537 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003538 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003539 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003540 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003541 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003542 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003543 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003544
Douglas Gregor20093b42009-12-09 23:02:17 +00003545 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003546 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003547 // "cv2 T2" as follows:
3548 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003550 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003551 // Note the analogous bullet points for rvlaue refs to functions. Because
3552 // there are no function rvalues in C++, rvalue refs to functions are treated
3553 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003554 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003555 bool T1Function = T1->isFunctionType();
3556 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003557 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003558 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003560 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003561 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003562 // reference-compatible with "cv2 T2," or
3563 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003564 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003565 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003566 // can occur. However, we do pay attention to whether it is a bit-field
3567 // to decide whether we're actually binding to a temporary created from
3568 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003569 if (DerivedToBase)
3570 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003571 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003572 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003573 else if (ObjCConversion)
3574 Sequence.AddObjCObjectConversionStep(
3575 S.Context.getQualifiedType(T1, T2Quals));
3576
Jordan Rose1fd1e282013-04-11 00:58:58 +00003577 ExprValueKind ValueKind =
3578 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3579 cv1T1, T1Quals, T2Quals,
3580 isLValueRef);
3581 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003582 return;
3583 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003584
3585 // - has a class type (i.e., T2 is a class type), where T1 is not
3586 // reference-related to T2, and can be implicitly converted to an
3587 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3588 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003589 // applicable conversion functions (13.3.1.6) and choosing the best
3590 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003591 // If we have an rvalue ref to function type here, the rhs must be
3592 // an rvalue.
3593 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3594 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003595 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003596 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003597 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003598 Sequence);
3599 if (ConvOvlResult == OR_Success)
3600 return;
John McCall1d318332010-01-12 00:44:57 +00003601 if (ConvOvlResult != OR_No_Viable_Function) {
3602 Sequence.SetOverloadFailure(
3603 InitializationSequence::FK_ReferenceInitOverloadFailed,
3604 ConvOvlResult);
3605 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003606 }
3607 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003608
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003609 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003610 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003611 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003612 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003613 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3614 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3615 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003616 Sequence.SetOverloadFailure(
3617 InitializationSequence::FK_ReferenceInitOverloadFailed,
3618 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003619 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003620 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003621 ? (RefRelationship == Sema::Ref_Related
3622 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3623 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3624 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003625
Douglas Gregor20093b42009-12-09 23:02:17 +00003626 return;
3627 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003628
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003629 // - If the initializer expression
3630 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3631 // "cv1 T1" is reference-compatible with "cv2 T2"
3632 // Note: functions are handled below.
3633 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003634 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003635 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003636 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003637 (InitCategory.isXValue() ||
3638 (InitCategory.isPRValue() && T2->isRecordType()) ||
3639 (InitCategory.isPRValue() && T2->isArrayType()))) {
3640 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3641 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003642 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3643 // compiler the freedom to perform a copy here or bind to the
3644 // object, while C++0x requires that we bind directly to the
3645 // object. Hence, we always bind to the object without making an
3646 // extra copy. However, in C++03 requires that we check for the
3647 // presence of a suitable copy constructor:
3648 //
3649 // The constructor that would be used to make the copy shall
3650 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003651 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003652 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003653 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003654 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003655 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003656
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003657 if (DerivedToBase)
3658 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3659 ValueKind);
3660 else if (ObjCConversion)
3661 Sequence.AddObjCObjectConversionStep(
3662 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003663
Jordan Rose1fd1e282013-04-11 00:58:58 +00003664 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3665 Initializer, cv1T1,
3666 T1Quals, T2Quals,
3667 isLValueRef);
3668
3669 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003671 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003672
3673 // - has a class type (i.e., T2 is a class type), where T1 is not
3674 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003675 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3676 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003677 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003678 if (RefRelationship == Sema::Ref_Incompatible) {
3679 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3680 Kind, Initializer,
3681 /*AllowRValues=*/true,
3682 Sequence);
3683 if (ConvOvlResult)
3684 Sequence.SetOverloadFailure(
3685 InitializationSequence::FK_ReferenceInitOverloadFailed,
3686 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003687
Douglas Gregor20093b42009-12-09 23:02:17 +00003688 return;
3689 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003690
Douglas Gregordefa32e2013-03-26 23:59:23 +00003691 if ((RefRelationship == Sema::Ref_Compatible ||
3692 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3693 isRValueRef && InitCategory.isLValue()) {
3694 Sequence.SetFailed(
3695 InitializationSequence::FK_RValueReferenceBindingToLValue);
3696 return;
3697 }
3698
Douglas Gregor20093b42009-12-09 23:02:17 +00003699 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3700 return;
3701 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003702
3703 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003704 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003705 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003706 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003707
Douglas Gregor20093b42009-12-09 23:02:17 +00003708 // Determine whether we are allowed to call explicit constructors or
3709 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003710 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003711
3712 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3713
John McCallf85e1932011-06-15 23:02:42 +00003714 ImplicitConversionSequence ICS
3715 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003716 /*SuppressUserConversions*/ false,
3717 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003718 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003719 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3720 /*AllowObjCWritebackConversion=*/false);
3721
3722 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003723 // FIXME: Use the conversion function set stored in ICS to turn
3724 // this into an overloading ambiguity diagnostic. However, we need
3725 // to keep that set as an OverloadCandidateSet rather than as some
3726 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003727 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3728 Sequence.SetOverloadFailure(
3729 InitializationSequence::FK_ReferenceInitOverloadFailed,
3730 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003731 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3732 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003733 else
3734 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003735 return;
John McCallf85e1932011-06-15 23:02:42 +00003736 } else {
3737 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003738 }
3739
3740 // [...] If T1 is reference-related to T2, cv1 must be the
3741 // same cv-qualification as, or greater cv-qualification
3742 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003743 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3744 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003745 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003746 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003747 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3748 return;
3749 }
3750
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003751 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003752 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003753 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003754 InitCategory.isLValue()) {
3755 Sequence.SetFailed(
3756 InitializationSequence::FK_RValueReferenceBindingToLValue);
3757 return;
3758 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003759
Douglas Gregor20093b42009-12-09 23:02:17 +00003760 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3761 return;
3762}
3763
3764/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765/// (C++ [dcl.init.string], C99 6.7.8).
3766static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003767 const InitializedEntity &Entity,
3768 const InitializationKind &Kind,
3769 Expr *Initializer,
3770 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003771 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003772}
3773
Douglas Gregor71d17402009-12-15 00:01:57 +00003774/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003775static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003776 const InitializedEntity &Entity,
3777 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003778 InitializationSequence &Sequence,
3779 InitListExpr *InitList) {
3780 assert((!InitList || InitList->getNumInits() == 0) &&
3781 "Shouldn't use value-init for non-empty init lists");
3782
Richard Smith1d0c9a82012-02-14 21:14:13 +00003783 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003784 //
3785 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003786 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003787
Douglas Gregor71d17402009-12-15 00:01:57 +00003788 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003789 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790
Douglas Gregor71d17402009-12-15 00:01:57 +00003791 if (const RecordType *RT = T->getAs<RecordType>()) {
3792 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003793 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003794 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003795 // C++98:
3796 // -- if T is a class type (clause 9) with a user-declared constructor
3797 // (12.1), then the default constructor for T is called (and the
3798 // initialization is ill-formed if T has no accessible default
3799 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003800 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003801 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003802 } else {
3803 // C++11:
3804 // -- if T is a class type (clause 9) with either no default constructor
3805 // (12.1 [class.ctor]) or a default constructor that is user-provided
3806 // or deleted, then the object is default-initialized;
3807 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3808 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003809 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811
Richard Smith1d0c9a82012-02-14 21:14:13 +00003812 // -- if T is a (possibly cv-qualified) non-union class type without a
3813 // user-provided or deleted default constructor, then the object is
3814 // zero-initialized and, if T has a non-trivial default constructor,
3815 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003816 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3817 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003818 if (NeedZeroInitialization)
3819 Sequence.AddZeroInitializationStep(Entity.getType());
3820
Richard Smithd5bc8672012-12-08 02:01:17 +00003821 // C++03:
3822 // -- if T is a non-union class type without a user-declared constructor,
3823 // then every non-static data member and base class component of T is
3824 // value-initialized;
3825 // [...] A program that calls for [...] value-initialization of an
3826 // entity of reference type is ill-formed.
3827 //
3828 // C++11 doesn't need this handling, because value-initialization does not
3829 // occur recursively there, and the implicit default constructor is
3830 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003831 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003832 ClassDecl->hasUninitializedReferenceMember()) {
3833 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3834 return;
3835 }
3836
Richard Smithf4bb8d02012-07-05 08:39:21 +00003837 // If this is list-value-initialization, pass the empty init list on when
3838 // building the constructor call. This affects the semantics of a few
3839 // things (such as whether an explicit default constructor can be called).
3840 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003841 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003842 bool InitListSyntax = InitList;
3843
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003844 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3845 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003846 }
3847 }
3848
Douglas Gregord6542d82009-12-22 15:35:07 +00003849 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003850}
3851
Douglas Gregor99a2e602009-12-16 01:38:02 +00003852/// \brief Attempt default initialization (C++ [dcl.init]p6).
3853static void TryDefaultInitialization(Sema &S,
3854 const InitializedEntity &Entity,
3855 const InitializationKind &Kind,
3856 InitializationSequence &Sequence) {
3857 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003858
Douglas Gregor99a2e602009-12-16 01:38:02 +00003859 // C++ [dcl.init]p6:
3860 // To default-initialize an object of type T means:
3861 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003862 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3863
Douglas Gregor99a2e602009-12-16 01:38:02 +00003864 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3865 // constructor for T is called (and the initialization is ill-formed if
3866 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003867 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003868 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003869 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003870 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003871
Douglas Gregor99a2e602009-12-16 01:38:02 +00003872 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003873
Douglas Gregor99a2e602009-12-16 01:38:02 +00003874 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003875 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003876 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003877 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003878 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003879 return;
3880 }
3881
3882 // If the destination type has a lifetime property, zero-initialize it.
3883 if (DestType.getQualifiers().hasObjCLifetime()) {
3884 Sequence.AddZeroInitializationStep(Entity.getType());
3885 return;
3886 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003887}
3888
Douglas Gregor20093b42009-12-09 23:02:17 +00003889/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3890/// which enumerates all conversion functions and performs overload resolution
3891/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003892static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003893 const InitializedEntity &Entity,
3894 const InitializationKind &Kind,
3895 Expr *Initializer,
3896 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003897 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003898 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3899 QualType SourceType = Initializer->getType();
3900 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3901 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003902
Douglas Gregor4a520a22009-12-14 17:27:33 +00003903 // Build the candidate set directly in the initialization sequence
3904 // structure, so that it will persist if we fail.
3905 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3906 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003907
Douglas Gregor4a520a22009-12-14 17:27:33 +00003908 // Determine whether we are allowed to call explicit constructors or
3909 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003910 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003911
Douglas Gregor4a520a22009-12-14 17:27:33 +00003912 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3913 // The type we're converting to is a class type. Enumerate its constructors
3914 // to see if there is a suitable conversion.
3915 CXXRecordDecl *DestRecordDecl
3916 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003917
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003918 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003919 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003920 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003921 // The container holding the constructors can under certain conditions
3922 // be changed while iterating. To be safe we copy the lookup results
3923 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003924 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003925 for (SmallVector<NamedDecl*, 8>::iterator
3926 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003927 Con != ConEnd; ++Con) {
3928 NamedDecl *D = *Con;
3929 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003930
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003931 // Find the constructor (which may be a template).
3932 CXXConstructorDecl *Constructor = 0;
3933 FunctionTemplateDecl *ConstructorTmpl
3934 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003935 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003936 Constructor = cast<CXXConstructorDecl>(
3937 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003938 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003939 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003940
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003941 if (!Constructor->isInvalidDecl() &&
3942 Constructor->isConvertingConstructor(AllowExplicit)) {
3943 if (ConstructorTmpl)
3944 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3945 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003946 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003947 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003948 else
3949 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003950 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003951 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003952 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003953 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003954 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003955 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003956
3957 SourceLocation DeclLoc = Initializer->getLocStart();
3958
Douglas Gregor4a520a22009-12-14 17:27:33 +00003959 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3960 // The type we're converting from is a class type, enumerate its conversion
3961 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003962
Eli Friedman33c2da92009-12-20 22:12:03 +00003963 // We can only enumerate the conversion functions for a complete type; if
3964 // the type isn't complete, simply skip this step.
3965 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3966 CXXRecordDecl *SourceRecordDecl
3967 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003968
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003969 std::pair<CXXRecordDecl::conversion_iterator,
3970 CXXRecordDecl::conversion_iterator>
3971 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3972 for (CXXRecordDecl::conversion_iterator
3973 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003974 NamedDecl *D = *I;
3975 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3976 if (isa<UsingShadowDecl>(D))
3977 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003978
Eli Friedman33c2da92009-12-20 22:12:03 +00003979 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3980 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003981 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003982 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003983 else
John McCall32daa422010-03-31 01:36:47 +00003984 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003985
Eli Friedman33c2da92009-12-20 22:12:03 +00003986 if (AllowExplicit || !Conv->isExplicit()) {
3987 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003988 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003989 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003990 CandidateSet);
3991 else
John McCall9aa472c2010-03-19 07:35:19 +00003992 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003993 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003994 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003995 }
3996 }
3997 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003998
3999 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004000 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004001 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004002 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004003 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004004 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004005 Result);
4006 return;
4007 }
John McCall1d318332010-01-12 00:44:57 +00004008
Douglas Gregor4a520a22009-12-14 17:27:33 +00004009 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004010 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004011 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004012
Douglas Gregor4a520a22009-12-14 17:27:33 +00004013 if (isa<CXXConstructorDecl>(Function)) {
4014 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004015 // subsumed by the initialization. Per DR5, the created temporary is of the
4016 // cv-unqualified type of the destination.
4017 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4018 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004019 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004020 return;
4021 }
4022
4023 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004024 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004025 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004026 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004027 // the resulting temporary object (possible to create an object of
4028 // a base class type). That copy is not a separate conversion, so
4029 // we just make a note of the actual destination type (possibly a
4030 // base class of the type returned by the conversion function) and
4031 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004032 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4033 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004034 return;
4035 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004036
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004037 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4038 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004039
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004040 // If the conversion following the call to the conversion function
4041 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004042 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4043 Best->FinalConversion.Third) {
4044 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004045 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004046 ICS.Standard = Best->FinalConversion;
4047 Sequence.AddConversionSequenceStep(ICS, DestType);
4048 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004049}
4050
John McCallf85e1932011-06-15 23:02:42 +00004051/// The non-zero enum values here are indexes into diagnostic alternatives.
4052enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4053
4054/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004055static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004056 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004057 // Skip parens.
4058 e = e->IgnoreParens();
4059
4060 // Skip address-of nodes.
4061 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4062 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004063 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4064 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004065
4066 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004067 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4068 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004069 case CK_Dependent:
4070 case CK_BitCast:
4071 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004072 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004073 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004074
4075 case CK_ArrayToPointerDecay:
4076 return IIK_nonscalar;
4077
4078 case CK_NullToPointer:
4079 return IIK_okay;
4080
4081 default:
4082 break;
4083 }
4084
4085 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004086 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004087 // set isWeakAccess to true, to mean that there will be an implicit
4088 // load which requires a cleanup.
4089 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4090 isWeakAccess = true;
4091
John McCallc03fa492011-06-27 23:59:58 +00004092 if (!isAddressOf) return IIK_nonlocal;
4093
John McCallf4b88a42012-03-10 09:33:50 +00004094 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4095 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004096
4097 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004098
4099 // If we have a conditional operator, check both sides.
4100 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004101 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4102 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004103 return iik;
4104
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004105 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004106
4107 // These are never scalar.
4108 } else if (isa<ArraySubscriptExpr>(e)) {
4109 return IIK_nonscalar;
4110
4111 // Otherwise, it needs to be a null pointer constant.
4112 } else {
4113 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4114 ? IIK_okay : IIK_nonlocal);
4115 }
4116
4117 return IIK_nonlocal;
4118}
4119
4120/// Check whether the given expression is a valid operand for an
4121/// indirect copy/restore.
4122static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4123 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004124 bool isWeakAccess = false;
4125 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4126 // If isWeakAccess to true, there will be an implicit
4127 // load which requires a cleanup.
4128 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4129 S.ExprNeedsCleanups = true;
4130
John McCallf85e1932011-06-15 23:02:42 +00004131 if (iik == IIK_okay) return;
4132
4133 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4134 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4135 << src->getSourceRange();
4136}
4137
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004138/// \brief Determine whether we have compatible array types for the
4139/// purposes of GNU by-copy array initialization.
4140static bool hasCompatibleArrayTypes(ASTContext &Context,
4141 const ArrayType *Dest,
4142 const ArrayType *Source) {
4143 // If the source and destination array types are equivalent, we're
4144 // done.
4145 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4146 return true;
4147
4148 // Make sure that the element types are the same.
4149 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4150 return false;
4151
4152 // The only mismatch we allow is when the destination is an
4153 // incomplete array type and the source is a constant array type.
4154 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4155}
4156
John McCallf85e1932011-06-15 23:02:42 +00004157static bool tryObjCWritebackConversion(Sema &S,
4158 InitializationSequence &Sequence,
4159 const InitializedEntity &Entity,
4160 Expr *Initializer) {
4161 bool ArrayDecay = false;
4162 QualType ArgType = Initializer->getType();
4163 QualType ArgPointee;
4164 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4165 ArrayDecay = true;
4166 ArgPointee = ArgArrayType->getElementType();
4167 ArgType = S.Context.getPointerType(ArgPointee);
4168 }
4169
4170 // Handle write-back conversion.
4171 QualType ConvertedArgType;
4172 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4173 ConvertedArgType))
4174 return false;
4175
4176 // We should copy unless we're passing to an argument explicitly
4177 // marked 'out'.
4178 bool ShouldCopy = true;
4179 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4180 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4181
4182 // Do we need an lvalue conversion?
4183 if (ArrayDecay || Initializer->isGLValue()) {
4184 ImplicitConversionSequence ICS;
4185 ICS.setStandard();
4186 ICS.Standard.setAsIdentityConversion();
4187
4188 QualType ResultType;
4189 if (ArrayDecay) {
4190 ICS.Standard.First = ICK_Array_To_Pointer;
4191 ResultType = S.Context.getPointerType(ArgPointee);
4192 } else {
4193 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4194 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4195 }
4196
4197 Sequence.AddConversionSequenceStep(ICS, ResultType);
4198 }
4199
4200 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4201 return true;
4202}
4203
Guy Benyei21f18c42013-02-07 10:55:47 +00004204static bool TryOCLSamplerInitialization(Sema &S,
4205 InitializationSequence &Sequence,
4206 QualType DestType,
4207 Expr *Initializer) {
4208 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4209 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4210 return false;
4211
4212 Sequence.AddOCLSamplerInitStep(DestType);
4213 return true;
4214}
4215
Guy Benyeie6b9d802013-01-20 12:31:11 +00004216//
4217// OpenCL 1.2 spec, s6.12.10
4218//
4219// The event argument can also be used to associate the
4220// async_work_group_copy with a previous async copy allowing
4221// an event to be shared by multiple async copies; otherwise
4222// event should be zero.
4223//
4224static bool TryOCLZeroEventInitialization(Sema &S,
4225 InitializationSequence &Sequence,
4226 QualType DestType,
4227 Expr *Initializer) {
4228 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4229 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4230 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4231 return false;
4232
4233 Sequence.AddOCLZeroEventStep(DestType);
4234 return true;
4235}
4236
Douglas Gregor20093b42009-12-09 23:02:17 +00004237InitializationSequence::InitializationSequence(Sema &S,
4238 const InitializedEntity &Entity,
4239 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004240 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004241 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004242 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004243
John McCall76da55d2013-04-16 07:28:30 +00004244 // Eliminate non-overload placeholder types in the arguments. We
4245 // need to do this before checking whether types are dependent
4246 // because lowering a pseudo-object expression might well give us
4247 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004248 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004249 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4250 // FIXME: should we be doing this here?
4251 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4252 if (result.isInvalid()) {
4253 SetFailed(FK_PlaceholderType);
4254 return;
4255 }
4256 Args[I] = result.take();
4257 }
4258
Douglas Gregor20093b42009-12-09 23:02:17 +00004259 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004260 // The semantics of initializers are as follows. The destination type is
4261 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004262 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004264 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004265 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004266
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004267 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004268 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004269 SequenceKind = DependentSequence;
4270 return;
4271 }
4272
Sebastian Redl7491c492011-06-05 13:59:11 +00004273 // Almost everything is a normal sequence.
4274 setSequenceKind(NormalSequence);
4275
Douglas Gregor20093b42009-12-09 23:02:17 +00004276 QualType SourceType;
4277 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004278 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004279 Initializer = Args[0];
4280 if (!isa<InitListExpr>(Initializer))
4281 SourceType = Initializer->getType();
4282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004283
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004284 // - If the initializer is a (non-parenthesized) braced-init-list, the
4285 // object is list-initialized (8.5.4).
4286 if (Kind.getKind() != InitializationKind::IK_Direct) {
4287 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4288 TryListInitialization(S, Entity, Kind, InitList, *this);
4289 return;
4290 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004291 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292
Douglas Gregor20093b42009-12-09 23:02:17 +00004293 // - If the destination type is a reference type, see 8.5.3.
4294 if (DestType->isReferenceType()) {
4295 // C++0x [dcl.init.ref]p1:
4296 // A variable declared to be a T& or T&&, that is, "reference to type T"
4297 // (8.3.2), shall be initialized by an object, or function, of type T or
4298 // by an object that can be converted into a T.
4299 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004300 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004301 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004302 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004303 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004304 return;
4305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306
Douglas Gregor20093b42009-12-09 23:02:17 +00004307 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004308 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004309 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004310 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004311 return;
4312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004313
Douglas Gregor99a2e602009-12-16 01:38:02 +00004314 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004315 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004316 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004317 return;
4318 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004319
John McCallce6c9b72011-02-21 07:22:22 +00004320 // - If the destination type is an array of characters, an array of
4321 // char16_t, an array of char32_t, or an array of wchar_t, and the
4322 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004324 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004325 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004326 if (Initializer && isa<VariableArrayType>(DestAT)) {
4327 SetFailed(FK_VariableLengthArrayHasInitializer);
4328 return;
4329 }
4330
Hans Wennborg0ff50742013-05-15 11:03:04 +00004331 if (Initializer) {
4332 switch (IsStringInit(Initializer, DestAT, Context)) {
4333 case SIF_None:
4334 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4335 return;
4336 case SIF_NarrowStringIntoWideChar:
4337 SetFailed(FK_NarrowStringIntoWideCharArray);
4338 return;
4339 case SIF_WideStringIntoChar:
4340 SetFailed(FK_WideStringIntoCharArray);
4341 return;
4342 case SIF_IncompatWideStringIntoWideChar:
4343 SetFailed(FK_IncompatWideStringIntoWideChar);
4344 return;
4345 case SIF_Other:
4346 break;
4347 }
John McCallce6c9b72011-02-21 07:22:22 +00004348 }
4349
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004350 // Note: as an GNU C extension, we allow initialization of an
4351 // array from a compound literal that creates an array of the same
4352 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004353 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004354 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4355 Initializer->getType()->isArrayType()) {
4356 const ArrayType *SourceAT
4357 = Context.getAsArrayType(Initializer->getType());
4358 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004359 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004360 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004361 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004362 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004363 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004364 }
Richard Smith0f163e92012-02-15 22:38:09 +00004365 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004366 // Note: as a GNU C++ extension, we allow list-initialization of a
4367 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004368 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004369 Entity.getKind() == InitializedEntity::EK_Member &&
4370 Initializer && isa<InitListExpr>(Initializer)) {
4371 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4372 *this);
4373 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004374 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004375 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004376 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4377 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004378 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004379 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004380
Douglas Gregor20093b42009-12-09 23:02:17 +00004381 return;
4382 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004383
John McCallf85e1932011-06-15 23:02:42 +00004384 // Determine whether we should consider writeback conversions for
4385 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004386 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004387 Entity.getKind() == InitializedEntity::EK_Parameter;
4388
4389 // We're at the end of the line for C: it's either a write-back conversion
4390 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004391 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004392 // If allowed, check whether this is an Objective-C writeback conversion.
4393 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004394 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004395 return;
4396 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004397
4398 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4399 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004400
4401 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4402 return;
4403
John McCallf85e1932011-06-15 23:02:42 +00004404 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004405 AddCAssignmentStep(DestType);
4406 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004407 return;
4408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004409
David Blaikie4e4d0842012-03-11 07:00:24 +00004410 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004411
Douglas Gregor20093b42009-12-09 23:02:17 +00004412 // - If the destination type is a (possibly cv-qualified) class type:
4413 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004414 // - If the initialization is direct-initialization, or if it is
4415 // copy-initialization where the cv-unqualified version of the
4416 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004417 // class of the destination, constructors are considered. [...]
4418 if (Kind.getKind() == InitializationKind::IK_Direct ||
4419 (Kind.getKind() == InitializationKind::IK_Copy &&
4420 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4421 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004422 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004423 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004424 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004425 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004426 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004427 // used) to a derived class thereof are enumerated as described in
4428 // 13.3.1.4, and the best one is chosen through overload resolution
4429 // (13.3).
4430 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004431 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004432 return;
4433 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004435 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004436 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004437 return;
4438 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004439 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004440
4441 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004442 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004443 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004444 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4445 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004446 return;
4447 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004448
Douglas Gregor20093b42009-12-09 23:02:17 +00004449 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004450 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004451 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004452 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004453 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004454
4455 ImplicitConversionSequence ICS
4456 = S.TryImplicitConversion(Initializer, Entity.getType(),
4457 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004458 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004459 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004460 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4461 allowObjCWritebackConversion);
4462
4463 if (ICS.isStandard() &&
4464 ICS.Standard.Second == ICK_Writeback_Conversion) {
4465 // Objective-C ARC writeback conversion.
4466
4467 // We should copy unless we're passing to an argument explicitly
4468 // marked 'out'.
4469 bool ShouldCopy = true;
4470 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4471 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4472
4473 // If there was an lvalue adjustment, add it as a separate conversion.
4474 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4475 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4476 ImplicitConversionSequence LvalueICS;
4477 LvalueICS.setStandard();
4478 LvalueICS.Standard.setAsIdentityConversion();
4479 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4480 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004481 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004482 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004483
4484 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004485 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004486 DeclAccessPair dap;
4487 if (Initializer->getType() == Context.OverloadTy &&
4488 !S.ResolveAddressOfOverloadedFunction(Initializer
4489 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004490 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004491 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004492 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004493 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004494 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004495
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004496 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004497 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004498}
4499
4500InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004501 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004502 StepEnd = Steps.end();
4503 Step != StepEnd; ++Step)
4504 Step->Destroy();
4505}
4506
4507//===----------------------------------------------------------------------===//
4508// Perform initialization
4509//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004511getAssignmentAction(const InitializedEntity &Entity) {
4512 switch(Entity.getKind()) {
4513 case InitializedEntity::EK_Variable:
4514 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004515 case InitializedEntity::EK_Exception:
4516 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004517 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004518 return Sema::AA_Initializing;
4519
4520 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004521 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004522 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4523 return Sema::AA_Sending;
4524
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004525 return Sema::AA_Passing;
4526
4527 case InitializedEntity::EK_Result:
4528 return Sema::AA_Returning;
4529
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004530 case InitializedEntity::EK_Temporary:
4531 // FIXME: Can we tell apart casting vs. converting?
4532 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004533
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004534 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004535 case InitializedEntity::EK_ArrayElement:
4536 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004537 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004538 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004539 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004540 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004541 return Sema::AA_Initializing;
4542 }
4543
David Blaikie7530c032012-01-17 06:56:22 +00004544 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004545}
4546
Richard Smith774d8b42013-01-08 00:08:23 +00004547/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004548/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004549static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004550 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004551 case InitializedEntity::EK_ArrayElement:
4552 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004553 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004554 case InitializedEntity::EK_New:
4555 case InitializedEntity::EK_Variable:
4556 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004557 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004558 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004559 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004560 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004561 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004562 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004563 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004564 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004566 case InitializedEntity::EK_Parameter:
4567 case InitializedEntity::EK_Temporary:
4568 return true;
4569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004570
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004571 llvm_unreachable("missed an InitializedEntity kind?");
4572}
4573
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004574/// \brief Whether the given entity, when initialized with an object
4575/// created for that initialization, requires destruction.
4576static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4577 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004578 case InitializedEntity::EK_Result:
4579 case InitializedEntity::EK_New:
4580 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004581 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004582 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004583 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004584 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004585 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004586 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004587
Richard Smith774d8b42013-01-08 00:08:23 +00004588 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004589 case InitializedEntity::EK_Variable:
4590 case InitializedEntity::EK_Parameter:
4591 case InitializedEntity::EK_Temporary:
4592 case InitializedEntity::EK_ArrayElement:
4593 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004594 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004595 return true;
4596 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004597
4598 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004599}
4600
Richard Smith83da2e72011-10-19 16:55:56 +00004601/// \brief Look for copy and move constructors and constructor templates, for
4602/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4603static void LookupCopyAndMoveConstructors(Sema &S,
4604 OverloadCandidateSet &CandidateSet,
4605 CXXRecordDecl *Class,
4606 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004607 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004608 // The container holding the constructors can under certain conditions
4609 // be changed while iterating (e.g. because of deserialization).
4610 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004611 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004612 for (SmallVector<NamedDecl*, 16>::iterator
4613 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4614 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004615 CXXConstructorDecl *Constructor = 0;
4616
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004617 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004618 // Handle copy/moveconstructors, only.
4619 if (!Constructor || Constructor->isInvalidDecl() ||
4620 !Constructor->isCopyOrMoveConstructor() ||
4621 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4622 continue;
4623
4624 DeclAccessPair FoundDecl
4625 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4626 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004627 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004628 continue;
4629 }
4630
4631 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004632 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004633 if (ConstructorTmpl->isInvalidDecl())
4634 continue;
4635
4636 Constructor = cast<CXXConstructorDecl>(
4637 ConstructorTmpl->getTemplatedDecl());
4638 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4639 continue;
4640
4641 // FIXME: Do we need to limit this to copy-constructor-like
4642 // candidates?
4643 DeclAccessPair FoundDecl
4644 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4645 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004646 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004647 }
4648}
4649
4650/// \brief Get the location at which initialization diagnostics should appear.
4651static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4652 Expr *Initializer) {
4653 switch (Entity.getKind()) {
4654 case InitializedEntity::EK_Result:
4655 return Entity.getReturnLoc();
4656
4657 case InitializedEntity::EK_Exception:
4658 return Entity.getThrowLoc();
4659
4660 case InitializedEntity::EK_Variable:
4661 return Entity.getDecl()->getLocation();
4662
Douglas Gregor47736542012-02-15 16:57:26 +00004663 case InitializedEntity::EK_LambdaCapture:
4664 return Entity.getCaptureLoc();
4665
Richard Smith83da2e72011-10-19 16:55:56 +00004666 case InitializedEntity::EK_ArrayElement:
4667 case InitializedEntity::EK_Member:
4668 case InitializedEntity::EK_Parameter:
4669 case InitializedEntity::EK_Temporary:
4670 case InitializedEntity::EK_New:
4671 case InitializedEntity::EK_Base:
4672 case InitializedEntity::EK_Delegating:
4673 case InitializedEntity::EK_VectorElement:
4674 case InitializedEntity::EK_ComplexElement:
4675 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004676 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith83da2e72011-10-19 16:55:56 +00004677 return Initializer->getLocStart();
4678 }
4679 llvm_unreachable("missed an InitializedEntity kind?");
4680}
4681
Douglas Gregor523d46a2010-04-18 07:40:54 +00004682/// \brief Make a (potentially elidable) temporary copy of the object
4683/// provided by the given initializer by calling the appropriate copy
4684/// constructor.
4685///
4686/// \param S The Sema object used for type-checking.
4687///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004688/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004689/// the type of the initializer expression or a superclass thereof.
4690///
James Dennett1dfbd922012-06-14 21:40:34 +00004691/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004692///
4693/// \param CurInit The initializer expression.
4694///
4695/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4696/// is permitted in C++03 (but not C++0x) when binding a reference to
4697/// an rvalue.
4698///
4699/// \returns An expression that copies the initializer expression into
4700/// a temporary object, or an error expression if a copy could not be
4701/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004702static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004703 QualType T,
4704 const InitializedEntity &Entity,
4705 ExprResult CurInit,
4706 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004707 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004708 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004709 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004710 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004711 Class = cast<CXXRecordDecl>(Record->getDecl());
4712 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004713 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004714
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004715 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004716 // When certain criteria are met, an implementation is allowed to
4717 // omit the copy/move construction of a class object, even if the
4718 // copy/move constructor and/or destructor for the object have
4719 // side effects. [...]
4720 // - when a temporary class object that has not been bound to a
4721 // reference (12.2) would be copied/moved to a class object
4722 // with the same cv-unqualified type, the copy/move operation
4723 // can be omitted by constructing the temporary object
4724 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004725 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004726 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004727 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004729 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004730 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004731 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004732
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004733 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004734 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004735 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004736
Douglas Gregorcc15f012011-01-21 19:38:21 +00004737 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004738 // Only consider constructors and constructor templates. Per
4739 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4740 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004741 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004742 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004743
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004744 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4745
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004746 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004747 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004748 case OR_Success:
4749 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004751 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004752 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4753 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4754 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004755 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004756 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004757 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004758 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004759 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004760 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004761
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004762 case OR_Ambiguous:
4763 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004764 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004765 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004766 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004767 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004768
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004769 case OR_Deleted:
4770 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004771 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004772 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004773 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004774 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004775 }
4776
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004777 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004778 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004779 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004780
Anders Carlsson9a68a672010-04-21 18:47:17 +00004781 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004782 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004783
4784 if (IsExtraneousCopy) {
4785 // If this is a totally extraneous copy for C++03 reference
4786 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004787 // expression. We don't generate an (elided) copy operation here
4788 // because doing so would require us to pass down a flag to avoid
4789 // infinite recursion, where each step adds another extraneous,
4790 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004791
Douglas Gregor2559a702010-04-18 07:57:34 +00004792 // Instantiate the default arguments of any extra parameters in
4793 // the selected copy constructor, as if we were going to create a
4794 // proper call to the copy constructor.
4795 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4796 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4797 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004798 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004799 break;
4800
4801 // Build the default argument expression; we don't actually care
4802 // if this succeeds or not, because this routine will complain
4803 // if there was a problem.
4804 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4805 }
4806
Douglas Gregor523d46a2010-04-18 07:40:54 +00004807 return S.Owned(CurInitExpr);
4808 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004809
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004810 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004811 // constructor call (we might have derived-to-base conversions, or
4812 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004813 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004814 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004815
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004816 // Actually perform the constructor call.
4817 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004818 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004819 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004820 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004821 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004822 CXXConstructExpr::CK_Complete,
4823 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004824
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004825 // If we're supposed to bind temporaries, do so.
4826 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4827 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004828 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004829}
Douglas Gregor20093b42009-12-09 23:02:17 +00004830
Richard Smith83da2e72011-10-19 16:55:56 +00004831/// \brief Check whether elidable copy construction for binding a reference to
4832/// a temporary would have succeeded if we were building in C++98 mode, for
4833/// -Wc++98-compat.
4834static void CheckCXX98CompatAccessibleCopy(Sema &S,
4835 const InitializedEntity &Entity,
4836 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004837 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004838
4839 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4840 if (!Record)
4841 return;
4842
4843 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4844 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4845 == DiagnosticsEngine::Ignored)
4846 return;
4847
4848 // Find constructors which would have been considered.
4849 OverloadCandidateSet CandidateSet(Loc);
4850 LookupCopyAndMoveConstructors(
4851 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4852
4853 // Perform overload resolution.
4854 OverloadCandidateSet::iterator Best;
4855 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4856
4857 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4858 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4859 << CurInitExpr->getSourceRange();
4860
4861 switch (OR) {
4862 case OR_Success:
4863 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004864 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004865 // FIXME: Check default arguments as far as that's possible.
4866 break;
4867
4868 case OR_No_Viable_Function:
4869 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004870 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004871 break;
4872
4873 case OR_Ambiguous:
4874 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004875 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004876 break;
4877
4878 case OR_Deleted:
4879 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004880 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004881 break;
4882 }
4883}
4884
Douglas Gregora41a8c52010-04-22 00:20:18 +00004885void InitializationSequence::PrintInitLocationNote(Sema &S,
4886 const InitializedEntity &Entity) {
4887 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4888 if (Entity.getDecl()->getLocation().isInvalid())
4889 return;
4890
4891 if (Entity.getDecl()->getDeclName())
4892 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4893 << Entity.getDecl()->getDeclName();
4894 else
4895 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4896 }
4897}
4898
Sebastian Redl3b802322011-07-14 19:07:55 +00004899static bool isReferenceBinding(const InitializationSequence::Step &s) {
4900 return s.Kind == InitializationSequence::SK_BindReference ||
4901 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4902}
4903
Jordan Rose2624b812013-05-06 16:48:12 +00004904/// Returns true if the parameters describe a constructor initialization of
4905/// an explicit temporary object, e.g. "Point(x, y)".
4906static bool isExplicitTemporary(const InitializedEntity &Entity,
4907 const InitializationKind &Kind,
4908 unsigned NumArgs) {
4909 switch (Entity.getKind()) {
4910 case InitializedEntity::EK_Temporary:
4911 case InitializedEntity::EK_CompoundLiteralInit:
4912 break;
4913 default:
4914 return false;
4915 }
4916
4917 switch (Kind.getKind()) {
4918 case InitializationKind::IK_DirectList:
4919 return true;
4920 // FIXME: Hack to work around cast weirdness.
4921 case InitializationKind::IK_Direct:
4922 case InitializationKind::IK_Value:
4923 return NumArgs != 1;
4924 default:
4925 return false;
4926 }
4927}
4928
Sebastian Redl10f04a62011-12-22 14:44:04 +00004929static ExprResult
4930PerformConstructorInitialization(Sema &S,
4931 const InitializedEntity &Entity,
4932 const InitializationKind &Kind,
4933 MultiExprArg Args,
4934 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004935 bool &ConstructorInitRequiresZeroInit,
4936 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004937 unsigned NumArgs = Args.size();
4938 CXXConstructorDecl *Constructor
4939 = cast<CXXConstructorDecl>(Step.Function.Function);
4940 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4941
4942 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004943 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004944 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4945 ? Kind.getEqualLoc()
4946 : Kind.getLocation();
4947
4948 if (Kind.getKind() == InitializationKind::IK_Default) {
4949 // Force even a trivial, implicit default constructor to be
4950 // semantically checked. We do this explicitly because we don't build
4951 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004952 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004953 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004954 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004955 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4956 }
4957
4958 ExprResult CurInit = S.Owned((Expr *)0);
4959
Douglas Gregored878af2012-02-24 23:56:31 +00004960 // C++ [over.match.copy]p1:
4961 // - When initializing a temporary to be bound to the first parameter
4962 // of a constructor that takes a reference to possibly cv-qualified
4963 // T as its first argument, called with a single argument in the
4964 // context of direct-initialization, explicit conversion functions
4965 // are also considered.
4966 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4967 Args.size() == 1 &&
4968 Constructor->isCopyOrMoveConstructor();
4969
Sebastian Redl10f04a62011-12-22 14:44:04 +00004970 // Determine the arguments required to actually perform the constructor
4971 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004972 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004973 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004974 AllowExplicitConv,
4975 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004976 return ExprError();
4977
4978
Jordan Rose2624b812013-05-06 16:48:12 +00004979 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004980 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004981 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00004982 if (S.DiagnoseUseOfDecl(Constructor, Loc))
4983 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004984
4985 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4986 if (!TSInfo)
4987 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004988 SourceRange ParenRange;
4989 if (Kind.getKind() != InitializationKind::IK_DirectList)
4990 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004991
Richard Smithc83c2302012-12-19 01:39:02 +00004992 CurInit = S.Owned(
4993 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4994 TSInfo, ConstructorArgs,
4995 ParenRange, IsListInitialization,
4996 HadMultipleCandidates,
4997 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00004998 } else {
4999 CXXConstructExpr::ConstructionKind ConstructKind =
5000 CXXConstructExpr::CK_Complete;
5001
5002 if (Entity.getKind() == InitializedEntity::EK_Base) {
5003 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5004 CXXConstructExpr::CK_VirtualBase :
5005 CXXConstructExpr::CK_NonVirtualBase;
5006 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5007 ConstructKind = CXXConstructExpr::CK_Delegating;
5008 }
5009
5010 // Only get the parenthesis range if it is a direct construction.
5011 SourceRange parenRange =
5012 Kind.getKind() == InitializationKind::IK_Direct ?
5013 Kind.getParenRange() : SourceRange();
5014
5015 // If the entity allows NRVO, mark the construction as elidable
5016 // unconditionally.
5017 if (Entity.allowsNRVO())
5018 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5019 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005020 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005021 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005022 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005023 ConstructorInitRequiresZeroInit,
5024 ConstructKind,
5025 parenRange);
5026 else
5027 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5028 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005029 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005030 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005031 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005032 ConstructorInitRequiresZeroInit,
5033 ConstructKind,
5034 parenRange);
5035 }
5036 if (CurInit.isInvalid())
5037 return ExprError();
5038
5039 // Only check access if all of that succeeded.
5040 S.CheckConstructorAccess(Loc, Constructor, Entity,
5041 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005042 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5043 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005044
5045 if (shouldBindAsTemporary(Entity))
5046 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5047
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005048 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005049}
5050
Richard Smith36d02af2012-06-04 22:27:30 +00005051/// Determine whether the specified InitializedEntity definitely has a lifetime
5052/// longer than the current full-expression. Conservatively returns false if
5053/// it's unclear.
5054static bool
5055InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5056 const InitializedEntity *Top = &Entity;
5057 while (Top->getParent())
5058 Top = Top->getParent();
5059
5060 switch (Top->getKind()) {
5061 case InitializedEntity::EK_Variable:
5062 case InitializedEntity::EK_Result:
5063 case InitializedEntity::EK_Exception:
5064 case InitializedEntity::EK_Member:
5065 case InitializedEntity::EK_New:
5066 case InitializedEntity::EK_Base:
5067 case InitializedEntity::EK_Delegating:
5068 return true;
5069
5070 case InitializedEntity::EK_ArrayElement:
5071 case InitializedEntity::EK_VectorElement:
5072 case InitializedEntity::EK_BlockElement:
5073 case InitializedEntity::EK_ComplexElement:
5074 // Could not determine what the full initialization is. Assume it might not
5075 // outlive the full-expression.
5076 return false;
5077
5078 case InitializedEntity::EK_Parameter:
5079 case InitializedEntity::EK_Temporary:
5080 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005081 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith36d02af2012-06-04 22:27:30 +00005082 // The entity being initialized might not outlive the full-expression.
5083 return false;
5084 }
5085
5086 llvm_unreachable("unknown entity kind");
5087}
5088
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005089ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005090InitializationSequence::Perform(Sema &S,
5091 const InitializedEntity &Entity,
5092 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005093 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005094 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005095 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005096 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005097 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005098 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005099
Sebastian Redl7491c492011-06-05 13:59:11 +00005100 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005101 // If the declaration is a non-dependent, incomplete array type
5102 // that has an initializer, then its type will be completed once
5103 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005104 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005105 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005106 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005107 if (const IncompleteArrayType *ArrayT
5108 = S.Context.getAsIncompleteArrayType(DeclType)) {
5109 // FIXME: We don't currently have the ability to accurately
5110 // compute the length of an initializer list without
5111 // performing full type-checking of the initializer list
5112 // (since we have to determine where braces are implicitly
5113 // introduced and such). So, we fall back to making the array
5114 // type a dependently-sized array type with no specified
5115 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005116 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005117 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005118
Douglas Gregord87b61f2009-12-10 17:56:55 +00005119 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005120 if (DeclaratorDecl *DD = Entity.getDecl()) {
5121 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5122 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005123 if (IncompleteArrayTypeLoc ArrayLoc =
5124 TL.getAs<IncompleteArrayTypeLoc>())
5125 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005126 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005127 }
5128
5129 *ResultType
5130 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5131 /*NumElts=*/0,
5132 ArrayT->getSizeModifier(),
5133 ArrayT->getIndexTypeCVRQualifiers(),
5134 Brackets);
5135 }
5136
5137 }
5138 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005139 if (Kind.getKind() == InitializationKind::IK_Direct &&
5140 !Kind.isExplicitCast()) {
5141 // Rebuild the ParenListExpr.
5142 SourceRange ParenRange = Kind.getParenRange();
5143 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005144 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005145 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005146 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005147 Kind.isExplicitCast() ||
5148 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005149 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005150 }
5151
Sebastian Redl7491c492011-06-05 13:59:11 +00005152 // No steps means no initialization.
5153 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005154 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005155
Richard Smith80ad52f2013-01-02 11:42:31 +00005156 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005157 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005158 Entity.getKind() != InitializedEntity::EK_Parameter) {
5159 // Produce a C++98 compatibility warning if we are initializing a reference
5160 // from an initializer list. For parameters, we produce a better warning
5161 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005162 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005163 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5164 << Init->getSourceRange();
5165 }
5166
Richard Smith36d02af2012-06-04 22:27:30 +00005167 // Diagnose cases where we initialize a pointer to an array temporary, and the
5168 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005169 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005170 Entity.getType()->isPointerType() &&
5171 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005172 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005173 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5174 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5175 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5176 << Init->getSourceRange();
5177 }
5178
Douglas Gregord6542d82009-12-22 15:35:07 +00005179 QualType DestType = Entity.getType().getNonReferenceType();
5180 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005181 // the same as Entity.getDecl()->getType() in cases involving type merging,
5182 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005183 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005184 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005185 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005186
John McCall60d7b3a2010-08-24 06:29:42 +00005187 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005188
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005189 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005190 // grab the only argument out the Args and place it into the "current"
5191 // initializer.
5192 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005193 case SK_ResolveAddressOfOverloadedFunction:
5194 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005195 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005196 case SK_CastDerivedToBaseLValue:
5197 case SK_BindReference:
5198 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005199 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005200 case SK_UserConversion:
5201 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005202 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005203 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005204 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005205 case SK_ConversionSequence:
5206 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005207 case SK_UnwrapInitList:
5208 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005209 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005210 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005211 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005212 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005213 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005214 case SK_PassByIndirectCopyRestore:
5215 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005216 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005217 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005218 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005219 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005220 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005221 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005222 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005223 break;
John McCallf6a16482010-12-04 03:47:34 +00005224 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005225
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005226 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005227 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005228 case SK_ZeroInitialization:
5229 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005230 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005231
5232 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005233 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005234 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005235 for (step_iterator Step = step_begin(), StepEnd = step_end();
5236 Step != StepEnd; ++Step) {
5237 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005238 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005239
John Wiegley429bb272011-04-08 18:41:53 +00005240 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005241
Douglas Gregor20093b42009-12-09 23:02:17 +00005242 switch (Step->Kind) {
5243 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005244 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005245 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005246 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005247 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5248 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005249 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005250 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005251 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005252 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005253
Douglas Gregor20093b42009-12-09 23:02:17 +00005254 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005255 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005256 case SK_CastDerivedToBaseLValue: {
5257 // We have a derived-to-base cast that produces either an rvalue or an
5258 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005259
John McCallf871d0c2010-08-07 06:22:56 +00005260 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005261
Douglas Gregor20093b42009-12-09 23:02:17 +00005262 // Casts to inaccessible base classes are allowed with C-style casts.
5263 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5264 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005265 CurInit.get()->getLocStart(),
5266 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005267 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005268 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005269
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005270 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5271 QualType T = SourceType;
5272 if (const PointerType *Pointer = T->getAs<PointerType>())
5273 T = Pointer->getPointeeType();
5274 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005275 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005276 cast<CXXRecordDecl>(RecordTy->getDecl()));
5277 }
5278
John McCall5baba9d2010-08-25 10:28:54 +00005279 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005280 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005281 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005282 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005283 VK_XValue :
5284 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005285 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5286 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005287 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005288 CurInit.get(),
5289 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005290 break;
5291 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005292
Douglas Gregor20093b42009-12-09 23:02:17 +00005293 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005294 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5295 if (CurInit.get()->refersToBitField()) {
5296 // We don't necessarily have an unambiguous source bit-field.
5297 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005298 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005299 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005300 << (BitField ? BitField->getDeclName() : DeclarationName())
5301 << (BitField != NULL)
John Wiegley429bb272011-04-08 18:41:53 +00005302 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005303 if (BitField)
5304 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5305
John McCallf312b1e2010-08-26 23:41:50 +00005306 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005307 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005308
John Wiegley429bb272011-04-08 18:41:53 +00005309 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005310 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005311 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5312 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005313 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005314 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005315 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005316 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005317
Douglas Gregor20093b42009-12-09 23:02:17 +00005318 // Reference binding does not have any corresponding ASTs.
5319
5320 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005321 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005322 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005323
Douglas Gregor20093b42009-12-09 23:02:17 +00005324 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005325
Douglas Gregor20093b42009-12-09 23:02:17 +00005326 case SK_BindReferenceToTemporary:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005327 // Make sure the "temporary" is actually an rvalue.
5328 assert(CurInit.get()->isRValue() && "not a temporary");
5329
Douglas Gregor20093b42009-12-09 23:02:17 +00005330 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005331 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005332 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005333
Douglas Gregor03e80032011-06-21 17:03:29 +00005334 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005335 CurInit = new (S.Context) MaterializeTemporaryExpr(
5336 Entity.getType().getNonReferenceType(),
5337 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005338 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005339
5340 // If we're binding to an Objective-C object that has lifetime, we
5341 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005342 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005343 CurInit.get()->getType()->isObjCLifetimeType())
5344 S.ExprNeedsCleanups = true;
5345
Douglas Gregor20093b42009-12-09 23:02:17 +00005346 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005347
Douglas Gregor523d46a2010-04-18 07:40:54 +00005348 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005349 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005350 /*IsExtraneousCopy=*/true);
5351 break;
5352
Douglas Gregor20093b42009-12-09 23:02:17 +00005353 case SK_UserConversion: {
5354 // We have a user-defined conversion that invokes either a constructor
5355 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005356 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005357 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005358 FunctionDecl *Fn = Step->Function.Function;
5359 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005360 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005361 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005362 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005363 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005364 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005365 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005366 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005367
Douglas Gregor20093b42009-12-09 23:02:17 +00005368 // Determine the arguments required to actually perform the constructor
5369 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005370 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005371 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005372 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005373 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005374 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005375
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005376 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005377 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005378 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005379 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005380 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005381 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005382 CXXConstructExpr::CK_Complete,
5383 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005384 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005385 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005386
Anders Carlsson9a68a672010-04-21 18:47:17 +00005387 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005388 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005389 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5390 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005391
John McCall2de56d12010-08-25 11:45:40 +00005392 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005393 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5394 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5395 S.IsDerivedFrom(SourceType, Class))
5396 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005397
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005398 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005399 } else {
5400 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005401 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005402 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005403 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005404 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5405 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005406
5407 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005408 // derived-to-base conversion? I believe the answer is "no", because
5409 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005410 ExprResult CurInitExprRes =
5411 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5412 FoundFn, Conversion);
5413 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005414 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005415 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005416
Douglas Gregor20093b42009-12-09 23:02:17 +00005417 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005418 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5419 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005420 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005421 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005422
John McCall2de56d12010-08-25 11:45:40 +00005423 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005425 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005426 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005427
Sebastian Redl3b802322011-07-14 19:07:55 +00005428 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005429 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5430
5431 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005432 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005433 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005434 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005435 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005436 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005437 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005438 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005439 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5440 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005441 }
5442 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005443
John McCallf871d0c2010-08-07 06:22:56 +00005444 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005445 CurInit.get()->getType(),
5446 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005447 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005448 if (MaybeBindToTemp)
5449 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005450 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005451 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005452 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005453 break;
5454 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005455
Douglas Gregor20093b42009-12-09 23:02:17 +00005456 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005457 case SK_QualificationConversionXValue:
5458 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005459 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005460 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005461 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005462 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005463 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005464 VK_XValue :
5465 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005466 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005467 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005468 }
5469
Jordan Rose1fd1e282013-04-11 00:58:58 +00005470 case SK_LValueToRValue: {
5471 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5472 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5473 CK_LValueToRValue,
5474 CurInit.take(),
5475 /*BasePath=*/0,
5476 VK_RValue));
5477 break;
5478 }
5479
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005480 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005481 Sema::CheckedConversionKind CCK
5482 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5483 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005484 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005485 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005486 ExprResult CurInitExprRes =
5487 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005488 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005489 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005490 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005491 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005492 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005493 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005494
Douglas Gregord87b61f2009-12-10 17:56:55 +00005495 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005496 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005497 // Hack: We must pass *ResultType if available in order to set the type
5498 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5499 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5500 // temporary, not a reference, so we should pass Ty.
5501 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5502 // Since this step is never used for a reference directly, we explicitly
5503 // unwrap references here and rewrap them afterwards.
5504 // We also need to create a InitializeTemporary entity for this.
5505 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005506 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005507 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005508 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5509 InitListChecker PerformInitList(S, InitEntity,
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005510 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005511 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00005512 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005513 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005514 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005515
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005516 if (ResultType) {
5517 if ((*ResultType)->isRValueReferenceType())
5518 Ty = S.Context.getRValueReferenceType(Ty);
5519 else if ((*ResultType)->isLValueReferenceType())
5520 Ty = S.Context.getLValueReferenceType(Ty,
5521 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5522 *ResultType = Ty;
5523 }
5524
5525 InitListExpr *StructuredInitList =
5526 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005527 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005528 CurInit = shouldBindAsTemporary(InitEntity)
5529 ? S.MaybeBindToTemporary(StructuredInitList)
5530 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005531 break;
5532 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005533
Sebastian Redl10f04a62011-12-22 14:44:04 +00005534 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005535 // When an initializer list is passed for a parameter of type "reference
5536 // to object", we don't get an EK_Temporary entity, but instead an
5537 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005538 // FIXME: This is a hack. What we really should do is create a user
5539 // conversion step for this case, but this makes it considerably more
5540 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005541 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5542 Entity.getType().getNonReferenceType());
5543 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005544 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005545 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005546 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5547 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005548 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005549 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5550 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005551 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005552 ConstructorInitRequiresZeroInit,
5553 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005554 break;
5555 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005556
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005557 case SK_UnwrapInitList:
5558 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5559 break;
5560
5561 case SK_RewrapInitList: {
5562 Expr *E = CurInit.take();
5563 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5564 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005565 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005566 ILE->setSyntacticForm(Syntactic);
5567 ILE->setType(E->getType());
5568 ILE->setValueKind(E->getValueKind());
5569 CurInit = S.Owned(ILE);
5570 break;
5571 }
5572
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005573 case SK_ConstructorInitialization: {
5574 // When an initializer list is passed for a parameter of type "reference
5575 // to object", we don't get an EK_Temporary entity, but instead an
5576 // EK_Parameter entity with reference type.
5577 // FIXME: This is a hack. What we really should do is create a user
5578 // conversion step for this case, but this makes it considerably more
5579 // complicated. For now, this will do.
5580 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5581 Entity.getType().getNonReferenceType());
5582 bool UseTemporary = Entity.getType()->isReferenceType();
5583 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5584 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005585 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005586 ConstructorInitRequiresZeroInit,
5587 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005588 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005589 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005590
Douglas Gregor71d17402009-12-15 00:01:57 +00005591 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005592 step_iterator NextStep = Step;
5593 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005594 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005595 (NextStep->Kind == SK_ConstructorInitialization ||
5596 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005597 // The need for zero-initialization is recorded directly into
5598 // the call to the object's constructor within the next step.
5599 ConstructorInitRequiresZeroInit = true;
5600 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005601 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005602 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005603 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5604 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005605 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005606 Kind.getRange().getBegin());
5607
5608 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5609 TSInfo->getType().getNonLValueExprType(S.Context),
5610 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005611 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005612 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005613 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005614 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005615 break;
5616 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005617
5618 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005619 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005620 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005621 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005622 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5623 if (Result.isInvalid())
5624 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005625 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005626
5627 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005628 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005629 if (ConvTy != Sema::Compatible &&
5630 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005631 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005632 == Sema::Compatible)
5633 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005634 if (CurInitExprRes.isInvalid())
5635 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005636 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005637
Douglas Gregora41a8c52010-04-22 00:20:18 +00005638 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005639 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5640 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005641 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005642 getAssignmentAction(Entity),
5643 &Complained)) {
5644 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005645 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005646 } else if (Complained)
5647 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005648 break;
5649 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005650
5651 case SK_StringInit: {
5652 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005653 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005654 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005655 break;
5656 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005657
5658 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005659 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005660 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005661 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005662 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005663
5664 case SK_ArrayInit:
5665 // Okay: we checked everything before creating this step. Note that
5666 // this is a GNU extension.
5667 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005668 << Step->Type << CurInit.get()->getType()
5669 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005670
5671 // If the destination type is an incomplete array type, update the
5672 // type accordingly.
5673 if (ResultType) {
5674 if (const IncompleteArrayType *IncompleteDest
5675 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5676 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005677 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005678 *ResultType = S.Context.getConstantArrayType(
5679 IncompleteDest->getElementType(),
5680 ConstantSource->getSize(),
5681 ArrayType::Normal, 0);
5682 }
5683 }
5684 }
John McCallf85e1932011-06-15 23:02:42 +00005685 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005686
Richard Smith0f163e92012-02-15 22:38:09 +00005687 case SK_ParenthesizedArrayInit:
5688 // Okay: we checked everything before creating this step. Note that
5689 // this is a GNU extension.
5690 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5691 << CurInit.get()->getSourceRange();
5692 break;
5693
John McCallf85e1932011-06-15 23:02:42 +00005694 case SK_PassByIndirectCopyRestore:
5695 case SK_PassByIndirectRestore:
5696 checkIndirectCopyRestoreSource(S, CurInit.get());
5697 CurInit = S.Owned(new (S.Context)
5698 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5699 Step->Kind == SK_PassByIndirectCopyRestore));
5700 break;
5701
5702 case SK_ProduceObjCObject:
5703 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005704 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005705 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005706 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005707
5708 case SK_StdInitializerList: {
5709 QualType Dest = Step->Type;
5710 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005711 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005712 (void)Success;
5713 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005714
5715 // If the element type has a destructor, check it.
5716 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5717 if (!RD->hasIrrelevantDestructor()) {
5718 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5719 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5720 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5721 S.PDiag(diag::err_access_dtor_temp) << E);
Richard Smith82f145d2013-05-04 06:44:46 +00005722 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5723 return ExprError();
Sebastian Redl28357452012-03-05 19:35:43 +00005724 }
5725 }
5726 }
5727
Sebastian Redl2b916b82012-01-17 22:49:42 +00005728 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005729 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5730 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005731 unsigned NumInits = ILE->getNumInits();
5732 SmallVector<Expr*, 16> Converted(NumInits);
5733 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5734 S.Context.getConstantArrayType(E,
5735 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5736 NumInits),
5737 ArrayType::Normal, 0));
5738 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5739 0, HiddenArray);
5740 for (unsigned i = 0; i < NumInits; ++i) {
5741 Element.setElementIndex(i);
5742 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005743 ExprResult Res = S.PerformCopyInitialization(
5744 Element, Init.get()->getExprLoc(), Init,
5745 /*TopLevelOfInitList=*/ true);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005746 assert(!Res.isInvalid() && "Result changed since try phase.");
5747 Converted[i] = Res.take();
5748 }
5749 InitListExpr *Semantic = new (S.Context)
5750 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005751 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005752 Semantic->setSyntacticForm(ILE);
5753 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005754 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005755 CurInit = S.Owned(Semantic);
5756 break;
5757 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005758 case SK_OCLSamplerInit: {
5759 assert(Step->Type->isSamplerT() &&
5760 "Sampler initialization on non sampler type.");
5761
5762 QualType SourceType = CurInit.get()->getType();
5763 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5764
5765 if (EntityKind == InitializedEntity::EK_Parameter) {
5766 if (!SourceType->isSamplerT())
5767 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5768 << SourceType;
5769 } else if (EntityKind != InitializedEntity::EK_Variable) {
5770 llvm_unreachable("Invalid EntityKind!");
5771 }
5772
5773 break;
5774 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005775 case SK_OCLZeroEvent: {
5776 assert(Step->Type->isEventT() &&
5777 "Event initialization on non event type.");
5778
5779 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5780 CK_ZeroToOCLEvent,
5781 CurInit.get()->getValueKind());
5782 break;
5783 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005784 }
5785 }
John McCall15d7d122010-11-11 03:21:53 +00005786
5787 // Diagnose non-fatal problems with the completed initialization.
5788 if (Entity.getKind() == InitializedEntity::EK_Member &&
5789 cast<FieldDecl>(Entity.getDecl())->isBitField())
5790 S.CheckBitFieldInitialization(Kind.getLocation(),
5791 cast<FieldDecl>(Entity.getDecl()),
5792 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005793
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005794 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005795}
5796
Richard Smithd5bc8672012-12-08 02:01:17 +00005797/// Somewhere within T there is an uninitialized reference subobject.
5798/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005799static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5800 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005801 if (T->isReferenceType()) {
5802 S.Diag(Loc, diag::err_reference_without_init)
5803 << T.getNonReferenceType();
5804 return true;
5805 }
5806
5807 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5808 if (!RD || !RD->hasUninitializedReferenceMember())
5809 return false;
5810
5811 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5812 FE = RD->field_end(); FI != FE; ++FI) {
5813 if (FI->isUnnamedBitfield())
5814 continue;
5815
5816 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5817 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5818 return true;
5819 }
5820 }
5821
5822 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5823 BE = RD->bases_end();
5824 BI != BE; ++BI) {
5825 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5826 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5827 return true;
5828 }
5829 }
5830
5831 return false;
5832}
5833
5834
Douglas Gregor20093b42009-12-09 23:02:17 +00005835//===----------------------------------------------------------------------===//
5836// Diagnose initialization failures
5837//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00005838
5839/// Emit notes associated with an initialization that failed due to a
5840/// "simple" conversion failure.
5841static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5842 Expr *op) {
5843 QualType destType = entity.getType();
5844 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5845 op->getType()->isObjCObjectPointerType()) {
5846
5847 // Emit a possible note about the conversion failing because the
5848 // operand is a message send with a related result type.
5849 S.EmitRelatedResultTypeNote(op);
5850
5851 // Emit a possible note about a return failing because we're
5852 // expecting a related result type.
5853 if (entity.getKind() == InitializedEntity::EK_Result)
5854 S.EmitRelatedResultTypeNoteForReturn(destType);
5855 }
5856}
5857
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005858bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005859 const InitializedEntity &Entity,
5860 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005861 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005862 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005863 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005864
Douglas Gregord6542d82009-12-22 15:35:07 +00005865 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005866 switch (Failure) {
5867 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005868 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005869 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005870 // Dig out the reference subobject which is uninitialized and diagnose it.
5871 // If this is value-initialization, this could be nested some way within
5872 // the target type.
5873 assert(Kind.getKind() == InitializationKind::IK_Value ||
5874 DestType->isReferenceType());
5875 bool Diagnosed =
5876 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5877 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5878 (void)Diagnosed;
5879 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005880 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005881 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005882 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005883
Douglas Gregor20093b42009-12-09 23:02:17 +00005884 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00005885 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00005886 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00005887 case FK_ArrayNeedsInitListOrStringLiteral:
5888 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
5889 break;
5890 case FK_ArrayNeedsInitListOrWideStringLiteral:
5891 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
5892 break;
5893 case FK_NarrowStringIntoWideCharArray:
5894 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
5895 break;
5896 case FK_WideStringIntoCharArray:
5897 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
5898 break;
5899 case FK_IncompatWideStringIntoWideChar:
5900 S.Diag(Kind.getLocation(),
5901 diag::err_array_init_incompat_wide_string_into_wchar);
5902 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005903 case FK_ArrayTypeMismatch:
5904 case FK_NonConstantArrayInit:
5905 S.Diag(Kind.getLocation(),
5906 (Failure == FK_ArrayTypeMismatch
5907 ? diag::err_array_init_different_type
5908 : diag::err_array_init_non_constant_array))
5909 << DestType.getNonReferenceType()
5910 << Args[0]->getType()
5911 << Args[0]->getSourceRange();
5912 break;
5913
John McCall73076432012-01-05 00:13:19 +00005914 case FK_VariableLengthArrayHasInitializer:
5915 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5916 << Args[0]->getSourceRange();
5917 break;
5918
John McCall6bb80172010-03-30 21:47:33 +00005919 case FK_AddressOfOverloadFailed: {
5920 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005921 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005922 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005923 true,
5924 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005925 break;
John McCall6bb80172010-03-30 21:47:33 +00005926 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005927
Douglas Gregor20093b42009-12-09 23:02:17 +00005928 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005929 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005930 switch (FailedOverloadResult) {
5931 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005932 if (Failure == FK_UserConversionOverloadFailed)
5933 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5934 << Args[0]->getType() << DestType
5935 << Args[0]->getSourceRange();
5936 else
5937 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5938 << DestType << Args[0]->getType()
5939 << Args[0]->getSourceRange();
5940
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005941 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005942 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005943
Douglas Gregor20093b42009-12-09 23:02:17 +00005944 case OR_No_Viable_Function:
5945 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5946 << Args[0]->getType() << DestType.getNonReferenceType()
5947 << Args[0]->getSourceRange();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005948 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005949 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005950
Douglas Gregor20093b42009-12-09 23:02:17 +00005951 case OR_Deleted: {
5952 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5953 << Args[0]->getType() << DestType.getNonReferenceType()
5954 << Args[0]->getSourceRange();
5955 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005956 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005957 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5958 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005959 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005960 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005961 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005962 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005963 }
5964 break;
5965 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005966
Douglas Gregor20093b42009-12-09 23:02:17 +00005967 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005968 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005969 }
5970 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005971
Douglas Gregor20093b42009-12-09 23:02:17 +00005972 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005973 if (isa<InitListExpr>(Args[0])) {
5974 S.Diag(Kind.getLocation(),
5975 diag::err_lvalue_reference_bind_to_initlist)
5976 << DestType.getNonReferenceType().isVolatileQualified()
5977 << DestType.getNonReferenceType()
5978 << Args[0]->getSourceRange();
5979 break;
5980 }
5981 // Intentional fallthrough
5982
Douglas Gregor20093b42009-12-09 23:02:17 +00005983 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005984 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005985 Failure == FK_NonConstLValueReferenceBindingToTemporary
5986 ? diag::err_lvalue_reference_bind_to_temporary
5987 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005988 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005989 << DestType.getNonReferenceType()
5990 << Args[0]->getType()
5991 << Args[0]->getSourceRange();
5992 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005993
Douglas Gregor20093b42009-12-09 23:02:17 +00005994 case FK_RValueReferenceBindingToLValue:
5995 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005996 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005997 << Args[0]->getSourceRange();
5998 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005999
Douglas Gregor20093b42009-12-09 23:02:17 +00006000 case FK_ReferenceInitDropsQualifiers:
6001 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6002 << DestType.getNonReferenceType()
6003 << Args[0]->getType()
6004 << Args[0]->getSourceRange();
6005 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006006
Douglas Gregor20093b42009-12-09 23:02:17 +00006007 case FK_ReferenceInitFailed:
6008 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6009 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006010 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006011 << Args[0]->getType()
6012 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006013 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006014 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006015
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006016 case FK_ConversionFailed: {
6017 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006018 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006019 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006020 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006021 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006022 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006023 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006024 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6025 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006026 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006027 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006028 }
John Wiegley429bb272011-04-08 18:41:53 +00006029
6030 case FK_ConversionFromPropertyFailed:
6031 // No-op. This error has already been reported.
6032 break;
6033
Douglas Gregord87b61f2009-12-10 17:56:55 +00006034 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006035 SourceRange R;
6036
6037 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006038 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006039 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006040 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006041 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006042
Douglas Gregor19311e72010-09-08 21:40:08 +00006043 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6044 if (Kind.isCStyleOrFunctionalCast())
6045 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6046 << R;
6047 else
6048 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6049 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006050 break;
6051 }
6052
6053 case FK_ReferenceBindingToInitList:
6054 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6055 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6056 break;
6057
6058 case FK_InitListBadDestinationType:
6059 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6060 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6061 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006062
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006063 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006064 case FK_ConstructorOverloadFailed: {
6065 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006066 if (Args.size())
6067 ArgsRange = SourceRange(Args.front()->getLocStart(),
6068 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006069
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006070 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006071 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006072 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006073 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006074 }
6075
Douglas Gregor51c56d62009-12-14 20:49:26 +00006076 // FIXME: Using "DestType" for the entity we're printing is probably
6077 // bad.
6078 switch (FailedOverloadResult) {
6079 case OR_Ambiguous:
6080 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6081 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006082 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006083 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006084
Douglas Gregor51c56d62009-12-14 20:49:26 +00006085 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006086 if (Kind.getKind() == InitializationKind::IK_Default &&
6087 (Entity.getKind() == InitializedEntity::EK_Base ||
6088 Entity.getKind() == InitializedEntity::EK_Member) &&
6089 isa<CXXConstructorDecl>(S.CurContext)) {
6090 // This is implicit default initialization of a member or
6091 // base within a constructor. If no viable function was
6092 // found, notify the user that she needs to explicitly
6093 // initialize this base/member.
6094 CXXConstructorDecl *Constructor
6095 = cast<CXXConstructorDecl>(S.CurContext);
6096 if (Entity.getKind() == InitializedEntity::EK_Base) {
6097 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006098 << (Constructor->getInheritedConstructor() ? 2 :
6099 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006100 << S.Context.getTypeDeclType(Constructor->getParent())
6101 << /*base=*/0
6102 << Entity.getType();
6103
6104 RecordDecl *BaseDecl
6105 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6106 ->getDecl();
6107 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6108 << S.Context.getTagDeclType(BaseDecl);
6109 } else {
6110 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006111 << (Constructor->getInheritedConstructor() ? 2 :
6112 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006113 << S.Context.getTypeDeclType(Constructor->getParent())
6114 << /*member=*/1
6115 << Entity.getName();
6116 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6117
6118 if (const RecordType *Record
6119 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006120 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006121 diag::note_previous_decl)
6122 << S.Context.getTagDeclType(Record->getDecl());
6123 }
6124 break;
6125 }
6126
Douglas Gregor51c56d62009-12-14 20:49:26 +00006127 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6128 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006129 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006130 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006131
Douglas Gregor51c56d62009-12-14 20:49:26 +00006132 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006133 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006134 OverloadingResult Ovl
6135 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006136 if (Ovl != OR_Deleted) {
6137 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6138 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006139 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006140 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006141 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006142
6143 // If this is a defaulted or implicitly-declared function, then
6144 // it was implicitly deleted. Make it clear that the deletion was
6145 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006146 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006147 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006148 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006149 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006150 else
6151 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6152 << true << DestType << ArgsRange;
6153
6154 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006155 break;
6156 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006157
Douglas Gregor51c56d62009-12-14 20:49:26 +00006158 case OR_Success:
6159 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006160 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006161 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006162 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006163
Douglas Gregor99a2e602009-12-16 01:38:02 +00006164 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006165 if (Entity.getKind() == InitializedEntity::EK_Member &&
6166 isa<CXXConstructorDecl>(S.CurContext)) {
6167 // This is implicit default-initialization of a const member in
6168 // a constructor. Complain that it needs to be explicitly
6169 // initialized.
6170 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6171 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006172 << (Constructor->getInheritedConstructor() ? 2 :
6173 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006174 << S.Context.getTypeDeclType(Constructor->getParent())
6175 << /*const=*/1
6176 << Entity.getName();
6177 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6178 << Entity.getName();
6179 } else {
6180 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6181 << DestType << (bool)DestType->getAs<RecordType>();
6182 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006183 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006184
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006185 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006186 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006187 diag::err_init_incomplete_type);
6188 break;
6189
Sebastian Redl14b0c192011-09-24 17:48:00 +00006190 case FK_ListInitializationFailed: {
6191 // Run the init list checker again to emit diagnostics.
6192 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6193 QualType DestType = Entity.getType();
6194 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00006195 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00006196 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00006197 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006198 assert(DiagnoseInitList.HadError() &&
6199 "Inconsistent init list check result.");
6200 break;
6201 }
John McCall5acb0c92011-10-17 18:40:02 +00006202
6203 case FK_PlaceholderType: {
6204 // FIXME: Already diagnosed!
6205 break;
6206 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006207
6208 case FK_InitListElementCopyFailure: {
6209 // Try to perform all copies again.
6210 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6211 unsigned NumInits = InitList->getNumInits();
6212 QualType DestType = Entity.getType();
6213 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006214 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006215 (void)Success;
6216 assert(Success && "Where did the std::initializer_list go?");
6217 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6218 S.Context.getConstantArrayType(E,
6219 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6220 NumInits),
6221 ArrayType::Normal, 0));
6222 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6223 0, HiddenArray);
6224 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6225 // where the init list type is wrong, e.g.
6226 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6227 // FIXME: Emit a note if we hit the limit?
6228 int ErrorCount = 0;
6229 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6230 Element.setElementIndex(i);
6231 ExprResult Init = S.Owned(InitList->getInit(i));
6232 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6233 .isInvalid())
6234 ++ErrorCount;
6235 }
6236 break;
6237 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006238
6239 case FK_ExplicitConstructor: {
6240 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6241 << Args[0]->getSourceRange();
6242 OverloadCandidateSet::iterator Best;
6243 OverloadingResult Ovl
6244 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006245 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006246 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6247 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6248 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6249 break;
6250 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006251 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006252
Douglas Gregora41a8c52010-04-22 00:20:18 +00006253 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006254 return true;
6255}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006256
Chris Lattner5f9e2722011-07-23 10:55:15 +00006257void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006258 switch (SequenceKind) {
6259 case FailedSequence: {
6260 OS << "Failed sequence: ";
6261 switch (Failure) {
6262 case FK_TooManyInitsForReference:
6263 OS << "too many initializers for reference";
6264 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006265
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006266 case FK_ArrayNeedsInitList:
6267 OS << "array requires initializer list";
6268 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006269
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006270 case FK_ArrayNeedsInitListOrStringLiteral:
6271 OS << "array requires initializer list or string literal";
6272 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006273
Hans Wennborg0ff50742013-05-15 11:03:04 +00006274 case FK_ArrayNeedsInitListOrWideStringLiteral:
6275 OS << "array requires initializer list or wide string literal";
6276 break;
6277
6278 case FK_NarrowStringIntoWideCharArray:
6279 OS << "narrow string into wide char array";
6280 break;
6281
6282 case FK_WideStringIntoCharArray:
6283 OS << "wide string into char array";
6284 break;
6285
6286 case FK_IncompatWideStringIntoWideChar:
6287 OS << "incompatible wide string into wide char array";
6288 break;
6289
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006290 case FK_ArrayTypeMismatch:
6291 OS << "array type mismatch";
6292 break;
6293
6294 case FK_NonConstantArrayInit:
6295 OS << "non-constant array initializer";
6296 break;
6297
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006298 case FK_AddressOfOverloadFailed:
6299 OS << "address of overloaded function failed";
6300 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006301
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006302 case FK_ReferenceInitOverloadFailed:
6303 OS << "overload resolution for reference initialization failed";
6304 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006305
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006306 case FK_NonConstLValueReferenceBindingToTemporary:
6307 OS << "non-const lvalue reference bound to temporary";
6308 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006309
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006310 case FK_NonConstLValueReferenceBindingToUnrelated:
6311 OS << "non-const lvalue reference bound to unrelated type";
6312 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006313
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006314 case FK_RValueReferenceBindingToLValue:
6315 OS << "rvalue reference bound to an lvalue";
6316 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006317
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006318 case FK_ReferenceInitDropsQualifiers:
6319 OS << "reference initialization drops qualifiers";
6320 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006321
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006322 case FK_ReferenceInitFailed:
6323 OS << "reference initialization failed";
6324 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006325
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006326 case FK_ConversionFailed:
6327 OS << "conversion failed";
6328 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006329
John Wiegley429bb272011-04-08 18:41:53 +00006330 case FK_ConversionFromPropertyFailed:
6331 OS << "conversion from property failed";
6332 break;
6333
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006334 case FK_TooManyInitsForScalar:
6335 OS << "too many initializers for scalar";
6336 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006337
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006338 case FK_ReferenceBindingToInitList:
6339 OS << "referencing binding to initializer list";
6340 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006341
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006342 case FK_InitListBadDestinationType:
6343 OS << "initializer list for non-aggregate, non-scalar type";
6344 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006345
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006346 case FK_UserConversionOverloadFailed:
6347 OS << "overloading failed for user-defined conversion";
6348 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006349
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006350 case FK_ConstructorOverloadFailed:
6351 OS << "constructor overloading failed";
6352 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006353
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006354 case FK_DefaultInitOfConst:
6355 OS << "default initialization of a const variable";
6356 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006357
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006358 case FK_Incomplete:
6359 OS << "initialization of incomplete type";
6360 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006361
6362 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006363 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006364 break;
6365
John McCall73076432012-01-05 00:13:19 +00006366 case FK_VariableLengthArrayHasInitializer:
6367 OS << "variable length array has an initializer";
6368 break;
6369
John McCall5acb0c92011-10-17 18:40:02 +00006370 case FK_PlaceholderType:
6371 OS << "initializer expression isn't contextually valid";
6372 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006373
6374 case FK_ListConstructorOverloadFailed:
6375 OS << "list constructor overloading failed";
6376 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006377
6378 case FK_InitListElementCopyFailure:
6379 OS << "copy construction of initializer list element failed";
6380 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006381
6382 case FK_ExplicitConstructor:
6383 OS << "list copy initialization chose explicit constructor";
6384 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006385 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006386 OS << '\n';
6387 return;
6388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006389
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006390 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006391 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006392 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006393
Sebastian Redl7491c492011-06-05 13:59:11 +00006394 case NormalSequence:
6395 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006396 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006397 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006398
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006399 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6400 if (S != step_begin()) {
6401 OS << " -> ";
6402 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006403
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006404 switch (S->Kind) {
6405 case SK_ResolveAddressOfOverloadedFunction:
6406 OS << "resolve address of overloaded function";
6407 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006408
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006409 case SK_CastDerivedToBaseRValue:
6410 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6411 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006412
Sebastian Redl906082e2010-07-20 04:20:21 +00006413 case SK_CastDerivedToBaseXValue:
6414 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6415 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006416
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006417 case SK_CastDerivedToBaseLValue:
6418 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6419 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006420
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006421 case SK_BindReference:
6422 OS << "bind reference to lvalue";
6423 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006424
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006425 case SK_BindReferenceToTemporary:
6426 OS << "bind reference to a temporary";
6427 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006428
Douglas Gregor523d46a2010-04-18 07:40:54 +00006429 case SK_ExtraneousCopyToTemporary:
6430 OS << "extraneous C++03 copy to temporary";
6431 break;
6432
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006433 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006434 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006435 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006436
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006437 case SK_QualificationConversionRValue:
6438 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006439 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006440
Sebastian Redl906082e2010-07-20 04:20:21 +00006441 case SK_QualificationConversionXValue:
6442 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006443 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006444
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006445 case SK_QualificationConversionLValue:
6446 OS << "qualification conversion (lvalue)";
6447 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006448
Jordan Rose1fd1e282013-04-11 00:58:58 +00006449 case SK_LValueToRValue:
6450 OS << "load (lvalue to rvalue)";
6451 break;
6452
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006453 case SK_ConversionSequence:
6454 OS << "implicit conversion sequence (";
6455 S->ICS->DebugPrint(); // FIXME: use OS
6456 OS << ")";
6457 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006458
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006459 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006460 OS << "list aggregate initialization";
6461 break;
6462
6463 case SK_ListConstructorCall:
6464 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006465 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006466
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006467 case SK_UnwrapInitList:
6468 OS << "unwrap reference initializer list";
6469 break;
6470
6471 case SK_RewrapInitList:
6472 OS << "rewrap reference initializer list";
6473 break;
6474
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006475 case SK_ConstructorInitialization:
6476 OS << "constructor initialization";
6477 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006478
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006479 case SK_ZeroInitialization:
6480 OS << "zero initialization";
6481 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006482
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006483 case SK_CAssignment:
6484 OS << "C assignment";
6485 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006486
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006487 case SK_StringInit:
6488 OS << "string initialization";
6489 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006490
6491 case SK_ObjCObjectConversion:
6492 OS << "Objective-C object conversion";
6493 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006494
6495 case SK_ArrayInit:
6496 OS << "array initialization";
6497 break;
John McCallf85e1932011-06-15 23:02:42 +00006498
Richard Smith0f163e92012-02-15 22:38:09 +00006499 case SK_ParenthesizedArrayInit:
6500 OS << "parenthesized array initialization";
6501 break;
6502
John McCallf85e1932011-06-15 23:02:42 +00006503 case SK_PassByIndirectCopyRestore:
6504 OS << "pass by indirect copy and restore";
6505 break;
6506
6507 case SK_PassByIndirectRestore:
6508 OS << "pass by indirect restore";
6509 break;
6510
6511 case SK_ProduceObjCObject:
6512 OS << "Objective-C object retension";
6513 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006514
6515 case SK_StdInitializerList:
6516 OS << "std::initializer_list from initializer list";
6517 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006518
Guy Benyei21f18c42013-02-07 10:55:47 +00006519 case SK_OCLSamplerInit:
6520 OS << "OpenCL sampler_t from integer constant";
6521 break;
6522
Guy Benyeie6b9d802013-01-20 12:31:11 +00006523 case SK_OCLZeroEvent:
6524 OS << "OpenCL event_t from zero";
6525 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006526 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006527
6528 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006529 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006530
6531 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006532}
6533
6534void InitializationSequence::dump() const {
6535 dump(llvm::errs());
6536}
6537
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006538static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6539 QualType EntityType,
6540 const Expr *PreInit,
6541 const Expr *PostInit) {
6542 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6543 return;
6544
6545 // A narrowing conversion can only appear as the final implicit conversion in
6546 // an initialization sequence.
6547 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6548 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6549 return;
6550
6551 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6552 const StandardConversionSequence *SCS = 0;
6553 switch (ICS.getKind()) {
6554 case ImplicitConversionSequence::StandardConversion:
6555 SCS = &ICS.Standard;
6556 break;
6557 case ImplicitConversionSequence::UserDefinedConversion:
6558 SCS = &ICS.UserDefined.After;
6559 break;
6560 case ImplicitConversionSequence::AmbiguousConversion:
6561 case ImplicitConversionSequence::EllipsisConversion:
6562 case ImplicitConversionSequence::BadConversion:
6563 return;
6564 }
6565
6566 // Determine the type prior to the narrowing conversion. If a conversion
6567 // operator was used, this may be different from both the type of the entity
6568 // and of the pre-initialization expression.
6569 QualType PreNarrowingType = PreInit->getType();
6570 if (Seq.step_begin() + 1 != Seq.step_end())
6571 PreNarrowingType = Seq.step_end()[-2].Type;
6572
6573 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6574 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006575 QualType ConstantType;
6576 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6577 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006578 case NK_Not_Narrowing:
6579 // No narrowing occurred.
6580 return;
6581
6582 case NK_Type_Narrowing:
6583 // This was a floating-to-integer conversion, which is always considered a
6584 // narrowing conversion even if the value is a constant and can be
6585 // represented exactly as an integer.
6586 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006587 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006588 diag::warn_init_list_type_narrowing
6589 : S.isSFINAEContext()?
6590 diag::err_init_list_type_narrowing_sfinae
6591 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006592 << PostInit->getSourceRange()
6593 << PreNarrowingType.getLocalUnqualifiedType()
6594 << EntityType.getLocalUnqualifiedType();
6595 break;
6596
6597 case NK_Constant_Narrowing:
6598 // A constant value was narrowed.
6599 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006600 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006601 diag::warn_init_list_constant_narrowing
6602 : S.isSFINAEContext()?
6603 diag::err_init_list_constant_narrowing_sfinae
6604 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006605 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006606 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006607 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006608 break;
6609
6610 case NK_Variable_Narrowing:
6611 // A variable's value may have been narrowed.
6612 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006613 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006614 diag::warn_init_list_variable_narrowing
6615 : S.isSFINAEContext()?
6616 diag::err_init_list_variable_narrowing_sfinae
6617 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006618 << PostInit->getSourceRange()
6619 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006620 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006621 break;
6622 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006623
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006624 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006625 llvm::raw_svector_ostream OS(StaticCast);
6626 OS << "static_cast<";
6627 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6628 // It's important to use the typedef's name if there is one so that the
6629 // fixit doesn't break code using types like int64_t.
6630 //
6631 // FIXME: This will break if the typedef requires qualification. But
6632 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006633 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006634 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006635 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006636 else {
6637 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6638 // with a broken cast.
6639 return;
6640 }
6641 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006642 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6643 << PostInit->getSourceRange()
6644 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006645 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006646 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006647}
6648
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006649//===----------------------------------------------------------------------===//
6650// Initialization helper functions
6651//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006652bool
6653Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6654 ExprResult Init) {
6655 if (Init.isInvalid())
6656 return false;
6657
6658 Expr *InitE = Init.get();
6659 assert(InitE && "No initialization expression");
6660
Douglas Gregor3c394c52012-07-31 22:15:04 +00006661 InitializationKind Kind
6662 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006663 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006664 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006665}
6666
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006667ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006668Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6669 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006670 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006671 bool TopLevelOfInitList,
6672 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006673 if (Init.isInvalid())
6674 return ExprError();
6675
John McCall15d7d122010-11-11 03:21:53 +00006676 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006677 assert(InitE && "No initialization expression?");
6678
6679 if (EqualLoc.isInvalid())
6680 EqualLoc = InitE->getLocStart();
6681
6682 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006683 EqualLoc,
6684 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006685 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006686 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006687
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006688 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006689
6690 if (!Result.isInvalid() && TopLevelOfInitList)
6691 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6692 InitE, Result.get());
6693
6694 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006695}