blob: f7b53b2be21092a5d31066793f6805d50c2b3dc7 [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 Wennborgc1fb1e02013-05-16 09:22:40 +0000123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
John McCallce6c9b72011-02-21 07:22:22 +0000125 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg0ff50742013-05-15 11:03:04 +0000126 if (!arrayType)
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
John McCallce6c9b72011-02-21 07:22:22 +0000129}
130
Richard Smith30ae1ed2013-05-05 16:40:13 +0000131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smith27f9cf32013-05-06 00:35:47 +0000134 while (true) {
Richard Smith30ae1ed2013-05-05 16:40:13 +0000135 E->setType(Ty);
Richard Smith27f9cf32013-05-06 00:35:47 +0000136 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137 break;
138 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139 E = PE->getSubExpr();
140 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141 E = UO->getSubExpr();
142 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143 E = GSE->getResultExpr();
144 else
145 llvm_unreachable("unexpected expr in string literal init");
Richard Smith30ae1ed2013-05-05 16:40:13 +0000146 }
Richard Smith30ae1ed2013-05-05 16:40:13 +0000147}
148
John McCallfef8b342011-02-21 07:57:55 +0000149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000151 // Get the length of the string as parsed.
152 uint64_t StrLength =
153 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
154
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000157 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000158 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +0000159 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000160 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
Richard Smith30ae1ed2013-05-05 16:40:13 +0000164 updateStringLiteralType(Str, DeclT);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000165 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000166 }
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Eli Friedman8718a6a2009-05-29 18:22:49 +0000168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000170 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000171 // the size may be smaller or larger than the string we are initializing.
172 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000173 if (S.getLangOpts().CPlusPlus) {
Richard Smith30ae1ed2013-05-05 16:40:13 +0000174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000175 // For Pascal strings it's OK to strip off the terminating null character,
176 // so the example below is valid:
177 //
178 // unsigned char a[2] = "\pa";
179 if (SL->isPascal())
180 StrLength--;
181 }
182
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000185 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000186 diag::err_initializer_string_for_char_array_too_long)
187 << Str->getSourceRange();
188 } else {
189 // C99 6.7.8p14.
190 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000191 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000192 diag::warn_initializer_string_for_char_array_too_long)
193 << Str->getSourceRange();
194 }
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Eli Friedman8718a6a2009-05-29 18:22:49 +0000196 // Set the type to the actual size that we are initializing. If we have
197 // something like:
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
Richard Smith30ae1ed2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000201}
202
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Douglas Gregor9e80f722009-01-29 01:05:33 +0000207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000221/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000234namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000235class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000236 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000237 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000238 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000239 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000240 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000241 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000243 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000244 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000245 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000246 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000247 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000248 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000249 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000250 unsigned &StructuredIndex,
251 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000252 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000253 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000254 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000255 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000256 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000257 unsigned &StructuredIndex,
258 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000259 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000260 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000261 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000262 InitListExpr *StructuredList,
263 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000264 void CheckComplexType(const InitializedEntity &Entity,
265 InitListExpr *IList, QualType DeclType,
266 unsigned &Index,
267 InitListExpr *StructuredList,
268 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000269 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000270 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000271 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000272 InitListExpr *StructuredList,
273 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000274 void CheckReferenceType(const InitializedEntity &Entity,
275 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000276 unsigned &Index,
277 InitListExpr *StructuredList,
278 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000279 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000280 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000283 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000284 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000285 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000286 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000287 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000288 unsigned &StructuredIndex,
289 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000290 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000291 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000292 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000293 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000294 InitListExpr *StructuredList,
295 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000296 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000297 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000298 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000299 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000300 RecordDecl::field_iterator *NextField,
301 llvm::APSInt *NextElementIndex,
302 unsigned &Index,
303 InitListExpr *StructuredList,
304 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000305 bool FinishSubobjectInit,
306 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000307 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
308 QualType CurrentObjectType,
309 InitListExpr *StructuredList,
310 unsigned StructuredIndex,
311 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000312 void UpdateStructuredListElement(InitListExpr *StructuredList,
313 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000314 Expr *expr);
315 int numArrayElements(QualType DeclType);
316 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000317
Douglas Gregord6d37de2009-12-22 00:05:34 +0000318 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
319 const InitializedEntity &ParentEntity,
320 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000321 void FillInValueInitializations(const InitializedEntity &Entity,
322 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000323 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
324 Expr *InitExpr, FieldDecl *Field,
325 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000326 void CheckValueInitializable(const InitializedEntity &Entity);
327
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000328public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000329 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000330 InitListExpr *IL, QualType &T, bool VerifyOnly,
331 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000332 bool HadError() { return hadError; }
333
334 // @brief Retrieves the fully-structured initializer list used for
335 // semantic analysis and code generation.
336 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
337};
Chris Lattner8b419b92009-02-24 22:48:58 +0000338} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000339
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000340void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
341 assert(VerifyOnly &&
342 "CheckValueInitializable is only inteded for verification mode.");
343
344 SourceLocation Loc;
345 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
346 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000347 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000348 if (InitSeq.Failed())
349 hadError = true;
350}
351
Douglas Gregord6d37de2009-12-22 00:05:34 +0000352void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
353 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000355 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000356 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000357 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000359 = InitializedEntity::InitializeMember(Field, &ParentEntity);
360 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000361 // If there's no explicit initializer but we have a default initializer, use
362 // that. This only happens in C++1y, since classes with default
363 // initializers are not aggregates in C++11.
364 if (Field->hasInClassInitializer()) {
365 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
366 ILE->getRBraceLoc(), Field);
367 if (Init < NumInits)
368 ILE->setInit(Init, DIE);
369 else {
370 ILE->updateInit(SemaRef.Context, Init, DIE);
371 RequiresSecondPass = true;
372 }
373 return;
374 }
375
Douglas Gregord6d37de2009-12-22 00:05:34 +0000376 // FIXME: We probably don't need to handle references
377 // specially here, since value-initialization of references is
378 // handled in InitializationSequence.
379 if (Field->getType()->isReferenceType()) {
380 // C++ [dcl.init.aggr]p9:
381 // If an incomplete or empty initializer-list leaves a
382 // member of reference type uninitialized, the program is
383 // ill-formed.
384 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
385 << Field->getType()
386 << ILE->getSyntacticForm()->getSourceRange();
387 SemaRef.Diag(Field->getLocation(),
388 diag::note_uninit_reference_member);
389 hadError = true;
390 return;
391 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000392
Douglas Gregord6d37de2009-12-22 00:05:34 +0000393 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
394 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000395 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000396 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000397 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000398 hadError = true;
399 return;
400 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000401
John McCall60d7b3a2010-08-24 06:29:42 +0000402 ExprResult MemberInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000403 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000404 if (MemberInit.isInvalid()) {
405 hadError = true;
406 return;
407 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000408
Douglas Gregord6d37de2009-12-22 00:05:34 +0000409 if (hadError) {
410 // Do nothing
411 } else if (Init < NumInits) {
412 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000413 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000414 // Value-initialization requires a constructor call, so
415 // extend the initializer list to include the constructor
416 // call and make a note that we'll need to take another pass
417 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000418 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000419 RequiresSecondPass = true;
420 }
421 } else if (InitListExpr *InnerILE
422 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423 FillInValueInitializations(MemberEntity, InnerILE,
424 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000425}
426
Douglas Gregor4c678342009-01-28 21:54:33 +0000427/// Recursively replaces NULL values within the given initializer list
428/// with expressions that perform value-initialization of the
429/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000430void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000431InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
432 InitListExpr *ILE,
433 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000435 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000436 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000437 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000438 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Ted Kremenek6217b802009-07-29 21:53:49 +0000440 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000441 const RecordDecl *RDecl = RType->getDecl();
442 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000443 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
444 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000445 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
446 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
447 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
448 FieldEnd = RDecl->field_end();
449 Field != FieldEnd; ++Field) {
450 if (Field->hasInClassInitializer()) {
451 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
452 break;
453 }
454 }
455 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000456 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000457 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
458 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000459 Field != FieldEnd; ++Field) {
460 if (Field->isUnnamedBitfield())
461 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000462
Douglas Gregord6d37de2009-12-22 00:05:34 +0000463 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000464 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000465
David Blaikie581deb32012-06-06 20:45:41 +0000466 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000467 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000468 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000469
Douglas Gregord6d37de2009-12-22 00:05:34 +0000470 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000471
Douglas Gregord6d37de2009-12-22 00:05:34 +0000472 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000473 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000474 break;
475 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000476 }
477
478 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000479 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000480
481 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000483 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000484 unsigned NumInits = ILE->getNumInits();
485 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000486 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000487 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000488 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
489 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000490 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000491 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000492 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000493 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000494 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000495 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000496 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000497 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000498 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000499
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000500
Douglas Gregor87fd7032009-02-02 17:43:21 +0000501 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000502 if (hadError)
503 return;
504
Anders Carlssond3d824d2010-01-23 04:34:47 +0000505 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
506 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000507 ElementEntity.setElementIndex(Init);
508
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000509 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
510 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000511 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
512 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000513 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000514 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000515 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000516 hadError = true;
517 return;
518 }
519
John McCall60d7b3a2010-08-24 06:29:42 +0000520 ExprResult ElementInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000521 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000522 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000523 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000524 return;
525 }
526
527 if (hadError) {
528 // Do nothing
529 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000530 // For arrays, just set the expression used for value-initialization
531 // of the "holes" in the array.
532 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
533 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
534 else
535 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000536 } else {
537 // For arrays, just set the expression used for value-initialization
538 // of the rest of elements and exit.
539 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
540 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
541 return;
542 }
543
Sebastian Redl7491c492011-06-05 13:59:11 +0000544 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000545 // Value-initialization requires a constructor call, so
546 // extend the initializer list to include the constructor
547 // call and make a note that we'll need to take another pass
548 // through the initializer list.
549 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
550 RequiresSecondPass = true;
551 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000552 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000553 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000554 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000555 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000556 }
557}
558
Chris Lattner68355a52009-01-29 05:10:57 +0000559
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000560InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000561 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000562 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000563 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000564 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000565
Eli Friedmanb85f7072008-05-19 19:16:24 +0000566 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000567 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000568 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000569 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000571 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000572 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000573
Sebastian Redl14b0c192011-09-24 17:48:00 +0000574 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000575 bool RequiresSecondPass = false;
576 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000577 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000579 RequiresSecondPass);
580 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000581}
582
583int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000584 // FIXME: use a proper constant
585 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000586 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000587 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000588 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
589 }
590 return maxElements;
591}
592
593int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000594 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000596 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000597 Field = structDecl->field_begin(),
598 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000599 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000600 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000601 ++InitializableMembers;
602 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000603 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000604 return std::min(InitializableMembers, 1);
605 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000606}
607
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000608void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000609 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000610 QualType T, unsigned &Index,
611 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000612 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000613 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Steve Naroff0cca7492008-05-01 22:18:59 +0000615 if (T->isArrayType())
616 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000617 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000618 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000619 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000620 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000621 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000622 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000623
Eli Friedman402256f2008-05-25 13:49:22 +0000624 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000625 if (!VerifyOnly)
626 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
627 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000628 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000629 hadError = true;
630 return;
631 }
632
Douglas Gregor4c678342009-01-28 21:54:33 +0000633 // Build a structured initializer list corresponding to this subobject.
634 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000635 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
636 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000637 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000638 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000640
Douglas Gregor4c678342009-01-28 21:54:33 +0000641 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000642 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000643 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000644 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000645 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000646 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000647
648 if (VerifyOnly) {
649 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
650 hadError = true;
651 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000652 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000653
Sebastian Redlc2235182011-10-16 18:19:28 +0000654 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000655 // Update the structured sub-object initializer so that it's ending
656 // range corresponds with the end of the last initializer it used.
657 if (EndIndex < ParentIList->getNumInits()) {
658 SourceLocation EndLoc
659 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
660 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000662
Sebastian Redlc2235182011-10-16 18:19:28 +0000663 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000664 if (T->isArrayType() || T->isRecordType()) {
665 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000666 AllowBraceElision ? diag::warn_missing_braces :
667 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000668 << StructuredSubobjectInitList->getSourceRange()
669 << FixItHint::CreateInsertion(
670 StructuredSubobjectInitList->getLocStart(), "{")
671 << FixItHint::CreateInsertion(
672 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000673 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000674 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000675 if (!AllowBraceElision)
676 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000677 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000678 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000679}
680
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000681void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000682 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000683 unsigned &Index,
684 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000685 unsigned &StructuredIndex,
686 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000687 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000688 if (!VerifyOnly) {
689 SyntacticToSemantic[IList] = StructuredList;
690 StructuredList->setSyntacticForm(IList);
691 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000692 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000693 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000694 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000695 QualType ExprTy = T;
696 if (!ExprTy->isArrayType())
697 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000698 IList->setType(ExprTy);
699 StructuredList->setType(ExprTy);
700 }
Eli Friedman638e1442008-05-25 13:22:35 +0000701 if (hadError)
702 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000703
Eli Friedman638e1442008-05-25 13:22:35 +0000704 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000705 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000706 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000707 if (SemaRef.getLangOpts().CPlusPlus ||
708 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000709 IList->getType()->isVectorType())) {
710 hadError = true;
711 }
712 return;
713 }
714
Eli Friedmane5408582009-05-29 20:20:05 +0000715 if (StructuredIndex == 1 &&
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000716 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
717 SIF_None) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000718 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000719 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000720 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000721 hadError = true;
722 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000723 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000724 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000725 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000726 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000727 // Don't complain for incomplete types, since we'll get an error
728 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000729 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000730 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000731 CurrentObjectType->isArrayType()? 0 :
732 CurrentObjectType->isVectorType()? 1 :
733 CurrentObjectType->isScalarType()? 2 :
734 CurrentObjectType->isUnionType()? 3 :
735 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000736
737 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000738 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000739 DK = diag::err_excess_initializers;
740 hadError = true;
741 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000742 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000743 DK = diag::err_excess_initializers;
744 hadError = true;
745 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000746
Chris Lattner08202542009-02-24 22:50:46 +0000747 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000748 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000749 }
750 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000751
Sebastian Redl14b0c192011-09-24 17:48:00 +0000752 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
753 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000754 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000755 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000756 << FixItHint::CreateRemoval(IList->getLocStart())
757 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000758}
759
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000760void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000761 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000762 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000763 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000764 unsigned &Index,
765 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000766 unsigned &StructuredIndex,
767 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000768 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
769 // Explicitly braced initializer for complex type can be real+imaginary
770 // parts.
771 CheckComplexType(Entity, IList, DeclType, Index,
772 StructuredList, StructuredIndex);
773 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000774 CheckScalarType(Entity, IList, DeclType, Index,
775 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000776 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000777 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000778 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000779 } else if (DeclType->isRecordType()) {
780 assert(DeclType->isAggregateType() &&
781 "non-aggregate records should be handed in CheckSubElementType");
782 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
783 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
784 SubobjectIsDesignatorContext, Index,
785 StructuredList, StructuredIndex,
786 TopLevelObject);
787 } else if (DeclType->isArrayType()) {
788 llvm::APSInt Zero(
789 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
790 false);
791 CheckArrayType(Entity, IList, DeclType, Zero,
792 SubobjectIsDesignatorContext, Index,
793 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000794 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
795 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000796 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000797 if (!VerifyOnly)
798 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
799 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000800 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000801 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000802 CheckReferenceType(Entity, IList, DeclType, Index,
803 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000804 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000805 if (!VerifyOnly)
806 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
807 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000808 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000809 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000810 if (!VerifyOnly)
811 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
812 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000813 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000814 }
815}
816
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000817void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000818 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000819 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000820 unsigned &Index,
821 InitListExpr *StructuredList,
822 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000823 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000824 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000825 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
826 unsigned newIndex = 0;
827 unsigned newStructuredIndex = 0;
828 InitListExpr *newStructuredList
829 = getStructuredSubobjectInit(IList, Index, ElemType,
830 StructuredList, StructuredIndex,
831 SubInitList->getSourceRange());
832 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
833 newStructuredList, newStructuredIndex);
834 ++StructuredIndex;
835 ++Index;
836 return;
837 }
838 assert(SemaRef.getLangOpts().CPlusPlus &&
839 "non-aggregate records are only possible in C++");
840 // C++ initialization is handled later.
841 }
842
843 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000844 return CheckScalarType(Entity, IList, ElemType, Index,
845 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000846 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000847 return CheckReferenceType(Entity, IList, ElemType, Index,
848 StructuredList, StructuredIndex);
849 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000850
John McCallfef8b342011-02-21 07:57:55 +0000851 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
852 // arrayType can be incomplete if we're initializing a flexible
853 // array member. There's nothing we can do with the completed
854 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000855
Hans Wennborg0ff50742013-05-15 11:03:04 +0000856 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000857 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000858 CheckStringInit(expr, ElemType, arrayType, SemaRef);
859 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000860 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000861 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000862 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000863 }
John McCallfef8b342011-02-21 07:57:55 +0000864
865 // Fall through for subaggregate initialization.
866
David Blaikie4e4d0842012-03-11 07:00:24 +0000867 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000868 // C++ [dcl.init.aggr]p12:
869 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000870 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000871 // an initializer-list. If the initializer can initialize a
872 // member, the member is initialized. [...]
873
874 // FIXME: Better EqualLoc?
875 InitializationKind Kind =
876 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000877 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000878
879 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000880 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000881 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000882 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000883 if (Result.isInvalid())
884 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000885
Sebastian Redl14b0c192011-09-24 17:48:00 +0000886 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000887 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000888 }
John McCallfef8b342011-02-21 07:57:55 +0000889 ++Index;
890 return;
891 }
892
893 // Fall through for subaggregate initialization
894 } else {
895 // C99 6.7.8p13:
896 //
897 // The initializer for a structure or union object that has
898 // automatic storage duration shall be either an initializer
899 // list as described below, or a single expression that has
900 // compatible structure or union type. In the latter case, the
901 // initial value of the object, including unnamed members, is
902 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000903 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000904 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000905 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
906 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000907 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000908 if (ExprRes.isInvalid())
909 hadError = true;
910 else {
911 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000912 if (ExprRes.isInvalid())
913 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000914 }
915 UpdateStructuredListElement(StructuredList, StructuredIndex,
916 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000917 ++Index;
918 return;
919 }
John Wiegley429bb272011-04-08 18:41:53 +0000920 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000921 // Fall through for subaggregate initialization
922 }
923
924 // C++ [dcl.init.aggr]p12:
925 //
926 // [...] Otherwise, if the member is itself a non-empty
927 // subaggregate, brace elision is assumed and the initializer is
928 // considered for the initialization of the first member of
929 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000930 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000931 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000932 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
933 StructuredIndex);
934 ++StructuredIndex;
935 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000936 if (!VerifyOnly) {
937 // We cannot initialize this element, so let
938 // PerformCopyInitialization produce the appropriate diagnostic.
939 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
940 SemaRef.Owned(expr),
941 /*TopLevelOfInitList=*/true);
942 }
John McCallfef8b342011-02-21 07:57:55 +0000943 hadError = true;
944 ++Index;
945 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000946 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000947}
948
Eli Friedman0c706c22011-09-19 23:17:44 +0000949void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
950 InitListExpr *IList, QualType DeclType,
951 unsigned &Index,
952 InitListExpr *StructuredList,
953 unsigned &StructuredIndex) {
954 assert(Index == 0 && "Index in explicit init list must be zero");
955
956 // As an extension, clang supports complex initializers, which initialize
957 // a complex number component-wise. When an explicit initializer list for
958 // a complex number contains two two initializers, this extension kicks in:
959 // it exepcts the initializer list to contain two elements convertible to
960 // the element type of the complex type. The first element initializes
961 // the real part, and the second element intitializes the imaginary part.
962
963 if (IList->getNumInits() != 2)
964 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
965 StructuredIndex);
966
967 // This is an extension in C. (The builtin _Complex type does not exist
968 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000969 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000970 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
971 << IList->getSourceRange();
972
973 // Initialize the complex number.
974 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
975 InitializedEntity ElementEntity =
976 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
977
978 for (unsigned i = 0; i < 2; ++i) {
979 ElementEntity.setElementIndex(Index);
980 CheckSubElementType(ElementEntity, IList, elementType, Index,
981 StructuredList, StructuredIndex);
982 }
983}
984
985
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000986void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000987 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000988 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000989 InitListExpr *StructuredList,
990 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000991 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000992 if (!VerifyOnly)
993 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000994 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000995 diag::warn_cxx98_compat_empty_scalar_initializer :
996 diag::err_empty_scalar_initializer)
997 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000998 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000999 ++Index;
1000 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +00001001 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001002 }
John McCallb934c2d2010-11-11 00:46:36 +00001003
1004 Expr *expr = IList->getInit(Index);
1005 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001006 if (!VerifyOnly)
1007 SemaRef.Diag(SubIList->getLocStart(),
1008 diag::warn_many_braces_around_scalar_init)
1009 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001010
1011 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1012 StructuredIndex);
1013 return;
1014 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001015 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001016 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001017 diag::err_designator_for_scalar_init)
1018 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001019 hadError = true;
1020 ++Index;
1021 ++StructuredIndex;
1022 return;
1023 }
1024
Sebastian Redl14b0c192011-09-24 17:48:00 +00001025 if (VerifyOnly) {
1026 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1027 hadError = true;
1028 ++Index;
1029 return;
1030 }
1031
John McCallb934c2d2010-11-11 00:46:36 +00001032 ExprResult Result =
1033 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001034 SemaRef.Owned(expr),
1035 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001036
1037 Expr *ResultExpr = 0;
1038
1039 if (Result.isInvalid())
1040 hadError = true; // types weren't compatible.
1041 else {
1042 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001043
John McCallb934c2d2010-11-11 00:46:36 +00001044 if (ResultExpr != expr) {
1045 // The type was promoted, update initializer list.
1046 IList->setInit(Index, ResultExpr);
1047 }
1048 }
1049 if (hadError)
1050 ++StructuredIndex;
1051 else
1052 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1053 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001054}
1055
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001056void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1057 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001058 unsigned &Index,
1059 InitListExpr *StructuredList,
1060 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001061 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001062 // FIXME: It would be wonderful if we could point at the actual member. In
1063 // general, it would be useful to pass location information down the stack,
1064 // so that we know the location (or decl) of the "current object" being
1065 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001066 if (!VerifyOnly)
1067 SemaRef.Diag(IList->getLocStart(),
1068 diag::err_init_reference_member_uninitialized)
1069 << DeclType
1070 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001071 hadError = true;
1072 ++Index;
1073 ++StructuredIndex;
1074 return;
1075 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001076
1077 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001078 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001079 if (!VerifyOnly)
1080 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1081 << DeclType << IList->getSourceRange();
1082 hadError = true;
1083 ++Index;
1084 ++StructuredIndex;
1085 return;
1086 }
1087
1088 if (VerifyOnly) {
1089 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1090 hadError = true;
1091 ++Index;
1092 return;
1093 }
1094
1095 ExprResult Result =
1096 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1097 SemaRef.Owned(expr),
1098 /*TopLevelOfInitList=*/true);
1099
1100 if (Result.isInvalid())
1101 hadError = true;
1102
1103 expr = Result.takeAs<Expr>();
1104 IList->setInit(Index, expr);
1105
1106 if (hadError)
1107 ++StructuredIndex;
1108 else
1109 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1110 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001111}
1112
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001113void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001114 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001115 unsigned &Index,
1116 InitListExpr *StructuredList,
1117 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001118 const VectorType *VT = DeclType->getAs<VectorType>();
1119 unsigned maxElements = VT->getNumElements();
1120 unsigned numEltsInit = 0;
1121 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001122
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001123 if (Index >= IList->getNumInits()) {
1124 // Make sure the element type can be value-initialized.
1125 if (VerifyOnly)
1126 CheckValueInitializable(
1127 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1128 return;
1129 }
1130
David Blaikie4e4d0842012-03-11 07:00:24 +00001131 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001132 // If the initializing element is a vector, try to copy-initialize
1133 // instead of breaking it apart (which is doomed to failure anyway).
1134 Expr *Init = IList->getInit(Index);
1135 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001136 if (VerifyOnly) {
1137 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1138 hadError = true;
1139 ++Index;
1140 return;
1141 }
1142
John McCall20e047a2010-10-30 00:11:39 +00001143 ExprResult Result =
1144 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001145 SemaRef.Owned(Init),
1146 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001147
1148 Expr *ResultExpr = 0;
1149 if (Result.isInvalid())
1150 hadError = true; // types weren't compatible.
1151 else {
1152 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001153
John McCall20e047a2010-10-30 00:11:39 +00001154 if (ResultExpr != Init) {
1155 // The type was promoted, update initializer list.
1156 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001157 }
1158 }
John McCall20e047a2010-10-30 00:11:39 +00001159 if (hadError)
1160 ++StructuredIndex;
1161 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001162 UpdateStructuredListElement(StructuredList, StructuredIndex,
1163 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001164 ++Index;
1165 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001166 }
Mike Stump1eb44332009-09-09 15:08:12 +00001167
John McCall20e047a2010-10-30 00:11:39 +00001168 InitializedEntity ElementEntity =
1169 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001170
John McCall20e047a2010-10-30 00:11:39 +00001171 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1172 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001173 if (Index >= IList->getNumInits()) {
1174 if (VerifyOnly)
1175 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001176 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001177 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001178
John McCall20e047a2010-10-30 00:11:39 +00001179 ElementEntity.setElementIndex(Index);
1180 CheckSubElementType(ElementEntity, IList, elementType, Index,
1181 StructuredList, StructuredIndex);
1182 }
1183 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001184 }
John McCall20e047a2010-10-30 00:11:39 +00001185
1186 InitializedEntity ElementEntity =
1187 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001188
John McCall20e047a2010-10-30 00:11:39 +00001189 // OpenCL initializers allows vectors to be constructed from vectors.
1190 for (unsigned i = 0; i < maxElements; ++i) {
1191 // Don't attempt to go past the end of the init list
1192 if (Index >= IList->getNumInits())
1193 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194
John McCall20e047a2010-10-30 00:11:39 +00001195 ElementEntity.setElementIndex(Index);
1196
1197 QualType IType = IList->getInit(Index)->getType();
1198 if (!IType->isVectorType()) {
1199 CheckSubElementType(ElementEntity, IList, elementType, Index,
1200 StructuredList, StructuredIndex);
1201 ++numEltsInit;
1202 } else {
1203 QualType VecType;
1204 const VectorType *IVT = IType->getAs<VectorType>();
1205 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001206
John McCall20e047a2010-10-30 00:11:39 +00001207 if (IType->isExtVectorType())
1208 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1209 else
1210 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001211 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001212 CheckSubElementType(ElementEntity, IList, VecType, Index,
1213 StructuredList, StructuredIndex);
1214 numEltsInit += numIElts;
1215 }
1216 }
1217
1218 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001219 if (numEltsInit != maxElements) {
1220 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001221 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001222 diag::err_vector_incorrect_num_initializers)
1223 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1224 hadError = true;
1225 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001226}
1227
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001228void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001229 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001230 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001231 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001232 unsigned &Index,
1233 InitListExpr *StructuredList,
1234 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001235 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1236
Steve Naroff0cca7492008-05-01 22:18:59 +00001237 // Check for the special-case of initializing an array with a string.
1238 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001239 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1240 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001241 // We place the string literal directly into the resulting
1242 // initializer list. This is the only place where the structure
1243 // of the structured initializer list doesn't match exactly,
1244 // because doing so would involve allocating one character
1245 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001246 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001247 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1248 UpdateStructuredListElement(StructuredList, StructuredIndex,
1249 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001250 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1251 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001252 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001253 return;
1254 }
1255 }
John McCallce6c9b72011-02-21 07:22:22 +00001256 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001257 // Check for VLAs; in standard C it would be possible to check this
1258 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1259 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001260 if (!VerifyOnly)
1261 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1262 diag::err_variable_object_no_init)
1263 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001264 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001265 ++Index;
1266 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001267 return;
1268 }
1269
Douglas Gregor05c13a32009-01-22 00:58:24 +00001270 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001271 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1272 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001273 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001274 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001275 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001276 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001277 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001278 maxElementsKnown = true;
1279 }
1280
John McCallce6c9b72011-02-21 07:22:22 +00001281 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001282 while (Index < IList->getNumInits()) {
1283 Expr *Init = IList->getInit(Index);
1284 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001285 // If we're not the subobject that matches up with the '{' for
1286 // the designator, we shouldn't be handling the
1287 // designator. Return immediately.
1288 if (!SubobjectIsDesignatorContext)
1289 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001290
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001291 // Handle this designated initializer. elementIndex will be
1292 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001293 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001294 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001295 StructuredList, StructuredIndex, true,
1296 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001297 hadError = true;
1298 continue;
1299 }
1300
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001301 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001302 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001303 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001304 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001305 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001306
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001307 // If the array is of incomplete type, keep track of the number of
1308 // elements in the initializer.
1309 if (!maxElementsKnown && elementIndex > maxElements)
1310 maxElements = elementIndex;
1311
Douglas Gregor05c13a32009-01-22 00:58:24 +00001312 continue;
1313 }
1314
1315 // If we know the maximum number of elements, and we've already
1316 // hit it, stop consuming elements in the initializer list.
1317 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001318 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001319
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001320 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001321 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001322 Entity);
1323 // Check this element.
1324 CheckSubElementType(ElementEntity, IList, elementType, Index,
1325 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001326 ++elementIndex;
1327
1328 // If the array is of incomplete type, keep track of the number of
1329 // elements in the initializer.
1330 if (!maxElementsKnown && elementIndex > maxElements)
1331 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001332 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001333 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001334 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001335 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001336 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001337 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001338 // Sizing an array implicitly to zero is not allowed by ISO C,
1339 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001340 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001341 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001342 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001343
Mike Stump1eb44332009-09-09 15:08:12 +00001344 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001345 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001346 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001347 if (!hadError && VerifyOnly) {
1348 // Check if there are any members of the array that get value-initialized.
1349 // If so, check if doing that is possible.
1350 // FIXME: This needs to detect holes left by designated initializers too.
1351 if (maxElementsKnown && elementIndex < maxElements)
1352 CheckValueInitializable(InitializedEntity::InitializeElement(
1353 SemaRef.Context, 0, Entity));
1354 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001355}
1356
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001357bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1358 Expr *InitExpr,
1359 FieldDecl *Field,
1360 bool TopLevelObject) {
1361 // Handle GNU flexible array initializers.
1362 unsigned FlexArrayDiag;
1363 if (isa<InitListExpr>(InitExpr) &&
1364 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1365 // Empty flexible array init always allowed as an extension
1366 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001367 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001368 // Disallow flexible array init in C++; it is not required for gcc
1369 // compatibility, and it needs work to IRGen correctly in general.
1370 FlexArrayDiag = diag::err_flexible_array_init;
1371 } else if (!TopLevelObject) {
1372 // Disallow flexible array init on non-top-level object
1373 FlexArrayDiag = diag::err_flexible_array_init;
1374 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1375 // Disallow flexible array init on anything which is not a variable.
1376 FlexArrayDiag = diag::err_flexible_array_init;
1377 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1378 // Disallow flexible array init on local variables.
1379 FlexArrayDiag = diag::err_flexible_array_init;
1380 } else {
1381 // Allow other cases.
1382 FlexArrayDiag = diag::ext_flexible_array_init;
1383 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001384
1385 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001386 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001387 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001388 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001389 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1390 << Field;
1391 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001392
1393 return FlexArrayDiag != diag::ext_flexible_array_init;
1394}
1395
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001396void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001397 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001398 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001399 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001400 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001401 unsigned &Index,
1402 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001403 unsigned &StructuredIndex,
1404 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001405 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Eli Friedmanb85f7072008-05-19 19:16:24 +00001407 // If the record is invalid, some of it's members are invalid. To avoid
1408 // confusion, we forgo checking the intializer for the entire record.
1409 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001410 // Assume it was supposed to consume a single initializer.
1411 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001412 hadError = true;
1413 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001414 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001415
1416 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001417 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001418
1419 // If there's a default initializer, use it.
1420 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1421 if (VerifyOnly)
1422 return;
1423 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1424 Field != FieldEnd; ++Field) {
1425 if (Field->hasInClassInitializer()) {
1426 StructuredList->setInitializedFieldInUnion(*Field);
1427 // FIXME: Actually build a CXXDefaultInitExpr?
1428 return;
1429 }
1430 }
1431 }
1432
1433 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001434 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1435 Field != FieldEnd; ++Field) {
1436 if (Field->getDeclName()) {
1437 if (VerifyOnly)
1438 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001439 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001440 else
David Blaikie581deb32012-06-06 20:45:41 +00001441 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001442 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001443 }
1444 }
1445 return;
1446 }
1447
Douglas Gregor05c13a32009-01-22 00:58:24 +00001448 // If structDecl is a forward declaration, this loop won't do
1449 // anything except look at designated initializers; That's okay,
1450 // because an error should get printed out elsewhere. It might be
1451 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001452 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001453 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001454 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001455 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001456 while (Index < IList->getNumInits()) {
1457 Expr *Init = IList->getInit(Index);
1458
1459 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001460 // If we're not the subobject that matches up with the '{' for
1461 // the designator, we shouldn't be handling the
1462 // designator. Return immediately.
1463 if (!SubobjectIsDesignatorContext)
1464 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001465
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001466 // Handle this designated initializer. Field will be updated to
1467 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001468 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001469 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001470 StructuredList, StructuredIndex,
1471 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001472 hadError = true;
1473
Douglas Gregordfb5e592009-02-12 19:00:39 +00001474 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001475
1476 // Disable check for missing fields when designators are used.
1477 // This matches gcc behaviour.
1478 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001479 continue;
1480 }
1481
1482 if (Field == FieldEnd) {
1483 // We've run out of fields. We're done.
1484 break;
1485 }
1486
Douglas Gregordfb5e592009-02-12 19:00:39 +00001487 // We've already initialized a member of a union. We're done.
1488 if (InitializedSomething && DeclType->isUnionType())
1489 break;
1490
Douglas Gregor44b43212008-12-11 16:49:14 +00001491 // If we've hit the flexible array member at the end, we're done.
1492 if (Field->getType()->isIncompleteArrayType())
1493 break;
1494
Douglas Gregor0bb76892009-01-29 16:53:55 +00001495 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001496 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001497 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001498 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001499 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001500
Douglas Gregor54001c12011-06-29 21:51:31 +00001501 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001502 bool InvalidUse;
1503 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001504 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001505 else
David Blaikie581deb32012-06-06 20:45:41 +00001506 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001507 IList->getInit(Index)->getLocStart());
1508 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001509 ++Index;
1510 ++Field;
1511 hadError = true;
1512 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001513 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001514
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001515 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001516 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001517 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1518 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001519 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001520
Sebastian Redl14b0c192011-09-24 17:48:00 +00001521 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001522 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001523 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001524 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001525
1526 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001527 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001528
John McCall80639de2010-03-11 19:32:38 +00001529 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001530 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1531 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1532 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001533 // It is possible we have one or more unnamed bitfields remaining.
1534 // Find first (if any) named field and emit warning.
1535 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1536 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001537 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001538 SemaRef.Diag(IList->getSourceRange().getEnd(),
1539 diag::warn_missing_field_initializers) << it->getName();
1540 break;
1541 }
1542 }
1543 }
1544
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001545 // Check that any remaining fields can be value-initialized.
1546 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1547 !Field->getType()->isIncompleteArrayType()) {
1548 // FIXME: Should check for holes left by designated initializers too.
1549 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001550 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001551 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001552 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001553 }
1554 }
1555
Mike Stump1eb44332009-09-09 15:08:12 +00001556 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001557 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001558 return;
1559
David Blaikie581deb32012-06-06 20:45:41 +00001560 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001561 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001562 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001563 ++Index;
1564 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001565 }
1566
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001567 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001568 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001569
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001570 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001571 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001572 StructuredList, StructuredIndex);
1573 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001574 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001575 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001576}
Steve Naroff0cca7492008-05-01 22:18:59 +00001577
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001578/// \brief Expand a field designator that refers to a member of an
1579/// anonymous struct or union into a series of field designators that
1580/// refers to the field within the appropriate subobject.
1581///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001582static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001583 DesignatedInitExpr *DIE,
1584 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001585 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001586 typedef DesignatedInitExpr::Designator Designator;
1587
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001588 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001589 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001590 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1591 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1592 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001593 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001594 DIE->getDesignator(DesigIdx)->getDotLoc(),
1595 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1596 else
1597 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1598 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001599 assert(isa<FieldDecl>(*PI));
1600 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001601 }
1602
1603 // Expand the current designator into the set of replacement
1604 // designators, so we have a full subobject path down to where the
1605 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001606 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001607 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001608}
Mike Stump1eb44332009-09-09 15:08:12 +00001609
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001610/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001611/// corresponds to FieldName.
1612static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1613 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001614 if (!FieldName)
1615 return 0;
1616
Francois Picheta0e27f02010-12-22 03:46:10 +00001617 assert(AnonField->isAnonymousStructOrUnion());
1618 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001619 while (IndirectFieldDecl *IF =
1620 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001621 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001622 return IF;
1623 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001624 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001625 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001626}
1627
Sebastian Redl14b0c192011-09-24 17:48:00 +00001628static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1629 DesignatedInitExpr *DIE) {
1630 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1631 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1632 for (unsigned I = 0; I < NumIndexExprs; ++I)
1633 IndexExprs[I] = DIE->getSubExpr(I + 1);
1634 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001635 DIE->size(), IndexExprs,
1636 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001637 DIE->usesGNUSyntax(), DIE->getInit());
1638}
1639
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001640namespace {
1641
1642// Callback to only accept typo corrections that are for field members of
1643// the given struct or union.
1644class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1645 public:
1646 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1647 : Record(RD) {}
1648
1649 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1650 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1651 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1652 }
1653
1654 private:
1655 RecordDecl *Record;
1656};
1657
1658}
1659
Douglas Gregor05c13a32009-01-22 00:58:24 +00001660/// @brief Check the well-formedness of a C99 designated initializer.
1661///
1662/// Determines whether the designated initializer @p DIE, which
1663/// resides at the given @p Index within the initializer list @p
1664/// IList, is well-formed for a current object of type @p DeclType
1665/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001666/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001667/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001668///
1669/// @param IList The initializer list in which this designated
1670/// initializer occurs.
1671///
Douglas Gregor71199712009-04-15 04:56:10 +00001672/// @param DIE The designated initializer expression.
1673///
1674/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001675///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001676/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001677/// into which the designation in @p DIE should refer.
1678///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001679/// @param NextField If non-NULL and the first designator in @p DIE is
1680/// a field, this will be set to the field declaration corresponding
1681/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001682///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001683/// @param NextElementIndex If non-NULL and the first designator in @p
1684/// DIE is an array designator or GNU array-range designator, this
1685/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001686///
1687/// @param Index Index into @p IList where the designated initializer
1688/// @p DIE occurs.
1689///
Douglas Gregor4c678342009-01-28 21:54:33 +00001690/// @param StructuredList The initializer list expression that
1691/// describes all of the subobject initializers in the order they'll
1692/// actually be initialized.
1693///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001694/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001695bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001696InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001697 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001698 DesignatedInitExpr *DIE,
1699 unsigned DesigIdx,
1700 QualType &CurrentObjectType,
1701 RecordDecl::field_iterator *NextField,
1702 llvm::APSInt *NextElementIndex,
1703 unsigned &Index,
1704 InitListExpr *StructuredList,
1705 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001706 bool FinishSubobjectInit,
1707 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001708 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001709 // Check the actual initialization for the designated object type.
1710 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001711
1712 // Temporarily remove the designator expression from the
1713 // initializer list that the child calls see, so that we don't try
1714 // to re-process the designator.
1715 unsigned OldIndex = Index;
1716 IList->setInit(OldIndex, DIE->getInit());
1717
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001718 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001719 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001720
1721 // Restore the designated initializer expression in the syntactic
1722 // form of the initializer list.
1723 if (IList->getInit(OldIndex) != DIE->getInit())
1724 DIE->setInit(IList->getInit(OldIndex));
1725 IList->setInit(OldIndex, DIE);
1726
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001727 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001728 }
1729
Douglas Gregor71199712009-04-15 04:56:10 +00001730 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001731 bool IsFirstDesignator = (DesigIdx == 0);
1732 if (!VerifyOnly) {
1733 assert((IsFirstDesignator || StructuredList) &&
1734 "Need a non-designated initializer list to start from");
1735
1736 // Determine the structural initializer list that corresponds to the
1737 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001738 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001739 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1740 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001741 SourceRange(D->getLocStart(),
1742 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001743 assert(StructuredList && "Expected a structured initializer list");
1744 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001745
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001746 if (D->isFieldDesignator()) {
1747 // C99 6.7.8p7:
1748 //
1749 // If a designator has the form
1750 //
1751 // . identifier
1752 //
1753 // then the current object (defined below) shall have
1754 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001755 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001756 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001757 if (!RT) {
1758 SourceLocation Loc = D->getDotLoc();
1759 if (Loc.isInvalid())
1760 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001761 if (!VerifyOnly)
1762 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001763 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001764 ++Index;
1765 return true;
1766 }
1767
Douglas Gregor4c678342009-01-28 21:54:33 +00001768 // Note: we perform a linear search of the fields here, despite
1769 // the fact that we have a faster lookup method, because we always
1770 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001771 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001772 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001773 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001774 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001775 Field = RT->getDecl()->field_begin(),
1776 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001777 for (; Field != FieldEnd; ++Field) {
1778 if (Field->isUnnamedBitfield())
1779 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780
Francois Picheta0e27f02010-12-22 03:46:10 +00001781 // If we find a field representing an anonymous field, look in the
1782 // IndirectFieldDecl that follow for the designated initializer.
1783 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1784 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001785 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001786 // In verify mode, don't modify the original.
1787 if (VerifyOnly)
1788 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001789 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1790 D = DIE->getDesignator(DesigIdx);
1791 break;
1792 }
1793 }
David Blaikie581deb32012-06-06 20:45:41 +00001794 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001795 break;
1796 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 break;
1798
1799 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001800 }
1801
Douglas Gregor4c678342009-01-28 21:54:33 +00001802 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001803 if (VerifyOnly) {
1804 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001805 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001806 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001807
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001808 // There was no normal field in the struct with the designated
1809 // name. Perform another lookup for this name, which may find
1810 // something that we can't designate (e.g., a member function),
1811 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001812 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001813 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001814 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001815 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001816 // Name lookup didn't find anything. Determine whether this
1817 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001818 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001819 TypoCorrection Corrected = SemaRef.CorrectTypo(
1820 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001821 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001822 RT->getDecl());
1823 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001824 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001825 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001826 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001827 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001828 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001829 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001830 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001831 << FieldName << CurrentObjectType << CorrectedQuotedStr
1832 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001833 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001834 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001835 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001836 } else {
1837 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1838 << FieldName << CurrentObjectType;
1839 ++Index;
1840 return true;
1841 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001842 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001843
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001844 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001845 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001846 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001847 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001848 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001849 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001850 ++Index;
1851 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001852 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001853
Francois Picheta0e27f02010-12-22 03:46:10 +00001854 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001855 // The replacement field comes from typo correction; find it
1856 // in the list of fields.
1857 FieldIndex = 0;
1858 Field = RT->getDecl()->field_begin();
1859 for (; Field != FieldEnd; ++Field) {
1860 if (Field->isUnnamedBitfield())
1861 continue;
1862
David Blaikie581deb32012-06-06 20:45:41 +00001863 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001864 Field->getIdentifier() == ReplacementField->getIdentifier())
1865 break;
1866
1867 ++FieldIndex;
1868 }
1869 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001870 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001871
1872 // All of the fields of a union are located at the same place in
1873 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001874 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001875 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001876 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001877 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001878 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001879
Douglas Gregor54001c12011-06-29 21:51:31 +00001880 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001881 bool InvalidUse;
1882 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001883 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001884 else
David Blaikie581deb32012-06-06 20:45:41 +00001885 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001886 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001887 ++Index;
1888 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001889 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001890
Sebastian Redl14b0c192011-09-24 17:48:00 +00001891 if (!VerifyOnly) {
1892 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001893 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Sebastian Redl14b0c192011-09-24 17:48:00 +00001895 // Make sure that our non-designated initializer list has space
1896 // for a subobject corresponding to this field.
1897 if (FieldIndex >= StructuredList->getNumInits())
1898 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1899 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001900
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001901 // This designator names a flexible array member.
1902 if (Field->getType()->isIncompleteArrayType()) {
1903 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001904 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001905 // We can't designate an object within the flexible array
1906 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001907 if (!VerifyOnly) {
1908 DesignatedInitExpr::Designator *NextD
1909 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001910 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001911 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001912 << SourceRange(NextD->getLocStart(),
1913 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001914 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001915 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001916 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001917 Invalid = true;
1918 }
1919
Chris Lattner9046c222010-10-10 17:49:49 +00001920 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1921 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001922 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001923 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001924 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001925 diag::err_flexible_array_init_needs_braces)
1926 << DIE->getInit()->getSourceRange();
1927 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001928 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001929 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001930 Invalid = true;
1931 }
1932
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001933 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001934 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001935 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001936 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001937
1938 if (Invalid) {
1939 ++Index;
1940 return true;
1941 }
1942
1943 // Initialize the array.
1944 bool prevHadError = hadError;
1945 unsigned newStructuredIndex = FieldIndex;
1946 unsigned OldIndex = Index;
1947 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001948
1949 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001950 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001951 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001952 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001953
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001954 IList->setInit(OldIndex, DIE);
1955 if (hadError && !prevHadError) {
1956 ++Field;
1957 ++FieldIndex;
1958 if (NextField)
1959 *NextField = Field;
1960 StructuredIndex = FieldIndex;
1961 return true;
1962 }
1963 } else {
1964 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001965 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001966 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001967
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001968 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001969 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001970 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1971 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001972 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001973 true, false))
1974 return true;
1975 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001976
1977 // Find the position of the next field to be initialized in this
1978 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001979 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001980 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001981
1982 // If this the first designator, our caller will continue checking
1983 // the rest of this struct/class/union subobject.
1984 if (IsFirstDesignator) {
1985 if (NextField)
1986 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001987 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001988 return false;
1989 }
1990
Douglas Gregor34e79462009-01-28 23:36:17 +00001991 if (!FinishSubobjectInit)
1992 return false;
1993
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001994 // We've already initialized something in the union; we're done.
1995 if (RT->getDecl()->isUnion())
1996 return hadError;
1997
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001998 // Check the remaining fields within this class/struct/union subobject.
1999 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002000
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002001 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002002 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002003 return hadError && !prevHadError;
2004 }
2005
2006 // C99 6.7.8p6:
2007 //
2008 // If a designator has the form
2009 //
2010 // [ constant-expression ]
2011 //
2012 // then the current object (defined below) shall have array
2013 // type and the expression shall be an integer constant
2014 // expression. If the array is of unknown size, any
2015 // nonnegative value is valid.
2016 //
2017 // Additionally, cope with the GNU extension that permits
2018 // designators of the form
2019 //
2020 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002021 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002022 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002023 if (!VerifyOnly)
2024 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2025 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002026 ++Index;
2027 return true;
2028 }
2029
2030 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00002031 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2032 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002033 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002034 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002035 DesignatedEndIndex = DesignatedStartIndex;
2036 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002037 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002038
Mike Stump1eb44332009-09-09 15:08:12 +00002039 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002040 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002041 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002042 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002043 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002044
Chris Lattnere0fd8322011-02-19 22:28:58 +00002045 // Codegen can't handle evaluating array range designators that have side
2046 // effects, because we replicate the AST value for each initialized element.
2047 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2048 // elements with something that has a side effect, so codegen can emit an
2049 // "error unsupported" error instead of miscompiling the app.
2050 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002051 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002052 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002053 }
2054
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002055 if (isa<ConstantArrayType>(AT)) {
2056 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002057 DesignatedStartIndex
2058 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002059 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002060 DesignatedEndIndex
2061 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002062 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2063 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002064 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002065 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002066 diag::err_array_designator_too_large)
2067 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2068 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002069 ++Index;
2070 return true;
2071 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002072 } else {
2073 // Make sure the bit-widths and signedness match.
2074 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002075 DesignatedEndIndex
2076 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002077 else if (DesignatedStartIndex.getBitWidth() <
2078 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002079 DesignatedStartIndex
2080 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002081 DesignatedStartIndex.setIsUnsigned(true);
2082 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002083 }
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregor4c678342009-01-28 21:54:33 +00002085 // Make sure that our non-designated initializer list has space
2086 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002087 if (!VerifyOnly &&
2088 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002089 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002090 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002091
Douglas Gregor34e79462009-01-28 23:36:17 +00002092 // Repeatedly perform subobject initializations in the range
2093 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002094
Douglas Gregor34e79462009-01-28 23:36:17 +00002095 // Move to the next designator
2096 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2097 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002098
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002099 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002100 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002101
Douglas Gregor34e79462009-01-28 23:36:17 +00002102 while (DesignatedStartIndex <= DesignatedEndIndex) {
2103 // Recurse to check later designated subobjects.
2104 QualType ElementType = AT->getElementType();
2105 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002106
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002107 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002108 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2109 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002110 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002111 (DesignatedStartIndex == DesignatedEndIndex),
2112 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002113 return true;
2114
2115 // Move to the next index in the array that we'll be initializing.
2116 ++DesignatedStartIndex;
2117 ElementIndex = DesignatedStartIndex.getZExtValue();
2118 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002119
2120 // If this the first designator, our caller will continue checking
2121 // the rest of this array subobject.
2122 if (IsFirstDesignator) {
2123 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002124 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002125 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002126 return false;
2127 }
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Douglas Gregor34e79462009-01-28 23:36:17 +00002129 if (!FinishSubobjectInit)
2130 return false;
2131
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002132 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002133 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002134 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002135 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002136 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002137 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002138}
2139
Douglas Gregor4c678342009-01-28 21:54:33 +00002140// Get the structured initializer list for a subobject of type
2141// @p CurrentObjectType.
2142InitListExpr *
2143InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2144 QualType CurrentObjectType,
2145 InitListExpr *StructuredList,
2146 unsigned StructuredIndex,
2147 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002148 if (VerifyOnly)
2149 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002150 Expr *ExistingInit = 0;
2151 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002152 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002153 else if (StructuredIndex < StructuredList->getNumInits())
2154 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Douglas Gregor4c678342009-01-28 21:54:33 +00002156 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2157 return Result;
2158
2159 if (ExistingInit) {
2160 // We are creating an initializer list that initializes the
2161 // subobjects of the current object, but there was already an
2162 // initialization that completely initialized the current
2163 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002164 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002165 // struct X { int a, b; };
2166 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002167 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002168 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2169 // designated initializer re-initializes the whole
2170 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002171 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002172 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002173 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002174 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002175 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002176 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002177 << ExistingInit->getSourceRange();
2178 }
2179
Mike Stump1eb44332009-09-09 15:08:12 +00002180 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002181 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002182 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002183 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002184
Eli Friedman5c89c392012-02-23 02:25:10 +00002185 QualType ResultType = CurrentObjectType;
2186 if (!ResultType->isArrayType())
2187 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2188 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002189
Douglas Gregorfa219202009-03-20 23:58:33 +00002190 // Pre-allocate storage for the structured initializer list.
2191 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002192 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002193 bool GotNumInits = false;
2194 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002195 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002196 GotNumInits = true;
2197 } else if (Index < IList->getNumInits()) {
2198 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002199 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002200 GotNumInits = true;
2201 }
Douglas Gregor08457732009-03-21 18:13:52 +00002202 }
2203
Mike Stump1eb44332009-09-09 15:08:12 +00002204 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002205 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2206 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2207 NumElements = CAType->getSize().getZExtValue();
2208 // Simple heuristic so that we don't allocate a very large
2209 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002210 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002211 NumElements = 0;
2212 }
John McCall183700f2009-09-21 23:43:11 +00002213 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002214 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002215 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002216 RecordDecl *RDecl = RType->getDecl();
2217 if (RDecl->isUnion())
2218 NumElements = 1;
2219 else
Mike Stump1eb44332009-09-09 15:08:12 +00002220 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002221 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002222 }
2223
Ted Kremenek709210f2010-04-13 23:39:13 +00002224 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002225
Douglas Gregor4c678342009-01-28 21:54:33 +00002226 // Link this new initializer list into the structured initializer
2227 // lists.
2228 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002229 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002230 else {
2231 Result->setSyntacticForm(IList);
2232 SyntacticToSemantic[IList] = Result;
2233 }
2234
2235 return Result;
2236}
2237
2238/// Update the initializer at index @p StructuredIndex within the
2239/// structured initializer list to the value @p expr.
2240void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2241 unsigned &StructuredIndex,
2242 Expr *expr) {
2243 // No structured initializer list to update
2244 if (!StructuredList)
2245 return;
2246
Ted Kremenek709210f2010-04-13 23:39:13 +00002247 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2248 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002249 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002250 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002251 diag::warn_initializer_overrides)
2252 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002253 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002254 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002255 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002256 << PrevInit->getSourceRange();
2257 }
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Douglas Gregor4c678342009-01-28 21:54:33 +00002259 ++StructuredIndex;
2260}
2261
Douglas Gregor05c13a32009-01-22 00:58:24 +00002262/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002263/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002264/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002265/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002266/// failure. Returns the index expression, possibly with an implicit cast
2267/// added, on success. If everything went okay, Value will receive the
2268/// value of the constant expression.
2269static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002270CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002271 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002272
2273 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002274 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2275 if (Result.isInvalid())
2276 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002277
Chris Lattner3bf68932009-04-25 21:59:05 +00002278 if (Value.isSigned() && Value.isNegative())
2279 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002280 << Value.toString(10) << Index->getSourceRange();
2281
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002282 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002283 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002284}
2285
John McCall60d7b3a2010-08-24 06:29:42 +00002286ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002287 SourceLocation Loc,
2288 bool GNUSyntax,
2289 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002290 typedef DesignatedInitExpr::Designator ASTDesignator;
2291
2292 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002293 SmallVector<ASTDesignator, 32> Designators;
2294 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002295
2296 // Build designators and check array designator expressions.
2297 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2298 const Designator &D = Desig.getDesignator(Idx);
2299 switch (D.getKind()) {
2300 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002301 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002302 D.getFieldLoc()));
2303 break;
2304
2305 case Designator::ArrayDesignator: {
2306 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2307 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002308 if (!Index->isTypeDependent() && !Index->isValueDependent())
2309 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2310 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002311 Invalid = true;
2312 else {
2313 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002314 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002315 D.getRBracketLoc()));
2316 InitExpressions.push_back(Index);
2317 }
2318 break;
2319 }
2320
2321 case Designator::ArrayRangeDesignator: {
2322 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2323 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2324 llvm::APSInt StartValue;
2325 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002326 bool StartDependent = StartIndex->isTypeDependent() ||
2327 StartIndex->isValueDependent();
2328 bool EndDependent = EndIndex->isTypeDependent() ||
2329 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002330 if (!StartDependent)
2331 StartIndex =
2332 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2333 if (!EndDependent)
2334 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2335
2336 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002337 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002338 else {
2339 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002340 if (StartDependent || EndDependent) {
2341 // Nothing to compute.
2342 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002343 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002344 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002345 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002346
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002347 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002348 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002349 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002350 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2351 Invalid = true;
2352 } else {
2353 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002354 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002355 D.getEllipsisLoc(),
2356 D.getRBracketLoc()));
2357 InitExpressions.push_back(StartIndex);
2358 InitExpressions.push_back(EndIndex);
2359 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002360 }
2361 break;
2362 }
2363 }
2364 }
2365
2366 if (Invalid || Init.isInvalid())
2367 return ExprError();
2368
2369 // Clear out the expressions within the designation.
2370 Desig.ClearExprs(*this);
2371
2372 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002373 = DesignatedInitExpr::Create(Context,
2374 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002375 InitExpressions, Loc, GNUSyntax,
2376 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002377
David Blaikie4e4d0842012-03-11 07:00:24 +00002378 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002379 Diag(DIE->getLocStart(), diag::ext_designated_init)
2380 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002381
Douglas Gregor05c13a32009-01-22 00:58:24 +00002382 return Owned(DIE);
2383}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002384
Douglas Gregor20093b42009-12-09 23:02:17 +00002385//===----------------------------------------------------------------------===//
2386// Initialization entity
2387//===----------------------------------------------------------------------===//
2388
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002389InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002390 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002391 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002392{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002393 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2394 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002395 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002396 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002397 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002398 Type = VT->getElementType();
2399 } else {
2400 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2401 assert(CT && "Unexpected type");
2402 Kind = EK_ComplexElement;
2403 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002404 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002405}
2406
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002407InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002408 CXXBaseSpecifier *Base,
2409 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002410{
2411 InitializedEntity Result;
2412 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002413 Result.Base = reinterpret_cast<uintptr_t>(Base);
2414 if (IsInheritedVirtualBase)
2415 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002416
Douglas Gregord6542d82009-12-22 15:35:07 +00002417 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002418 return Result;
2419}
2420
Douglas Gregor99a2e602009-12-16 01:38:02 +00002421DeclarationName InitializedEntity::getName() const {
2422 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002423 case EK_Parameter: {
2424 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2425 return (D ? D->getDeclName() : DeclarationName());
2426 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002427
2428 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002429 case EK_Member:
2430 return VariableOrMember->getDeclName();
2431
Douglas Gregor47736542012-02-15 16:57:26 +00002432 case EK_LambdaCapture:
2433 return Capture.Var->getDeclName();
2434
Douglas Gregor99a2e602009-12-16 01:38:02 +00002435 case EK_Result:
2436 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002437 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002438 case EK_Temporary:
2439 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002440 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002441 case EK_ArrayElement:
2442 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002443 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002444 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002445 case EK_CompoundLiteralInit:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002446 return DeclarationName();
2447 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002448
David Blaikie7530c032012-01-17 06:56:22 +00002449 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002450}
2451
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002452DeclaratorDecl *InitializedEntity::getDecl() const {
2453 switch (getKind()) {
2454 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002455 case EK_Member:
2456 return VariableOrMember;
2457
John McCallf85e1932011-06-15 23:02:42 +00002458 case EK_Parameter:
2459 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2460
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002461 case EK_Result:
2462 case EK_Exception:
2463 case EK_New:
2464 case EK_Temporary:
2465 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002466 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002467 case EK_ArrayElement:
2468 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002469 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002470 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002471 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002472 case EK_CompoundLiteralInit:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002473 return 0;
2474 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002475
David Blaikie7530c032012-01-17 06:56:22 +00002476 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002477}
2478
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002479bool InitializedEntity::allowsNRVO() const {
2480 switch (getKind()) {
2481 case EK_Result:
2482 case EK_Exception:
2483 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002484
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002485 case EK_Variable:
2486 case EK_Parameter:
2487 case EK_Member:
2488 case EK_New:
2489 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002490 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002491 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002492 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002493 case EK_ArrayElement:
2494 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002495 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002496 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002497 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002498 break;
2499 }
2500
2501 return false;
2502}
2503
Douglas Gregor20093b42009-12-09 23:02:17 +00002504//===----------------------------------------------------------------------===//
2505// Initialization sequence
2506//===----------------------------------------------------------------------===//
2507
2508void InitializationSequence::Step::Destroy() {
2509 switch (Kind) {
2510 case SK_ResolveAddressOfOverloadedFunction:
2511 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002512 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002513 case SK_CastDerivedToBaseLValue:
2514 case SK_BindReference:
2515 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002516 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002517 case SK_UserConversion:
2518 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002519 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002520 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002521 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002522 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002523 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002524 case SK_UnwrapInitList:
2525 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002526 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002527 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002528 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002529 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002530 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002531 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002532 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002533 case SK_PassByIndirectCopyRestore:
2534 case SK_PassByIndirectRestore:
2535 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002536 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002537 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002538 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002539 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002540
Douglas Gregor20093b42009-12-09 23:02:17 +00002541 case SK_ConversionSequence:
2542 delete ICS;
2543 }
2544}
2545
Douglas Gregorb70cf442010-03-26 20:14:36 +00002546bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002547 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002548}
2549
2550bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002551 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002552 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002553
Douglas Gregorb70cf442010-03-26 20:14:36 +00002554 switch (getFailureKind()) {
2555 case FK_TooManyInitsForReference:
2556 case FK_ArrayNeedsInitList:
2557 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002558 case FK_ArrayNeedsInitListOrWideStringLiteral:
2559 case FK_NarrowStringIntoWideCharArray:
2560 case FK_WideStringIntoCharArray:
2561 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002562 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2563 case FK_NonConstLValueReferenceBindingToTemporary:
2564 case FK_NonConstLValueReferenceBindingToUnrelated:
2565 case FK_RValueReferenceBindingToLValue:
2566 case FK_ReferenceInitDropsQualifiers:
2567 case FK_ReferenceInitFailed:
2568 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002569 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002570 case FK_TooManyInitsForScalar:
2571 case FK_ReferenceBindingToInitList:
2572 case FK_InitListBadDestinationType:
2573 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002574 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002575 case FK_ArrayTypeMismatch:
2576 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002577 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002578 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002579 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002580 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002581 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002582 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002583
Douglas Gregorb70cf442010-03-26 20:14:36 +00002584 case FK_ReferenceInitOverloadFailed:
2585 case FK_UserConversionOverloadFailed:
2586 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002587 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002588 return FailedOverloadResult == OR_Ambiguous;
2589 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002590
David Blaikie7530c032012-01-17 06:56:22 +00002591 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002592}
2593
Douglas Gregord6e44a32010-04-16 22:09:46 +00002594bool InitializationSequence::isConstructorInitialization() const {
2595 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2596}
2597
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002598void
2599InitializationSequence
2600::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2601 DeclAccessPair Found,
2602 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002603 Step S;
2604 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2605 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002606 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002607 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002608 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002609 Steps.push_back(S);
2610}
2611
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002612void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002613 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002614 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002615 switch (VK) {
2616 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2617 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2618 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002619 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002620 S.Type = BaseType;
2621 Steps.push_back(S);
2622}
2623
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002624void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002625 bool BindingTemporary) {
2626 Step S;
2627 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2628 S.Type = T;
2629 Steps.push_back(S);
2630}
2631
Douglas Gregor523d46a2010-04-18 07:40:54 +00002632void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2633 Step S;
2634 S.Kind = SK_ExtraneousCopyToTemporary;
2635 S.Type = T;
2636 Steps.push_back(S);
2637}
2638
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002639void
2640InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2641 DeclAccessPair FoundDecl,
2642 QualType T,
2643 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002644 Step S;
2645 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002646 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002647 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002648 S.Function.Function = Function;
2649 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002650 Steps.push_back(S);
2651}
2652
2653void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002654 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002655 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002656 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002657 switch (VK) {
2658 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002659 S.Kind = SK_QualificationConversionRValue;
2660 break;
John McCall5baba9d2010-08-25 10:28:54 +00002661 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002662 S.Kind = SK_QualificationConversionXValue;
2663 break;
John McCall5baba9d2010-08-25 10:28:54 +00002664 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002665 S.Kind = SK_QualificationConversionLValue;
2666 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002667 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002668 S.Type = Ty;
2669 Steps.push_back(S);
2670}
2671
Jordan Rose1fd1e282013-04-11 00:58:58 +00002672void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2673 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2674
2675 Step S;
2676 S.Kind = SK_LValueToRValue;
2677 S.Type = Ty;
2678 Steps.push_back(S);
2679}
2680
Douglas Gregor20093b42009-12-09 23:02:17 +00002681void InitializationSequence::AddConversionSequenceStep(
2682 const ImplicitConversionSequence &ICS,
2683 QualType T) {
2684 Step S;
2685 S.Kind = SK_ConversionSequence;
2686 S.Type = T;
2687 S.ICS = new ImplicitConversionSequence(ICS);
2688 Steps.push_back(S);
2689}
2690
Douglas Gregord87b61f2009-12-10 17:56:55 +00002691void InitializationSequence::AddListInitializationStep(QualType T) {
2692 Step S;
2693 S.Kind = SK_ListInitialization;
2694 S.Type = T;
2695 Steps.push_back(S);
2696}
2697
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002698void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002699InitializationSequence
2700::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2701 AccessSpecifier Access,
2702 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002703 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002704 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002705 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002706 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2707 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002708 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002709 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002710 S.Function.Function = Constructor;
2711 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002712 Steps.push_back(S);
2713}
2714
Douglas Gregor71d17402009-12-15 00:01:57 +00002715void InitializationSequence::AddZeroInitializationStep(QualType T) {
2716 Step S;
2717 S.Kind = SK_ZeroInitialization;
2718 S.Type = T;
2719 Steps.push_back(S);
2720}
2721
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002722void InitializationSequence::AddCAssignmentStep(QualType T) {
2723 Step S;
2724 S.Kind = SK_CAssignment;
2725 S.Type = T;
2726 Steps.push_back(S);
2727}
2728
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002729void InitializationSequence::AddStringInitStep(QualType T) {
2730 Step S;
2731 S.Kind = SK_StringInit;
2732 S.Type = T;
2733 Steps.push_back(S);
2734}
2735
Douglas Gregor569c3162010-08-07 11:51:51 +00002736void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2737 Step S;
2738 S.Kind = SK_ObjCObjectConversion;
2739 S.Type = T;
2740 Steps.push_back(S);
2741}
2742
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002743void InitializationSequence::AddArrayInitStep(QualType T) {
2744 Step S;
2745 S.Kind = SK_ArrayInit;
2746 S.Type = T;
2747 Steps.push_back(S);
2748}
2749
Richard Smith0f163e92012-02-15 22:38:09 +00002750void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2751 Step S;
2752 S.Kind = SK_ParenthesizedArrayInit;
2753 S.Type = T;
2754 Steps.push_back(S);
2755}
2756
John McCallf85e1932011-06-15 23:02:42 +00002757void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2758 bool shouldCopy) {
2759 Step s;
2760 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2761 : SK_PassByIndirectRestore);
2762 s.Type = type;
2763 Steps.push_back(s);
2764}
2765
2766void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2767 Step S;
2768 S.Kind = SK_ProduceObjCObject;
2769 S.Type = T;
2770 Steps.push_back(S);
2771}
2772
Sebastian Redl2b916b82012-01-17 22:49:42 +00002773void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2774 Step S;
2775 S.Kind = SK_StdInitializerList;
2776 S.Type = T;
2777 Steps.push_back(S);
2778}
2779
Guy Benyei21f18c42013-02-07 10:55:47 +00002780void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2781 Step S;
2782 S.Kind = SK_OCLSamplerInit;
2783 S.Type = T;
2784 Steps.push_back(S);
2785}
2786
Guy Benyeie6b9d802013-01-20 12:31:11 +00002787void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2788 Step S;
2789 S.Kind = SK_OCLZeroEvent;
2790 S.Type = T;
2791 Steps.push_back(S);
2792}
2793
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002794void InitializationSequence::RewrapReferenceInitList(QualType T,
2795 InitListExpr *Syntactic) {
2796 assert(Syntactic->getNumInits() == 1 &&
2797 "Can only rewrap trivial init lists.");
2798 Step S;
2799 S.Kind = SK_UnwrapInitList;
2800 S.Type = Syntactic->getInit(0)->getType();
2801 Steps.insert(Steps.begin(), S);
2802
2803 S.Kind = SK_RewrapInitList;
2804 S.Type = T;
2805 S.WrappingSyntacticList = Syntactic;
2806 Steps.push_back(S);
2807}
2808
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002809void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002810 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002811 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002812 this->Failure = Failure;
2813 this->FailedOverloadResult = Result;
2814}
2815
2816//===----------------------------------------------------------------------===//
2817// Attempt initialization
2818//===----------------------------------------------------------------------===//
2819
John McCallf85e1932011-06-15 23:02:42 +00002820static void MaybeProduceObjCObject(Sema &S,
2821 InitializationSequence &Sequence,
2822 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002823 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002824
2825 /// When initializing a parameter, produce the value if it's marked
2826 /// __attribute__((ns_consumed)).
2827 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2828 if (!Entity.isParameterConsumed())
2829 return;
2830
2831 assert(Entity.getType()->isObjCRetainableType() &&
2832 "consuming an object of unretainable type?");
2833 Sequence.AddProduceObjCObjectStep(Entity.getType());
2834
2835 /// When initializing a return value, if the return type is a
2836 /// retainable type, then returns need to immediately retain the
2837 /// object. If an autorelease is required, it will be done at the
2838 /// last instant.
2839 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2840 if (!Entity.getType()->isObjCRetainableType())
2841 return;
2842
2843 Sequence.AddProduceObjCObjectStep(Entity.getType());
2844 }
2845}
2846
Richard Smithf4bb8d02012-07-05 08:39:21 +00002847/// \brief When initializing from init list via constructor, handle
2848/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002849///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002850/// \return true if we have handled initialization of an object of type
2851/// std::initializer_list<T>, false otherwise.
2852static bool TryInitializerListConstruction(Sema &S,
2853 InitListExpr *List,
2854 QualType DestType,
2855 InitializationSequence &Sequence) {
2856 QualType E;
2857 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002858 return false;
2859
Richard Smithf4bb8d02012-07-05 08:39:21 +00002860 // Check that each individual element can be copy-constructed. But since we
2861 // have no place to store further information, we'll recalculate everything
2862 // later.
2863 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2864 S.Context.getConstantArrayType(E,
2865 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2866 List->getNumInits()),
2867 ArrayType::Normal, 0));
2868 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2869 0, HiddenArray);
2870 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2871 Element.setElementIndex(i);
2872 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2873 Sequence.SetFailed(
2874 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002875 return true;
2876 }
2877 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002878 Sequence.AddStdInitializerListConstructionStep(DestType);
2879 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002880}
2881
Sebastian Redl96715b22012-02-04 21:27:39 +00002882static OverloadingResult
2883ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002884 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002885 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002886 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002887 OverloadCandidateSet::iterator &Best,
2888 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002889 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002890 CandidateSet.clear();
2891
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002892 for (ArrayRef<NamedDecl *>::iterator
2893 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002894 NamedDecl *D = *Con;
2895 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2896 bool SuppressUserConversions = false;
2897
2898 // Find the constructor (which may be a template).
2899 CXXConstructorDecl *Constructor = 0;
2900 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2901 if (ConstructorTmpl)
2902 Constructor = cast<CXXConstructorDecl>(
2903 ConstructorTmpl->getTemplatedDecl());
2904 else {
2905 Constructor = cast<CXXConstructorDecl>(D);
2906
2907 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002908 // suppress user-defined conversions on the arguments. We do the same for
2909 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002910 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002911 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002912 SuppressUserConversions = true;
2913 }
2914
2915 if (!Constructor->isInvalidDecl() &&
2916 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002917 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002918 if (ConstructorTmpl)
2919 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002920 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002921 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002922 else {
2923 // C++ [over.match.copy]p1:
2924 // - When initializing a temporary to be bound to the first parameter
2925 // of a constructor that takes a reference to possibly cv-qualified
2926 // T as its first argument, called with a single argument in the
2927 // context of direct-initialization, explicit conversion functions
2928 // are also considered.
2929 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002930 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00002931 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002932 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002933 SuppressUserConversions,
2934 /*PartialOverloading=*/false,
2935 /*AllowExplicit=*/AllowExplicitConv);
2936 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002937 }
2938 }
2939
2940 // Perform overload resolution and return the result.
2941 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2942}
2943
Sebastian Redl10f04a62011-12-22 14:44:04 +00002944/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2945/// enumerates the constructors of the initialized entity and performs overload
2946/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002947/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002948/// class type.
2949static void TryConstructorInitialization(Sema &S,
2950 const InitializedEntity &Entity,
2951 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002952 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002953 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002954 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002955 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00002956 "InitListSyntax must come with a single initializer list argument.");
2957
Sebastian Redl10f04a62011-12-22 14:44:04 +00002958 // The type we're constructing needs to be complete.
2959 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002960 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002961 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002962 }
2963
2964 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2965 assert(DestRecordType && "Constructor initialization requires record type");
2966 CXXRecordDecl *DestRecordDecl
2967 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2968
Sebastian Redl96715b22012-02-04 21:27:39 +00002969 // Build the candidate set directly in the initialization sequence
2970 // structure, so that it will persist if we fail.
2971 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2972
2973 // Determine whether we are allowed to call explicit constructors or
2974 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002975 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002976 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002977
Sebastian Redl10f04a62011-12-22 14:44:04 +00002978 // - Otherwise, if T is a class type, constructors are considered. The
2979 // applicable constructors are enumerated, and the best one is chosen
2980 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00002981 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002982 // The container holding the constructors can under certain conditions
2983 // be changed while iterating (e.g. because of deserialization).
2984 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00002985 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00002986
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002987 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002988 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002989 bool AsInitializerList = false;
2990
2991 // C++11 [over.match.list]p1:
2992 // When objects of non-aggregate type T are list-initialized, overload
2993 // resolution selects the constructor in two phases:
2994 // - Initially, the candidate functions are the initializer-list
2995 // constructors of the class T and the argument list consists of the
2996 // initializer list as a single argument.
2997 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002998 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002999 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003000
3001 // If the initializer list has no elements and T has a default constructor,
3002 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003003 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003004 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003005 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003006 CopyInitialization, AllowExplicit,
3007 /*OnlyListConstructor=*/true,
3008 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003009
3010 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003011 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003012 }
3013
3014 // C++11 [over.match.list]p1:
3015 // - If no viable initializer-list constructor is found, overload resolution
3016 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003017 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003018 // elements of the initializer list.
3019 if (Result == OR_No_Viable_Function) {
3020 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003021 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003022 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003023 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003024 /*OnlyListConstructors=*/false,
3025 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003026 }
3027 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003028 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003029 InitializationSequence::FK_ListConstructorOverloadFailed :
3030 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003031 Result);
3032 return;
3033 }
3034
Richard Smithf4bb8d02012-07-05 08:39:21 +00003035 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003036 // If a program calls for the default initialization of an object
3037 // of a const-qualified type T, T shall be a class type with a
3038 // user-provided default constructor.
3039 if (Kind.getKind() == InitializationKind::IK_Default &&
3040 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003041 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003042 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3043 return;
3044 }
3045
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003046 // C++11 [over.match.list]p1:
3047 // In copy-list-initialization, if an explicit constructor is chosen, the
3048 // initializer is ill-formed.
3049 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3050 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3051 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3052 return;
3053 }
3054
Sebastian Redl10f04a62011-12-22 14:44:04 +00003055 // Add the constructor initialization step. Any cv-qualification conversion is
3056 // subsumed by the initialization.
3057 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003058 Sequence.AddConstructorInitializationStep(CtorDecl,
3059 Best->FoundDecl.getAccess(),
3060 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003061 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003062}
3063
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003064static bool
3065ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3066 Expr *Initializer,
3067 QualType &SourceType,
3068 QualType &UnqualifiedSourceType,
3069 QualType UnqualifiedTargetType,
3070 InitializationSequence &Sequence) {
3071 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3072 S.Context.OverloadTy) {
3073 DeclAccessPair Found;
3074 bool HadMultipleCandidates = false;
3075 if (FunctionDecl *Fn
3076 = S.ResolveAddressOfOverloadedFunction(Initializer,
3077 UnqualifiedTargetType,
3078 false, Found,
3079 &HadMultipleCandidates)) {
3080 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3081 HadMultipleCandidates);
3082 SourceType = Fn->getType();
3083 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3084 } else if (!UnqualifiedTargetType->isRecordType()) {
3085 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3086 return true;
3087 }
3088 }
3089 return false;
3090}
3091
3092static void TryReferenceInitializationCore(Sema &S,
3093 const InitializedEntity &Entity,
3094 const InitializationKind &Kind,
3095 Expr *Initializer,
3096 QualType cv1T1, QualType T1,
3097 Qualifiers T1Quals,
3098 QualType cv2T2, QualType T2,
3099 Qualifiers T2Quals,
3100 InitializationSequence &Sequence);
3101
Richard Smithf4bb8d02012-07-05 08:39:21 +00003102static void TryValueInitialization(Sema &S,
3103 const InitializedEntity &Entity,
3104 const InitializationKind &Kind,
3105 InitializationSequence &Sequence,
3106 InitListExpr *InitList = 0);
3107
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003108static void TryListInitialization(Sema &S,
3109 const InitializedEntity &Entity,
3110 const InitializationKind &Kind,
3111 InitListExpr *InitList,
3112 InitializationSequence &Sequence);
3113
3114/// \brief Attempt list initialization of a reference.
3115static void TryReferenceListInitialization(Sema &S,
3116 const InitializedEntity &Entity,
3117 const InitializationKind &Kind,
3118 InitListExpr *InitList,
3119 InitializationSequence &Sequence)
3120{
3121 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003122 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003123 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3124 return;
3125 }
3126
3127 QualType DestType = Entity.getType();
3128 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3129 Qualifiers T1Quals;
3130 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3131
3132 // Reference initialization via an initializer list works thus:
3133 // If the initializer list consists of a single element that is
3134 // reference-related to the referenced type, bind directly to that element
3135 // (possibly creating temporaries).
3136 // Otherwise, initialize a temporary with the initializer list and
3137 // bind to that.
3138 if (InitList->getNumInits() == 1) {
3139 Expr *Initializer = InitList->getInit(0);
3140 QualType cv2T2 = Initializer->getType();
3141 Qualifiers T2Quals;
3142 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3143
3144 // If this fails, creating a temporary wouldn't work either.
3145 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3146 T1, Sequence))
3147 return;
3148
3149 SourceLocation DeclLoc = Initializer->getLocStart();
3150 bool dummy1, dummy2, dummy3;
3151 Sema::ReferenceCompareResult RefRelationship
3152 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3153 dummy2, dummy3);
3154 if (RefRelationship >= Sema::Ref_Related) {
3155 // Try to bind the reference here.
3156 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3157 T1Quals, cv2T2, T2, T2Quals, Sequence);
3158 if (Sequence)
3159 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3160 return;
3161 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003162
3163 // Update the initializer if we've resolved an overloaded function.
3164 if (Sequence.step_begin() != Sequence.step_end())
3165 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003166 }
3167
3168 // Not reference-related. Create a temporary and bind to that.
3169 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3170
3171 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3172 if (Sequence) {
3173 if (DestType->isRValueReferenceType() ||
3174 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3175 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3176 else
3177 Sequence.SetFailed(
3178 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3179 }
3180}
3181
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003182/// \brief Attempt list initialization (C++0x [dcl.init.list])
3183static void TryListInitialization(Sema &S,
3184 const InitializedEntity &Entity,
3185 const InitializationKind &Kind,
3186 InitListExpr *InitList,
3187 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003188 QualType DestType = Entity.getType();
3189
Sebastian Redl14b0c192011-09-24 17:48:00 +00003190 // C++ doesn't allow scalar initialization with more than one argument.
3191 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003192 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003193 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3194 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3195 return;
3196 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003197 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003198 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003199 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003200 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003201 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003202 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003203 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003204 return;
3205 }
3206
Richard Smithf4bb8d02012-07-05 08:39:21 +00003207 // C++11 [dcl.init.list]p3:
3208 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003209 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003210 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003211 // - Otherwise, if the initializer list has no elements and T is a
3212 // class type with a default constructor, the object is
3213 // value-initialized.
3214 if (InitList->getNumInits() == 0) {
3215 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003216 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003217 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3218 return;
3219 }
3220 }
3221
3222 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3223 // an initializer_list object constructed [...]
3224 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3225 return;
3226
3227 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003228 Expr *InitListAsExpr = InitList;
3229 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003230 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003231 } else
3232 Sequence.SetFailed(
3233 InitializationSequence::FK_InitListBadDestinationType);
3234 return;
3235 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003236 }
3237
Sebastian Redl14b0c192011-09-24 17:48:00 +00003238 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003239 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003240 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00003241 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003242 if (CheckInitList.HadError()) {
3243 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3244 return;
3245 }
3246
3247 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003248 Sequence.AddListInitializationStep(DestType);
3249}
Douglas Gregor20093b42009-12-09 23:02:17 +00003250
3251/// \brief Try a reference initialization that involves calling a conversion
3252/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003253static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3254 const InitializedEntity &Entity,
3255 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003256 Expr *Initializer,
3257 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003258 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003259 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003260 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3261 QualType T1 = cv1T1.getUnqualifiedType();
3262 QualType cv2T2 = Initializer->getType();
3263 QualType T2 = cv2T2.getUnqualifiedType();
3264
3265 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003266 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003267 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003269 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003270 ObjCConversion,
3271 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003272 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003273 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003274 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003275 (void)ObjCLifetimeConversion;
3276
Douglas Gregor20093b42009-12-09 23:02:17 +00003277 // Build the candidate set directly in the initialization sequence
3278 // structure, so that it will persist if we fail.
3279 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3280 CandidateSet.clear();
3281
3282 // Determine whether we are allowed to call explicit constructors or
3283 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003284 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003285 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3286
Douglas Gregor20093b42009-12-09 23:02:17 +00003287 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003288 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3289 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003290 // The type we're converting to is a class type. Enumerate its constructors
3291 // to see if there is a suitable conversion.
3292 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003293
David Blaikie3bc93e32012-12-19 00:45:41 +00003294 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003295 // The container holding the constructors can under certain conditions
3296 // be changed while iterating (e.g. because of deserialization).
3297 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003298 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003299 for (SmallVector<NamedDecl*, 16>::iterator
3300 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3301 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003302 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3303
Douglas Gregor20093b42009-12-09 23:02:17 +00003304 // Find the constructor (which may be a template).
3305 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003306 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003307 if (ConstructorTmpl)
3308 Constructor = cast<CXXConstructorDecl>(
3309 ConstructorTmpl->getTemplatedDecl());
3310 else
John McCall9aa472c2010-03-19 07:35:19 +00003311 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003312
Douglas Gregor20093b42009-12-09 23:02:17 +00003313 if (!Constructor->isInvalidDecl() &&
3314 Constructor->isConvertingConstructor(AllowExplicit)) {
3315 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003316 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003317 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003318 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003319 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003320 else
John McCall9aa472c2010-03-19 07:35:19 +00003321 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003322 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003323 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003324 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003325 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003326 }
John McCall572fc622010-08-17 07:23:57 +00003327 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3328 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003329
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003330 const RecordType *T2RecordType = 0;
3331 if ((T2RecordType = T2->getAs<RecordType>()) &&
3332 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003333 // The type we're converting from is a class type, enumerate its conversion
3334 // functions.
3335 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3336
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003337 std::pair<CXXRecordDecl::conversion_iterator,
3338 CXXRecordDecl::conversion_iterator>
3339 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3340 for (CXXRecordDecl::conversion_iterator
3341 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003342 NamedDecl *D = *I;
3343 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3344 if (isa<UsingShadowDecl>(D))
3345 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346
Douglas Gregor20093b42009-12-09 23:02:17 +00003347 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3348 CXXConversionDecl *Conv;
3349 if (ConvTemplate)
3350 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3351 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003352 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003353
Douglas Gregor20093b42009-12-09 23:02:17 +00003354 // If the conversion function doesn't return a reference type,
3355 // it can't be considered for this conversion unless we're allowed to
3356 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003357 // FIXME: Do we need to make sure that we only consider conversion
3358 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003359 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003360 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003361 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3362 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003363 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003364 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003365 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003366 else
John McCall9aa472c2010-03-19 07:35:19 +00003367 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003368 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003369 }
3370 }
3371 }
John McCall572fc622010-08-17 07:23:57 +00003372 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3373 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003374
Douglas Gregor20093b42009-12-09 23:02:17 +00003375 SourceLocation DeclLoc = Initializer->getLocStart();
3376
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003378 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003380 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003381 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003382
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003384 // This is the overload that will be used for this initialization step if we
3385 // use this initialization. Mark it as referenced.
3386 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003387
Eli Friedman03981012009-12-11 02:42:07 +00003388 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003389 if (isa<CXXConversionDecl>(Function))
3390 T2 = Function->getResultType();
3391 else
3392 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003393
3394 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003395 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003396 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003397 T2.getNonLValueExprType(S.Context),
3398 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003399
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003400 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003401 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003402 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003403 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003404 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003405 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003406 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003407
Douglas Gregor20093b42009-12-09 23:02:17 +00003408 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003409 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003410 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003411 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003412 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003413 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003414 NewDerivedToBase, NewObjCConversion,
3415 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003416 if (NewRefRelationship == Sema::Ref_Incompatible) {
3417 // If the type we've converted to is not reference-related to the
3418 // type we're looking for, then there is another conversion step
3419 // we need to perform to produce a temporary of the right type
3420 // that we'll be binding to.
3421 ImplicitConversionSequence ICS;
3422 ICS.setStandard();
3423 ICS.Standard = Best->FinalConversion;
3424 T2 = ICS.Standard.getToType(2);
3425 Sequence.AddConversionSequenceStep(ICS, T2);
3426 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003427 Sequence.AddDerivedToBaseCastStep(
3428 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003429 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003430 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003431 else if (NewObjCConversion)
3432 Sequence.AddObjCObjectConversionStep(
3433 S.Context.getQualifiedType(T1,
3434 T2.getNonReferenceType().getQualifiers()));
3435
Douglas Gregor20093b42009-12-09 23:02:17 +00003436 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003437 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003438
Douglas Gregor20093b42009-12-09 23:02:17 +00003439 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3440 return OR_Success;
3441}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003442
Richard Smith83da2e72011-10-19 16:55:56 +00003443static void CheckCXX98CompatAccessibleCopy(Sema &S,
3444 const InitializedEntity &Entity,
3445 Expr *CurInitExpr);
3446
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003447/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3448static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003449 const InitializedEntity &Entity,
3450 const InitializationKind &Kind,
3451 Expr *Initializer,
3452 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003453 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003454 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003455 Qualifiers T1Quals;
3456 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003457 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003458 Qualifiers T2Quals;
3459 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003460
Douglas Gregor20093b42009-12-09 23:02:17 +00003461 // If the initializer is the address of an overloaded function, try
3462 // to resolve the overloaded function. If all goes well, T2 is the
3463 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003464 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3465 T1, Sequence))
3466 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003467
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003468 // Delegate everything else to a subfunction.
3469 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3470 T1Quals, cv2T2, T2, T2Quals, Sequence);
3471}
3472
Jordan Rose1fd1e282013-04-11 00:58:58 +00003473/// Converts the target of reference initialization so that it has the
3474/// appropriate qualifiers and value kind.
3475///
3476/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3477/// \code
3478/// int x;
3479/// const int &r = x;
3480/// \endcode
3481///
3482/// In this case the reference is binding to a bitfield lvalue, which isn't
3483/// valid. Perform a load to create a lifetime-extended temporary instead.
3484/// \code
3485/// const int &r = someStruct.bitfield;
3486/// \endcode
3487static ExprValueKind
3488convertQualifiersAndValueKindIfNecessary(Sema &S,
3489 InitializationSequence &Sequence,
3490 Expr *Initializer,
3491 QualType cv1T1,
3492 Qualifiers T1Quals,
3493 Qualifiers T2Quals,
3494 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003495 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003496 Initializer->refersToVectorElement();
3497
3498 if (IsNonAddressableType) {
3499 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3500 // lvalue reference to a non-volatile const type, or the reference shall be
3501 // an rvalue reference.
3502 //
3503 // If not, we can't make a temporary and bind to that. Give up and allow the
3504 // error to be diagnosed later.
3505 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3506 assert(Initializer->isGLValue());
3507 return Initializer->getValueKind();
3508 }
3509
3510 // Force a load so we can materialize a temporary.
3511 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3512 return VK_RValue;
3513 }
3514
3515 if (T1Quals != T2Quals) {
3516 Sequence.AddQualificationConversionStep(cv1T1,
3517 Initializer->getValueKind());
3518 }
3519
3520 return Initializer->getValueKind();
3521}
3522
3523
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003524/// \brief Reference initialization without resolving overloaded functions.
3525static void TryReferenceInitializationCore(Sema &S,
3526 const InitializedEntity &Entity,
3527 const InitializationKind &Kind,
3528 Expr *Initializer,
3529 QualType cv1T1, QualType T1,
3530 Qualifiers T1Quals,
3531 QualType cv2T2, QualType T2,
3532 Qualifiers T2Quals,
3533 InitializationSequence &Sequence) {
3534 QualType DestType = Entity.getType();
3535 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003536 // Compute some basic properties of the types and the initializer.
3537 bool isLValueRef = DestType->isLValueReferenceType();
3538 bool isRValueRef = !isLValueRef;
3539 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003540 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003541 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003542 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003543 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003544 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003545 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003546
Douglas Gregor20093b42009-12-09 23:02:17 +00003547 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003548 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003549 // "cv2 T2" as follows:
3550 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003551 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003552 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003553 // Note the analogous bullet points for rvlaue refs to functions. Because
3554 // there are no function rvalues in C++, rvalue refs to functions are treated
3555 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003556 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003557 bool T1Function = T1->isFunctionType();
3558 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003560 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003561 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003562 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003563 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003564 // reference-compatible with "cv2 T2," or
3565 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003567 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003568 // can occur. However, we do pay attention to whether it is a bit-field
3569 // to decide whether we're actually binding to a temporary created from
3570 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003571 if (DerivedToBase)
3572 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003573 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003574 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003575 else if (ObjCConversion)
3576 Sequence.AddObjCObjectConversionStep(
3577 S.Context.getQualifiedType(T1, T2Quals));
3578
Jordan Rose1fd1e282013-04-11 00:58:58 +00003579 ExprValueKind ValueKind =
3580 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3581 cv1T1, T1Quals, T2Quals,
3582 isLValueRef);
3583 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003584 return;
3585 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003586
3587 // - has a class type (i.e., T2 is a class type), where T1 is not
3588 // reference-related to T2, and can be implicitly converted to an
3589 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3590 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003591 // applicable conversion functions (13.3.1.6) and choosing the best
3592 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003593 // If we have an rvalue ref to function type here, the rhs must be
3594 // an rvalue.
3595 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3596 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003597 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003598 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003599 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003600 Sequence);
3601 if (ConvOvlResult == OR_Success)
3602 return;
John McCall1d318332010-01-12 00:44:57 +00003603 if (ConvOvlResult != OR_No_Viable_Function) {
3604 Sequence.SetOverloadFailure(
3605 InitializationSequence::FK_ReferenceInitOverloadFailed,
3606 ConvOvlResult);
3607 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003608 }
3609 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003610
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003611 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003612 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003613 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003614 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003615 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3616 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3617 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003618 Sequence.SetOverloadFailure(
3619 InitializationSequence::FK_ReferenceInitOverloadFailed,
3620 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003621 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003622 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003623 ? (RefRelationship == Sema::Ref_Related
3624 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3625 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3626 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003627
Douglas Gregor20093b42009-12-09 23:02:17 +00003628 return;
3629 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003630
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003631 // - If the initializer expression
3632 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3633 // "cv1 T1" is reference-compatible with "cv2 T2"
3634 // Note: functions are handled below.
3635 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003636 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003638 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003639 (InitCategory.isXValue() ||
3640 (InitCategory.isPRValue() && T2->isRecordType()) ||
3641 (InitCategory.isPRValue() && T2->isArrayType()))) {
3642 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3643 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003644 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3645 // compiler the freedom to perform a copy here or bind to the
3646 // object, while C++0x requires that we bind directly to the
3647 // object. Hence, we always bind to the object without making an
3648 // extra copy. However, in C++03 requires that we check for the
3649 // presence of a suitable copy constructor:
3650 //
3651 // The constructor that would be used to make the copy shall
3652 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003653 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003654 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003655 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003656 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003657 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003658
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003659 if (DerivedToBase)
3660 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3661 ValueKind);
3662 else if (ObjCConversion)
3663 Sequence.AddObjCObjectConversionStep(
3664 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003665
Jordan Rose1fd1e282013-04-11 00:58:58 +00003666 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3667 Initializer, cv1T1,
3668 T1Quals, T2Quals,
3669 isLValueRef);
3670
3671 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003672 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003673 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003674
3675 // - has a class type (i.e., T2 is a class type), where T1 is not
3676 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003677 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3678 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003679 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003680 if (RefRelationship == Sema::Ref_Incompatible) {
3681 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3682 Kind, Initializer,
3683 /*AllowRValues=*/true,
3684 Sequence);
3685 if (ConvOvlResult)
3686 Sequence.SetOverloadFailure(
3687 InitializationSequence::FK_ReferenceInitOverloadFailed,
3688 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003689
Douglas Gregor20093b42009-12-09 23:02:17 +00003690 return;
3691 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003692
Douglas Gregordefa32e2013-03-26 23:59:23 +00003693 if ((RefRelationship == Sema::Ref_Compatible ||
3694 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3695 isRValueRef && InitCategory.isLValue()) {
3696 Sequence.SetFailed(
3697 InitializationSequence::FK_RValueReferenceBindingToLValue);
3698 return;
3699 }
3700
Douglas Gregor20093b42009-12-09 23:02:17 +00003701 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3702 return;
3703 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003704
3705 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003706 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003707 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003708 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003709
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 // Determine whether we are allowed to call explicit constructors or
3711 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003712 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003713
3714 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3715
John McCallf85e1932011-06-15 23:02:42 +00003716 ImplicitConversionSequence ICS
3717 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003718 /*SuppressUserConversions*/ false,
3719 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003720 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003721 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3722 /*AllowObjCWritebackConversion=*/false);
3723
3724 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003725 // FIXME: Use the conversion function set stored in ICS to turn
3726 // this into an overloading ambiguity diagnostic. However, we need
3727 // to keep that set as an OverloadCandidateSet rather than as some
3728 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003729 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3730 Sequence.SetOverloadFailure(
3731 InitializationSequence::FK_ReferenceInitOverloadFailed,
3732 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003733 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3734 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003735 else
3736 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003737 return;
John McCallf85e1932011-06-15 23:02:42 +00003738 } else {
3739 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003740 }
3741
3742 // [...] If T1 is reference-related to T2, cv1 must be the
3743 // same cv-qualification as, or greater cv-qualification
3744 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003745 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3746 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003747 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003748 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003749 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3750 return;
3751 }
3752
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003753 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003754 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003755 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003756 InitCategory.isLValue()) {
3757 Sequence.SetFailed(
3758 InitializationSequence::FK_RValueReferenceBindingToLValue);
3759 return;
3760 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003761
Douglas Gregor20093b42009-12-09 23:02:17 +00003762 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3763 return;
3764}
3765
3766/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003767/// (C++ [dcl.init.string], C99 6.7.8).
3768static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003769 const InitializedEntity &Entity,
3770 const InitializationKind &Kind,
3771 Expr *Initializer,
3772 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003773 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003774}
3775
Douglas Gregor71d17402009-12-15 00:01:57 +00003776/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003777static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003778 const InitializedEntity &Entity,
3779 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003780 InitializationSequence &Sequence,
3781 InitListExpr *InitList) {
3782 assert((!InitList || InitList->getNumInits() == 0) &&
3783 "Shouldn't use value-init for non-empty init lists");
3784
Richard Smith1d0c9a82012-02-14 21:14:13 +00003785 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003786 //
3787 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003788 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003789
Douglas Gregor71d17402009-12-15 00:01:57 +00003790 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003791 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
Douglas Gregor71d17402009-12-15 00:01:57 +00003793 if (const RecordType *RT = T->getAs<RecordType>()) {
3794 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003795 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003796 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003797 // C++98:
3798 // -- if T is a class type (clause 9) with a user-declared constructor
3799 // (12.1), then the default constructor for T is called (and the
3800 // initialization is ill-formed if T has no accessible default
3801 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003802 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003803 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003804 } else {
3805 // C++11:
3806 // -- if T is a class type (clause 9) with either no default constructor
3807 // (12.1 [class.ctor]) or a default constructor that is user-provided
3808 // or deleted, then the object is default-initialized;
3809 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3810 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003811 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003813
Richard Smith1d0c9a82012-02-14 21:14:13 +00003814 // -- if T is a (possibly cv-qualified) non-union class type without a
3815 // user-provided or deleted default constructor, then the object is
3816 // zero-initialized and, if T has a non-trivial default constructor,
3817 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003818 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3819 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003820 if (NeedZeroInitialization)
3821 Sequence.AddZeroInitializationStep(Entity.getType());
3822
Richard Smithd5bc8672012-12-08 02:01:17 +00003823 // C++03:
3824 // -- if T is a non-union class type without a user-declared constructor,
3825 // then every non-static data member and base class component of T is
3826 // value-initialized;
3827 // [...] A program that calls for [...] value-initialization of an
3828 // entity of reference type is ill-formed.
3829 //
3830 // C++11 doesn't need this handling, because value-initialization does not
3831 // occur recursively there, and the implicit default constructor is
3832 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003833 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003834 ClassDecl->hasUninitializedReferenceMember()) {
3835 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3836 return;
3837 }
3838
Richard Smithf4bb8d02012-07-05 08:39:21 +00003839 // If this is list-value-initialization, pass the empty init list on when
3840 // building the constructor call. This affects the semantics of a few
3841 // things (such as whether an explicit default constructor can be called).
3842 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003843 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003844 bool InitListSyntax = InitList;
3845
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003846 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3847 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003848 }
3849 }
3850
Douglas Gregord6542d82009-12-22 15:35:07 +00003851 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003852}
3853
Douglas Gregor99a2e602009-12-16 01:38:02 +00003854/// \brief Attempt default initialization (C++ [dcl.init]p6).
3855static void TryDefaultInitialization(Sema &S,
3856 const InitializedEntity &Entity,
3857 const InitializationKind &Kind,
3858 InitializationSequence &Sequence) {
3859 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003860
Douglas Gregor99a2e602009-12-16 01:38:02 +00003861 // C++ [dcl.init]p6:
3862 // To default-initialize an object of type T means:
3863 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003864 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3865
Douglas Gregor99a2e602009-12-16 01:38:02 +00003866 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3867 // constructor for T is called (and the initialization is ill-formed if
3868 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003869 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003870 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003871 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003872 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003873
Douglas Gregor99a2e602009-12-16 01:38:02 +00003874 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003875
Douglas Gregor99a2e602009-12-16 01:38:02 +00003876 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003877 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003878 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003879 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003880 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003881 return;
3882 }
3883
3884 // If the destination type has a lifetime property, zero-initialize it.
3885 if (DestType.getQualifiers().hasObjCLifetime()) {
3886 Sequence.AddZeroInitializationStep(Entity.getType());
3887 return;
3888 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003889}
3890
Douglas Gregor20093b42009-12-09 23:02:17 +00003891/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3892/// which enumerates all conversion functions and performs overload resolution
3893/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003894static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003895 const InitializedEntity &Entity,
3896 const InitializationKind &Kind,
3897 Expr *Initializer,
3898 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003899 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003900 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3901 QualType SourceType = Initializer->getType();
3902 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3903 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003904
Douglas Gregor4a520a22009-12-14 17:27:33 +00003905 // Build the candidate set directly in the initialization sequence
3906 // structure, so that it will persist if we fail.
3907 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3908 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003909
Douglas Gregor4a520a22009-12-14 17:27:33 +00003910 // Determine whether we are allowed to call explicit constructors or
3911 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003912 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003913
Douglas Gregor4a520a22009-12-14 17:27:33 +00003914 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3915 // The type we're converting to is a class type. Enumerate its constructors
3916 // to see if there is a suitable conversion.
3917 CXXRecordDecl *DestRecordDecl
3918 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003919
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003920 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003921 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003922 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003923 // The container holding the constructors can under certain conditions
3924 // be changed while iterating. To be safe we copy the lookup results
3925 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003926 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003927 for (SmallVector<NamedDecl*, 8>::iterator
3928 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003929 Con != ConEnd; ++Con) {
3930 NamedDecl *D = *Con;
3931 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003932
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003933 // Find the constructor (which may be a template).
3934 CXXConstructorDecl *Constructor = 0;
3935 FunctionTemplateDecl *ConstructorTmpl
3936 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003937 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003938 Constructor = cast<CXXConstructorDecl>(
3939 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003940 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003941 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003942
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003943 if (!Constructor->isInvalidDecl() &&
3944 Constructor->isConvertingConstructor(AllowExplicit)) {
3945 if (ConstructorTmpl)
3946 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3947 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003948 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003949 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003950 else
3951 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003952 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003953 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003954 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003955 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003956 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003957 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003958
3959 SourceLocation DeclLoc = Initializer->getLocStart();
3960
Douglas Gregor4a520a22009-12-14 17:27:33 +00003961 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3962 // The type we're converting from is a class type, enumerate its conversion
3963 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003964
Eli Friedman33c2da92009-12-20 22:12:03 +00003965 // We can only enumerate the conversion functions for a complete type; if
3966 // the type isn't complete, simply skip this step.
3967 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3968 CXXRecordDecl *SourceRecordDecl
3969 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003970
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003971 std::pair<CXXRecordDecl::conversion_iterator,
3972 CXXRecordDecl::conversion_iterator>
3973 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3974 for (CXXRecordDecl::conversion_iterator
3975 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003976 NamedDecl *D = *I;
3977 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3978 if (isa<UsingShadowDecl>(D))
3979 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003980
Eli Friedman33c2da92009-12-20 22:12:03 +00003981 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3982 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003983 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003984 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003985 else
John McCall32daa422010-03-31 01:36:47 +00003986 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003987
Eli Friedman33c2da92009-12-20 22:12:03 +00003988 if (AllowExplicit || !Conv->isExplicit()) {
3989 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003990 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003991 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003992 CandidateSet);
3993 else
John McCall9aa472c2010-03-19 07:35:19 +00003994 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003995 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003996 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003997 }
3998 }
3999 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004000
4001 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004002 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004003 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004004 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004005 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004006 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004007 Result);
4008 return;
4009 }
John McCall1d318332010-01-12 00:44:57 +00004010
Douglas Gregor4a520a22009-12-14 17:27:33 +00004011 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004012 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004013 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004014
Douglas Gregor4a520a22009-12-14 17:27:33 +00004015 if (isa<CXXConstructorDecl>(Function)) {
4016 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004017 // subsumed by the initialization. Per DR5, the created temporary is of the
4018 // cv-unqualified type of the destination.
4019 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4020 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004021 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004022 return;
4023 }
4024
4025 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004026 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004027 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004028 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004029 // the resulting temporary object (possible to create an object of
4030 // a base class type). That copy is not a separate conversion, so
4031 // we just make a note of the actual destination type (possibly a
4032 // base class of the type returned by the conversion function) and
4033 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004034 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4035 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004036 return;
4037 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004038
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004039 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4040 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004041
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004042 // If the conversion following the call to the conversion function
4043 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004044 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4045 Best->FinalConversion.Third) {
4046 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004047 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004048 ICS.Standard = Best->FinalConversion;
4049 Sequence.AddConversionSequenceStep(ICS, DestType);
4050 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004051}
4052
John McCallf85e1932011-06-15 23:02:42 +00004053/// The non-zero enum values here are indexes into diagnostic alternatives.
4054enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4055
4056/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004057static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004058 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004059 // Skip parens.
4060 e = e->IgnoreParens();
4061
4062 // Skip address-of nodes.
4063 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4064 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004065 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4066 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004067
4068 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004069 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4070 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004071 case CK_Dependent:
4072 case CK_BitCast:
4073 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004074 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004075 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004076
4077 case CK_ArrayToPointerDecay:
4078 return IIK_nonscalar;
4079
4080 case CK_NullToPointer:
4081 return IIK_okay;
4082
4083 default:
4084 break;
4085 }
4086
4087 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004088 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004089 // set isWeakAccess to true, to mean that there will be an implicit
4090 // load which requires a cleanup.
4091 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4092 isWeakAccess = true;
4093
John McCallc03fa492011-06-27 23:59:58 +00004094 if (!isAddressOf) return IIK_nonlocal;
4095
John McCallf4b88a42012-03-10 09:33:50 +00004096 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4097 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004098
4099 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004100
4101 // If we have a conditional operator, check both sides.
4102 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004103 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4104 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004105 return iik;
4106
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004107 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004108
4109 // These are never scalar.
4110 } else if (isa<ArraySubscriptExpr>(e)) {
4111 return IIK_nonscalar;
4112
4113 // Otherwise, it needs to be a null pointer constant.
4114 } else {
4115 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4116 ? IIK_okay : IIK_nonlocal);
4117 }
4118
4119 return IIK_nonlocal;
4120}
4121
4122/// Check whether the given expression is a valid operand for an
4123/// indirect copy/restore.
4124static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4125 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004126 bool isWeakAccess = false;
4127 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4128 // If isWeakAccess to true, there will be an implicit
4129 // load which requires a cleanup.
4130 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4131 S.ExprNeedsCleanups = true;
4132
John McCallf85e1932011-06-15 23:02:42 +00004133 if (iik == IIK_okay) return;
4134
4135 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4136 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4137 << src->getSourceRange();
4138}
4139
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004140/// \brief Determine whether we have compatible array types for the
4141/// purposes of GNU by-copy array initialization.
4142static bool hasCompatibleArrayTypes(ASTContext &Context,
4143 const ArrayType *Dest,
4144 const ArrayType *Source) {
4145 // If the source and destination array types are equivalent, we're
4146 // done.
4147 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4148 return true;
4149
4150 // Make sure that the element types are the same.
4151 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4152 return false;
4153
4154 // The only mismatch we allow is when the destination is an
4155 // incomplete array type and the source is a constant array type.
4156 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4157}
4158
John McCallf85e1932011-06-15 23:02:42 +00004159static bool tryObjCWritebackConversion(Sema &S,
4160 InitializationSequence &Sequence,
4161 const InitializedEntity &Entity,
4162 Expr *Initializer) {
4163 bool ArrayDecay = false;
4164 QualType ArgType = Initializer->getType();
4165 QualType ArgPointee;
4166 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4167 ArrayDecay = true;
4168 ArgPointee = ArgArrayType->getElementType();
4169 ArgType = S.Context.getPointerType(ArgPointee);
4170 }
4171
4172 // Handle write-back conversion.
4173 QualType ConvertedArgType;
4174 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4175 ConvertedArgType))
4176 return false;
4177
4178 // We should copy unless we're passing to an argument explicitly
4179 // marked 'out'.
4180 bool ShouldCopy = true;
4181 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4182 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4183
4184 // Do we need an lvalue conversion?
4185 if (ArrayDecay || Initializer->isGLValue()) {
4186 ImplicitConversionSequence ICS;
4187 ICS.setStandard();
4188 ICS.Standard.setAsIdentityConversion();
4189
4190 QualType ResultType;
4191 if (ArrayDecay) {
4192 ICS.Standard.First = ICK_Array_To_Pointer;
4193 ResultType = S.Context.getPointerType(ArgPointee);
4194 } else {
4195 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4196 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4197 }
4198
4199 Sequence.AddConversionSequenceStep(ICS, ResultType);
4200 }
4201
4202 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4203 return true;
4204}
4205
Guy Benyei21f18c42013-02-07 10:55:47 +00004206static bool TryOCLSamplerInitialization(Sema &S,
4207 InitializationSequence &Sequence,
4208 QualType DestType,
4209 Expr *Initializer) {
4210 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4211 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4212 return false;
4213
4214 Sequence.AddOCLSamplerInitStep(DestType);
4215 return true;
4216}
4217
Guy Benyeie6b9d802013-01-20 12:31:11 +00004218//
4219// OpenCL 1.2 spec, s6.12.10
4220//
4221// The event argument can also be used to associate the
4222// async_work_group_copy with a previous async copy allowing
4223// an event to be shared by multiple async copies; otherwise
4224// event should be zero.
4225//
4226static bool TryOCLZeroEventInitialization(Sema &S,
4227 InitializationSequence &Sequence,
4228 QualType DestType,
4229 Expr *Initializer) {
4230 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4231 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4232 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4233 return false;
4234
4235 Sequence.AddOCLZeroEventStep(DestType);
4236 return true;
4237}
4238
Douglas Gregor20093b42009-12-09 23:02:17 +00004239InitializationSequence::InitializationSequence(Sema &S,
4240 const InitializedEntity &Entity,
4241 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004242 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004243 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004244 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004245
John McCall76da55d2013-04-16 07:28:30 +00004246 // Eliminate non-overload placeholder types in the arguments. We
4247 // need to do this before checking whether types are dependent
4248 // because lowering a pseudo-object expression might well give us
4249 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004250 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004251 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4252 // FIXME: should we be doing this here?
4253 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4254 if (result.isInvalid()) {
4255 SetFailed(FK_PlaceholderType);
4256 return;
4257 }
4258 Args[I] = result.take();
4259 }
4260
Douglas Gregor20093b42009-12-09 23:02:17 +00004261 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004262 // The semantics of initializers are as follows. The destination type is
4263 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004264 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004266 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004267 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004268
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004269 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004270 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004271 SequenceKind = DependentSequence;
4272 return;
4273 }
4274
Sebastian Redl7491c492011-06-05 13:59:11 +00004275 // Almost everything is a normal sequence.
4276 setSequenceKind(NormalSequence);
4277
Douglas Gregor20093b42009-12-09 23:02:17 +00004278 QualType SourceType;
4279 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004280 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004281 Initializer = Args[0];
4282 if (!isa<InitListExpr>(Initializer))
4283 SourceType = Initializer->getType();
4284 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004286 // - If the initializer is a (non-parenthesized) braced-init-list, the
4287 // object is list-initialized (8.5.4).
4288 if (Kind.getKind() != InitializationKind::IK_Direct) {
4289 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4290 TryListInitialization(S, Entity, Kind, InitList, *this);
4291 return;
4292 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004293 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004294
Douglas Gregor20093b42009-12-09 23:02:17 +00004295 // - If the destination type is a reference type, see 8.5.3.
4296 if (DestType->isReferenceType()) {
4297 // C++0x [dcl.init.ref]p1:
4298 // A variable declared to be a T& or T&&, that is, "reference to type T"
4299 // (8.3.2), shall be initialized by an object, or function, of type T or
4300 // by an object that can be converted into a T.
4301 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004302 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004303 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004304 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004305 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004306 return;
4307 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308
Douglas Gregor20093b42009-12-09 23:02:17 +00004309 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004310 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004311 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004312 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004313 return;
4314 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315
Douglas Gregor99a2e602009-12-16 01:38:02 +00004316 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004317 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004318 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004319 return;
4320 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004321
John McCallce6c9b72011-02-21 07:22:22 +00004322 // - If the destination type is an array of characters, an array of
4323 // char16_t, an array of char32_t, or an array of wchar_t, and the
4324 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004325 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004326 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004327 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004328 if (Initializer && isa<VariableArrayType>(DestAT)) {
4329 SetFailed(FK_VariableLengthArrayHasInitializer);
4330 return;
4331 }
4332
Hans Wennborg0ff50742013-05-15 11:03:04 +00004333 if (Initializer) {
4334 switch (IsStringInit(Initializer, DestAT, Context)) {
4335 case SIF_None:
4336 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4337 return;
4338 case SIF_NarrowStringIntoWideChar:
4339 SetFailed(FK_NarrowStringIntoWideCharArray);
4340 return;
4341 case SIF_WideStringIntoChar:
4342 SetFailed(FK_WideStringIntoCharArray);
4343 return;
4344 case SIF_IncompatWideStringIntoWideChar:
4345 SetFailed(FK_IncompatWideStringIntoWideChar);
4346 return;
4347 case SIF_Other:
4348 break;
4349 }
John McCallce6c9b72011-02-21 07:22:22 +00004350 }
4351
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004352 // Note: as an GNU C extension, we allow initialization of an
4353 // array from a compound literal that creates an array of the same
4354 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004355 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004356 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4357 Initializer->getType()->isArrayType()) {
4358 const ArrayType *SourceAT
4359 = Context.getAsArrayType(Initializer->getType());
4360 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004361 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004362 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004363 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004364 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004365 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004366 }
Richard Smith0f163e92012-02-15 22:38:09 +00004367 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004368 // Note: as a GNU C++ extension, we allow list-initialization of a
4369 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004370 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004371 Entity.getKind() == InitializedEntity::EK_Member &&
4372 Initializer && isa<InitListExpr>(Initializer)) {
4373 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4374 *this);
4375 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004376 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004377 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004378 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4379 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004380 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004381 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004382
Douglas Gregor20093b42009-12-09 23:02:17 +00004383 return;
4384 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004385
John McCallf85e1932011-06-15 23:02:42 +00004386 // Determine whether we should consider writeback conversions for
4387 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004388 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004389 Entity.getKind() == InitializedEntity::EK_Parameter;
4390
4391 // We're at the end of the line for C: it's either a write-back conversion
4392 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004393 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004394 // If allowed, check whether this is an Objective-C writeback conversion.
4395 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004396 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004397 return;
4398 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004399
4400 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4401 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004402
4403 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4404 return;
4405
John McCallf85e1932011-06-15 23:02:42 +00004406 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004407 AddCAssignmentStep(DestType);
4408 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004409 return;
4410 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004411
David Blaikie4e4d0842012-03-11 07:00:24 +00004412 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004413
Douglas Gregor20093b42009-12-09 23:02:17 +00004414 // - If the destination type is a (possibly cv-qualified) class type:
4415 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004416 // - If the initialization is direct-initialization, or if it is
4417 // copy-initialization where the cv-unqualified version of the
4418 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004419 // class of the destination, constructors are considered. [...]
4420 if (Kind.getKind() == InitializationKind::IK_Direct ||
4421 (Kind.getKind() == InitializationKind::IK_Copy &&
4422 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4423 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004424 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004425 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004426 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004427 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004428 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004429 // used) to a derived class thereof are enumerated as described in
4430 // 13.3.1.4, and the best one is chosen through overload resolution
4431 // (13.3).
4432 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004433 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004434 return;
4435 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004436
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004437 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004438 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004439 return;
4440 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004441 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004442
4443 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004444 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004445 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004446 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4447 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004448 return;
4449 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004450
Douglas Gregor20093b42009-12-09 23:02:17 +00004451 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004452 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004453 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004454 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004455 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004456
4457 ImplicitConversionSequence ICS
4458 = S.TryImplicitConversion(Initializer, Entity.getType(),
4459 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004460 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004461 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004462 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4463 allowObjCWritebackConversion);
4464
4465 if (ICS.isStandard() &&
4466 ICS.Standard.Second == ICK_Writeback_Conversion) {
4467 // Objective-C ARC writeback conversion.
4468
4469 // We should copy unless we're passing to an argument explicitly
4470 // marked 'out'.
4471 bool ShouldCopy = true;
4472 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4473 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4474
4475 // If there was an lvalue adjustment, add it as a separate conversion.
4476 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4477 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4478 ImplicitConversionSequence LvalueICS;
4479 LvalueICS.setStandard();
4480 LvalueICS.Standard.setAsIdentityConversion();
4481 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4482 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004483 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004484 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004485
4486 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004487 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004488 DeclAccessPair dap;
4489 if (Initializer->getType() == Context.OverloadTy &&
4490 !S.ResolveAddressOfOverloadedFunction(Initializer
4491 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004492 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004493 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004494 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004495 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004496 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004497
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004498 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004499 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004500}
4501
4502InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004503 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004504 StepEnd = Steps.end();
4505 Step != StepEnd; ++Step)
4506 Step->Destroy();
4507}
4508
4509//===----------------------------------------------------------------------===//
4510// Perform initialization
4511//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004513getAssignmentAction(const InitializedEntity &Entity) {
4514 switch(Entity.getKind()) {
4515 case InitializedEntity::EK_Variable:
4516 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004517 case InitializedEntity::EK_Exception:
4518 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004519 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004520 return Sema::AA_Initializing;
4521
4522 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004523 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004524 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4525 return Sema::AA_Sending;
4526
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004527 return Sema::AA_Passing;
4528
4529 case InitializedEntity::EK_Result:
4530 return Sema::AA_Returning;
4531
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004532 case InitializedEntity::EK_Temporary:
4533 // FIXME: Can we tell apart casting vs. converting?
4534 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004535
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004536 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004537 case InitializedEntity::EK_ArrayElement:
4538 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004539 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004540 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004541 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004542 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004543 return Sema::AA_Initializing;
4544 }
4545
David Blaikie7530c032012-01-17 06:56:22 +00004546 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004547}
4548
Richard Smith774d8b42013-01-08 00:08:23 +00004549/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004550/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004551static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004552 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004553 case InitializedEntity::EK_ArrayElement:
4554 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004555 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004556 case InitializedEntity::EK_New:
4557 case InitializedEntity::EK_Variable:
4558 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004559 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004560 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004561 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004562 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004563 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004564 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004565 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004566 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004567
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004568 case InitializedEntity::EK_Parameter:
4569 case InitializedEntity::EK_Temporary:
4570 return true;
4571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004572
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004573 llvm_unreachable("missed an InitializedEntity kind?");
4574}
4575
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004576/// \brief Whether the given entity, when initialized with an object
4577/// created for that initialization, requires destruction.
4578static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4579 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004580 case InitializedEntity::EK_Result:
4581 case InitializedEntity::EK_New:
4582 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004583 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004584 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004585 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004586 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004587 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004588 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004589
Richard Smith774d8b42013-01-08 00:08:23 +00004590 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004591 case InitializedEntity::EK_Variable:
4592 case InitializedEntity::EK_Parameter:
4593 case InitializedEntity::EK_Temporary:
4594 case InitializedEntity::EK_ArrayElement:
4595 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004596 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004597 return true;
4598 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004599
4600 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004601}
4602
Richard Smith83da2e72011-10-19 16:55:56 +00004603/// \brief Look for copy and move constructors and constructor templates, for
4604/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4605static void LookupCopyAndMoveConstructors(Sema &S,
4606 OverloadCandidateSet &CandidateSet,
4607 CXXRecordDecl *Class,
4608 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004609 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004610 // The container holding the constructors can under certain conditions
4611 // be changed while iterating (e.g. because of deserialization).
4612 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004613 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004614 for (SmallVector<NamedDecl*, 16>::iterator
4615 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4616 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004617 CXXConstructorDecl *Constructor = 0;
4618
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004619 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004620 // Handle copy/moveconstructors, only.
4621 if (!Constructor || Constructor->isInvalidDecl() ||
4622 !Constructor->isCopyOrMoveConstructor() ||
4623 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4624 continue;
4625
4626 DeclAccessPair FoundDecl
4627 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4628 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004629 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004630 continue;
4631 }
4632
4633 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004634 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004635 if (ConstructorTmpl->isInvalidDecl())
4636 continue;
4637
4638 Constructor = cast<CXXConstructorDecl>(
4639 ConstructorTmpl->getTemplatedDecl());
4640 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4641 continue;
4642
4643 // FIXME: Do we need to limit this to copy-constructor-like
4644 // candidates?
4645 DeclAccessPair FoundDecl
4646 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4647 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004648 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004649 }
4650}
4651
4652/// \brief Get the location at which initialization diagnostics should appear.
4653static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4654 Expr *Initializer) {
4655 switch (Entity.getKind()) {
4656 case InitializedEntity::EK_Result:
4657 return Entity.getReturnLoc();
4658
4659 case InitializedEntity::EK_Exception:
4660 return Entity.getThrowLoc();
4661
4662 case InitializedEntity::EK_Variable:
4663 return Entity.getDecl()->getLocation();
4664
Douglas Gregor47736542012-02-15 16:57:26 +00004665 case InitializedEntity::EK_LambdaCapture:
4666 return Entity.getCaptureLoc();
4667
Richard Smith83da2e72011-10-19 16:55:56 +00004668 case InitializedEntity::EK_ArrayElement:
4669 case InitializedEntity::EK_Member:
4670 case InitializedEntity::EK_Parameter:
4671 case InitializedEntity::EK_Temporary:
4672 case InitializedEntity::EK_New:
4673 case InitializedEntity::EK_Base:
4674 case InitializedEntity::EK_Delegating:
4675 case InitializedEntity::EK_VectorElement:
4676 case InitializedEntity::EK_ComplexElement:
4677 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004678 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith83da2e72011-10-19 16:55:56 +00004679 return Initializer->getLocStart();
4680 }
4681 llvm_unreachable("missed an InitializedEntity kind?");
4682}
4683
Douglas Gregor523d46a2010-04-18 07:40:54 +00004684/// \brief Make a (potentially elidable) temporary copy of the object
4685/// provided by the given initializer by calling the appropriate copy
4686/// constructor.
4687///
4688/// \param S The Sema object used for type-checking.
4689///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004690/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004691/// the type of the initializer expression or a superclass thereof.
4692///
James Dennett1dfbd922012-06-14 21:40:34 +00004693/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004694///
4695/// \param CurInit The initializer expression.
4696///
4697/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4698/// is permitted in C++03 (but not C++0x) when binding a reference to
4699/// an rvalue.
4700///
4701/// \returns An expression that copies the initializer expression into
4702/// a temporary object, or an error expression if a copy could not be
4703/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004704static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004705 QualType T,
4706 const InitializedEntity &Entity,
4707 ExprResult CurInit,
4708 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004709 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004710 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004711 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004712 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004713 Class = cast<CXXRecordDecl>(Record->getDecl());
4714 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004715 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004716
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004717 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004718 // When certain criteria are met, an implementation is allowed to
4719 // omit the copy/move construction of a class object, even if the
4720 // copy/move constructor and/or destructor for the object have
4721 // side effects. [...]
4722 // - when a temporary class object that has not been bound to a
4723 // reference (12.2) would be copied/moved to a class object
4724 // with the same cv-unqualified type, the copy/move operation
4725 // can be omitted by constructing the temporary object
4726 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004727 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004728 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004729 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004730 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004731 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004732 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004733 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004734
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004735 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004736 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004737 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004738
Douglas Gregorcc15f012011-01-21 19:38:21 +00004739 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004740 // Only consider constructors and constructor templates. Per
4741 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4742 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004743 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004744 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004745
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004746 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4747
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004748 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004749 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004750 case OR_Success:
4751 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004752
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004753 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004754 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4755 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4756 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004757 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004758 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004759 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004760 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004761 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004762 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004763
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004764 case OR_Ambiguous:
4765 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004766 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004767 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004768 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004769 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004770
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004771 case OR_Deleted:
4772 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004773 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004774 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004775 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004776 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004777 }
4778
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004779 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004780 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004781 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004782
Anders Carlsson9a68a672010-04-21 18:47:17 +00004783 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004784 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004785
4786 if (IsExtraneousCopy) {
4787 // If this is a totally extraneous copy for C++03 reference
4788 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004789 // expression. We don't generate an (elided) copy operation here
4790 // because doing so would require us to pass down a flag to avoid
4791 // infinite recursion, where each step adds another extraneous,
4792 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004793
Douglas Gregor2559a702010-04-18 07:57:34 +00004794 // Instantiate the default arguments of any extra parameters in
4795 // the selected copy constructor, as if we were going to create a
4796 // proper call to the copy constructor.
4797 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4798 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4799 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004800 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004801 break;
4802
4803 // Build the default argument expression; we don't actually care
4804 // if this succeeds or not, because this routine will complain
4805 // if there was a problem.
4806 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4807 }
4808
Douglas Gregor523d46a2010-04-18 07:40:54 +00004809 return S.Owned(CurInitExpr);
4810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004811
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004812 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004813 // constructor call (we might have derived-to-base conversions, or
4814 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004815 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004816 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004817
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004818 // Actually perform the constructor call.
4819 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004820 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004821 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004822 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004823 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004824 CXXConstructExpr::CK_Complete,
4825 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004826
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004827 // If we're supposed to bind temporaries, do so.
4828 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4829 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004830 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004831}
Douglas Gregor20093b42009-12-09 23:02:17 +00004832
Richard Smith83da2e72011-10-19 16:55:56 +00004833/// \brief Check whether elidable copy construction for binding a reference to
4834/// a temporary would have succeeded if we were building in C++98 mode, for
4835/// -Wc++98-compat.
4836static void CheckCXX98CompatAccessibleCopy(Sema &S,
4837 const InitializedEntity &Entity,
4838 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004839 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004840
4841 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4842 if (!Record)
4843 return;
4844
4845 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4846 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4847 == DiagnosticsEngine::Ignored)
4848 return;
4849
4850 // Find constructors which would have been considered.
4851 OverloadCandidateSet CandidateSet(Loc);
4852 LookupCopyAndMoveConstructors(
4853 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4854
4855 // Perform overload resolution.
4856 OverloadCandidateSet::iterator Best;
4857 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4858
4859 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4860 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4861 << CurInitExpr->getSourceRange();
4862
4863 switch (OR) {
4864 case OR_Success:
4865 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004866 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004867 // FIXME: Check default arguments as far as that's possible.
4868 break;
4869
4870 case OR_No_Viable_Function:
4871 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004872 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004873 break;
4874
4875 case OR_Ambiguous:
4876 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004877 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004878 break;
4879
4880 case OR_Deleted:
4881 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004882 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004883 break;
4884 }
4885}
4886
Douglas Gregora41a8c52010-04-22 00:20:18 +00004887void InitializationSequence::PrintInitLocationNote(Sema &S,
4888 const InitializedEntity &Entity) {
4889 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4890 if (Entity.getDecl()->getLocation().isInvalid())
4891 return;
4892
4893 if (Entity.getDecl()->getDeclName())
4894 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4895 << Entity.getDecl()->getDeclName();
4896 else
4897 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4898 }
4899}
4900
Sebastian Redl3b802322011-07-14 19:07:55 +00004901static bool isReferenceBinding(const InitializationSequence::Step &s) {
4902 return s.Kind == InitializationSequence::SK_BindReference ||
4903 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4904}
4905
Jordan Rose2624b812013-05-06 16:48:12 +00004906/// Returns true if the parameters describe a constructor initialization of
4907/// an explicit temporary object, e.g. "Point(x, y)".
4908static bool isExplicitTemporary(const InitializedEntity &Entity,
4909 const InitializationKind &Kind,
4910 unsigned NumArgs) {
4911 switch (Entity.getKind()) {
4912 case InitializedEntity::EK_Temporary:
4913 case InitializedEntity::EK_CompoundLiteralInit:
4914 break;
4915 default:
4916 return false;
4917 }
4918
4919 switch (Kind.getKind()) {
4920 case InitializationKind::IK_DirectList:
4921 return true;
4922 // FIXME: Hack to work around cast weirdness.
4923 case InitializationKind::IK_Direct:
4924 case InitializationKind::IK_Value:
4925 return NumArgs != 1;
4926 default:
4927 return false;
4928 }
4929}
4930
Sebastian Redl10f04a62011-12-22 14:44:04 +00004931static ExprResult
4932PerformConstructorInitialization(Sema &S,
4933 const InitializedEntity &Entity,
4934 const InitializationKind &Kind,
4935 MultiExprArg Args,
4936 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004937 bool &ConstructorInitRequiresZeroInit,
4938 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004939 unsigned NumArgs = Args.size();
4940 CXXConstructorDecl *Constructor
4941 = cast<CXXConstructorDecl>(Step.Function.Function);
4942 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4943
4944 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004945 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004946 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4947 ? Kind.getEqualLoc()
4948 : Kind.getLocation();
4949
4950 if (Kind.getKind() == InitializationKind::IK_Default) {
4951 // Force even a trivial, implicit default constructor to be
4952 // semantically checked. We do this explicitly because we don't build
4953 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004954 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004955 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004956 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004957 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4958 }
4959
4960 ExprResult CurInit = S.Owned((Expr *)0);
4961
Douglas Gregored878af2012-02-24 23:56:31 +00004962 // C++ [over.match.copy]p1:
4963 // - When initializing a temporary to be bound to the first parameter
4964 // of a constructor that takes a reference to possibly cv-qualified
4965 // T as its first argument, called with a single argument in the
4966 // context of direct-initialization, explicit conversion functions
4967 // are also considered.
4968 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4969 Args.size() == 1 &&
4970 Constructor->isCopyOrMoveConstructor();
4971
Sebastian Redl10f04a62011-12-22 14:44:04 +00004972 // Determine the arguments required to actually perform the constructor
4973 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004974 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004975 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004976 AllowExplicitConv,
4977 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004978 return ExprError();
4979
4980
Jordan Rose2624b812013-05-06 16:48:12 +00004981 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004982 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004983 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00004984 if (S.DiagnoseUseOfDecl(Constructor, Loc))
4985 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004986
4987 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4988 if (!TSInfo)
4989 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004990 SourceRange ParenRange;
4991 if (Kind.getKind() != InitializationKind::IK_DirectList)
4992 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004993
Richard Smithc83c2302012-12-19 01:39:02 +00004994 CurInit = S.Owned(
4995 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4996 TSInfo, ConstructorArgs,
4997 ParenRange, IsListInitialization,
4998 HadMultipleCandidates,
4999 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00005000 } else {
5001 CXXConstructExpr::ConstructionKind ConstructKind =
5002 CXXConstructExpr::CK_Complete;
5003
5004 if (Entity.getKind() == InitializedEntity::EK_Base) {
5005 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5006 CXXConstructExpr::CK_VirtualBase :
5007 CXXConstructExpr::CK_NonVirtualBase;
5008 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5009 ConstructKind = CXXConstructExpr::CK_Delegating;
5010 }
5011
5012 // Only get the parenthesis range if it is a direct construction.
5013 SourceRange parenRange =
5014 Kind.getKind() == InitializationKind::IK_Direct ?
5015 Kind.getParenRange() : SourceRange();
5016
5017 // If the entity allows NRVO, mark the construction as elidable
5018 // unconditionally.
5019 if (Entity.allowsNRVO())
5020 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5021 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005022 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005023 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005024 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005025 ConstructorInitRequiresZeroInit,
5026 ConstructKind,
5027 parenRange);
5028 else
5029 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5030 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005031 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005032 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005033 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005034 ConstructorInitRequiresZeroInit,
5035 ConstructKind,
5036 parenRange);
5037 }
5038 if (CurInit.isInvalid())
5039 return ExprError();
5040
5041 // Only check access if all of that succeeded.
5042 S.CheckConstructorAccess(Loc, Constructor, Entity,
5043 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005044 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5045 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005046
5047 if (shouldBindAsTemporary(Entity))
5048 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5049
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005050 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005051}
5052
Richard Smith36d02af2012-06-04 22:27:30 +00005053/// Determine whether the specified InitializedEntity definitely has a lifetime
5054/// longer than the current full-expression. Conservatively returns false if
5055/// it's unclear.
5056static bool
5057InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5058 const InitializedEntity *Top = &Entity;
5059 while (Top->getParent())
5060 Top = Top->getParent();
5061
5062 switch (Top->getKind()) {
5063 case InitializedEntity::EK_Variable:
5064 case InitializedEntity::EK_Result:
5065 case InitializedEntity::EK_Exception:
5066 case InitializedEntity::EK_Member:
5067 case InitializedEntity::EK_New:
5068 case InitializedEntity::EK_Base:
5069 case InitializedEntity::EK_Delegating:
5070 return true;
5071
5072 case InitializedEntity::EK_ArrayElement:
5073 case InitializedEntity::EK_VectorElement:
5074 case InitializedEntity::EK_BlockElement:
5075 case InitializedEntity::EK_ComplexElement:
5076 // Could not determine what the full initialization is. Assume it might not
5077 // outlive the full-expression.
5078 return false;
5079
5080 case InitializedEntity::EK_Parameter:
5081 case InitializedEntity::EK_Temporary:
5082 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005083 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith36d02af2012-06-04 22:27:30 +00005084 // The entity being initialized might not outlive the full-expression.
5085 return false;
5086 }
5087
5088 llvm_unreachable("unknown entity kind");
5089}
5090
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005092InitializationSequence::Perform(Sema &S,
5093 const InitializedEntity &Entity,
5094 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005095 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005096 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005097 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005098 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005099 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005100 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005101
Sebastian Redl7491c492011-06-05 13:59:11 +00005102 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005103 // If the declaration is a non-dependent, incomplete array type
5104 // that has an initializer, then its type will be completed once
5105 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005106 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005107 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005108 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005109 if (const IncompleteArrayType *ArrayT
5110 = S.Context.getAsIncompleteArrayType(DeclType)) {
5111 // FIXME: We don't currently have the ability to accurately
5112 // compute the length of an initializer list without
5113 // performing full type-checking of the initializer list
5114 // (since we have to determine where braces are implicitly
5115 // introduced and such). So, we fall back to making the array
5116 // type a dependently-sized array type with no specified
5117 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005118 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005119 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005120
Douglas Gregord87b61f2009-12-10 17:56:55 +00005121 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005122 if (DeclaratorDecl *DD = Entity.getDecl()) {
5123 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5124 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005125 if (IncompleteArrayTypeLoc ArrayLoc =
5126 TL.getAs<IncompleteArrayTypeLoc>())
5127 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005128 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005129 }
5130
5131 *ResultType
5132 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5133 /*NumElts=*/0,
5134 ArrayT->getSizeModifier(),
5135 ArrayT->getIndexTypeCVRQualifiers(),
5136 Brackets);
5137 }
5138
5139 }
5140 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005141 if (Kind.getKind() == InitializationKind::IK_Direct &&
5142 !Kind.isExplicitCast()) {
5143 // Rebuild the ParenListExpr.
5144 SourceRange ParenRange = Kind.getParenRange();
5145 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005146 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005147 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005148 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005149 Kind.isExplicitCast() ||
5150 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005151 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005152 }
5153
Sebastian Redl7491c492011-06-05 13:59:11 +00005154 // No steps means no initialization.
5155 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005156 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005157
Richard Smith80ad52f2013-01-02 11:42:31 +00005158 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005159 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005160 Entity.getKind() != InitializedEntity::EK_Parameter) {
5161 // Produce a C++98 compatibility warning if we are initializing a reference
5162 // from an initializer list. For parameters, we produce a better warning
5163 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005164 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005165 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5166 << Init->getSourceRange();
5167 }
5168
Richard Smith36d02af2012-06-04 22:27:30 +00005169 // Diagnose cases where we initialize a pointer to an array temporary, and the
5170 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005171 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005172 Entity.getType()->isPointerType() &&
5173 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005174 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005175 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5176 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5177 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5178 << Init->getSourceRange();
5179 }
5180
Douglas Gregord6542d82009-12-22 15:35:07 +00005181 QualType DestType = Entity.getType().getNonReferenceType();
5182 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005183 // the same as Entity.getDecl()->getType() in cases involving type merging,
5184 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005185 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005186 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005187 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005188
John McCall60d7b3a2010-08-24 06:29:42 +00005189 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005190
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005191 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005192 // grab the only argument out the Args and place it into the "current"
5193 // initializer.
5194 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005195 case SK_ResolveAddressOfOverloadedFunction:
5196 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005197 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005198 case SK_CastDerivedToBaseLValue:
5199 case SK_BindReference:
5200 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005201 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005202 case SK_UserConversion:
5203 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005204 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005205 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005206 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005207 case SK_ConversionSequence:
5208 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005209 case SK_UnwrapInitList:
5210 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005211 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005212 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005213 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005214 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005215 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005216 case SK_PassByIndirectCopyRestore:
5217 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005218 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005219 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005220 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005221 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005222 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005223 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005224 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005225 break;
John McCallf6a16482010-12-04 03:47:34 +00005226 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005227
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005228 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005229 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005230 case SK_ZeroInitialization:
5231 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005232 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005233
5234 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005235 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005236 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005237 for (step_iterator Step = step_begin(), StepEnd = step_end();
5238 Step != StepEnd; ++Step) {
5239 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005240 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005241
John Wiegley429bb272011-04-08 18:41:53 +00005242 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005243
Douglas Gregor20093b42009-12-09 23:02:17 +00005244 switch (Step->Kind) {
5245 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005246 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005247 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005248 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005249 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5250 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005251 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005252 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005253 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005254 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005255
Douglas Gregor20093b42009-12-09 23:02:17 +00005256 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005257 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005258 case SK_CastDerivedToBaseLValue: {
5259 // We have a derived-to-base cast that produces either an rvalue or an
5260 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005261
John McCallf871d0c2010-08-07 06:22:56 +00005262 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005263
Douglas Gregor20093b42009-12-09 23:02:17 +00005264 // Casts to inaccessible base classes are allowed with C-style casts.
5265 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5266 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005267 CurInit.get()->getLocStart(),
5268 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005269 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005270 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005271
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005272 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5273 QualType T = SourceType;
5274 if (const PointerType *Pointer = T->getAs<PointerType>())
5275 T = Pointer->getPointeeType();
5276 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005277 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005278 cast<CXXRecordDecl>(RecordTy->getDecl()));
5279 }
5280
John McCall5baba9d2010-08-25 10:28:54 +00005281 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005282 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005283 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005284 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005285 VK_XValue :
5286 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005287 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5288 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005289 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005290 CurInit.get(),
5291 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005292 break;
5293 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005294
Douglas Gregor20093b42009-12-09 23:02:17 +00005295 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005296 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5297 if (CurInit.get()->refersToBitField()) {
5298 // We don't necessarily have an unambiguous source bit-field.
5299 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005300 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005301 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005302 << (BitField ? BitField->getDeclName() : DeclarationName())
5303 << (BitField != NULL)
John Wiegley429bb272011-04-08 18:41:53 +00005304 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005305 if (BitField)
5306 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5307
John McCallf312b1e2010-08-26 23:41:50 +00005308 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005309 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005310
John Wiegley429bb272011-04-08 18:41:53 +00005311 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005312 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005313 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5314 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005315 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005316 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005317 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005318 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005319
Douglas Gregor20093b42009-12-09 23:02:17 +00005320 // Reference binding does not have any corresponding ASTs.
5321
5322 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005323 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005324 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005325
Douglas Gregor20093b42009-12-09 23:02:17 +00005326 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005327
Douglas Gregor20093b42009-12-09 23:02:17 +00005328 case SK_BindReferenceToTemporary:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005329 // Make sure the "temporary" is actually an rvalue.
5330 assert(CurInit.get()->isRValue() && "not a temporary");
5331
Douglas Gregor20093b42009-12-09 23:02:17 +00005332 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005333 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005334 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005335
Douglas Gregor03e80032011-06-21 17:03:29 +00005336 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005337 CurInit = new (S.Context) MaterializeTemporaryExpr(
5338 Entity.getType().getNonReferenceType(),
5339 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005340 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005341
5342 // If we're binding to an Objective-C object that has lifetime, we
5343 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005344 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005345 CurInit.get()->getType()->isObjCLifetimeType())
5346 S.ExprNeedsCleanups = true;
5347
Douglas Gregor20093b42009-12-09 23:02:17 +00005348 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005349
Douglas Gregor523d46a2010-04-18 07:40:54 +00005350 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005351 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005352 /*IsExtraneousCopy=*/true);
5353 break;
5354
Douglas Gregor20093b42009-12-09 23:02:17 +00005355 case SK_UserConversion: {
5356 // We have a user-defined conversion that invokes either a constructor
5357 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005358 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005359 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005360 FunctionDecl *Fn = Step->Function.Function;
5361 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005362 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005363 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005364 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005365 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005366 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005367 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005368 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005369
Douglas Gregor20093b42009-12-09 23:02:17 +00005370 // Determine the arguments required to actually perform the constructor
5371 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005372 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005373 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005374 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005375 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005376 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005377
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005378 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005379 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005380 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005381 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005382 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005383 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005384 CXXConstructExpr::CK_Complete,
5385 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005386 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005387 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005388
Anders Carlsson9a68a672010-04-21 18:47:17 +00005389 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005390 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005391 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5392 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005393
John McCall2de56d12010-08-25 11:45:40 +00005394 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005395 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5396 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5397 S.IsDerivedFrom(SourceType, Class))
5398 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005399
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005400 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005401 } else {
5402 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005403 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005404 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005405 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005406 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5407 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005408
5409 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005410 // derived-to-base conversion? I believe the answer is "no", because
5411 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005412 ExprResult CurInitExprRes =
5413 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5414 FoundFn, Conversion);
5415 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005416 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005417 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005418
Douglas Gregor20093b42009-12-09 23:02:17 +00005419 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005420 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5421 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005422 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005423 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424
John McCall2de56d12010-08-25 11:45:40 +00005425 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005426
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005427 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005428 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005429
Sebastian Redl3b802322011-07-14 19:07:55 +00005430 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005431 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5432
5433 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005434 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005435 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005436 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005437 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005438 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005439 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005440 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005441 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5442 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005443 }
5444 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005445
John McCallf871d0c2010-08-07 06:22:56 +00005446 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005447 CurInit.get()->getType(),
5448 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005449 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005450 if (MaybeBindToTemp)
5451 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005452 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005453 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005454 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005455 break;
5456 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005457
Douglas Gregor20093b42009-12-09 23:02:17 +00005458 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005459 case SK_QualificationConversionXValue:
5460 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005461 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005462 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005463 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005464 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005465 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005466 VK_XValue :
5467 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005468 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005469 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005470 }
5471
Jordan Rose1fd1e282013-04-11 00:58:58 +00005472 case SK_LValueToRValue: {
5473 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5474 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5475 CK_LValueToRValue,
5476 CurInit.take(),
5477 /*BasePath=*/0,
5478 VK_RValue));
5479 break;
5480 }
5481
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005482 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005483 Sema::CheckedConversionKind CCK
5484 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5485 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005486 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005487 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005488 ExprResult CurInitExprRes =
5489 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005490 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005491 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005492 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005493 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005494 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005495 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005496
Douglas Gregord87b61f2009-12-10 17:56:55 +00005497 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005498 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005499 // Hack: We must pass *ResultType if available in order to set the type
5500 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5501 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5502 // temporary, not a reference, so we should pass Ty.
5503 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5504 // Since this step is never used for a reference directly, we explicitly
5505 // unwrap references here and rewrap them afterwards.
5506 // We also need to create a InitializeTemporary entity for this.
5507 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005508 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005509 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005510 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5511 InitListChecker PerformInitList(S, InitEntity,
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005512 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005513 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00005514 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005515 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005516 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005517
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005518 if (ResultType) {
5519 if ((*ResultType)->isRValueReferenceType())
5520 Ty = S.Context.getRValueReferenceType(Ty);
5521 else if ((*ResultType)->isLValueReferenceType())
5522 Ty = S.Context.getLValueReferenceType(Ty,
5523 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5524 *ResultType = Ty;
5525 }
5526
5527 InitListExpr *StructuredInitList =
5528 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005529 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005530 CurInit = shouldBindAsTemporary(InitEntity)
5531 ? S.MaybeBindToTemporary(StructuredInitList)
5532 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005533 break;
5534 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005535
Sebastian Redl10f04a62011-12-22 14:44:04 +00005536 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005537 // When an initializer list is passed for a parameter of type "reference
5538 // to object", we don't get an EK_Temporary entity, but instead an
5539 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005540 // FIXME: This is a hack. What we really should do is create a user
5541 // conversion step for this case, but this makes it considerably more
5542 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005543 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5544 Entity.getType().getNonReferenceType());
5545 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005546 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005547 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005548 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5549 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005550 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005551 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5552 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005553 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005554 ConstructorInitRequiresZeroInit,
5555 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005556 break;
5557 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005558
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005559 case SK_UnwrapInitList:
5560 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5561 break;
5562
5563 case SK_RewrapInitList: {
5564 Expr *E = CurInit.take();
5565 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5566 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005567 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005568 ILE->setSyntacticForm(Syntactic);
5569 ILE->setType(E->getType());
5570 ILE->setValueKind(E->getValueKind());
5571 CurInit = S.Owned(ILE);
5572 break;
5573 }
5574
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005575 case SK_ConstructorInitialization: {
5576 // When an initializer list is passed for a parameter of type "reference
5577 // to object", we don't get an EK_Temporary entity, but instead an
5578 // EK_Parameter entity with reference type.
5579 // FIXME: This is a hack. What we really should do is create a user
5580 // conversion step for this case, but this makes it considerably more
5581 // complicated. For now, this will do.
5582 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5583 Entity.getType().getNonReferenceType());
5584 bool UseTemporary = Entity.getType()->isReferenceType();
5585 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5586 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005587 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005588 ConstructorInitRequiresZeroInit,
5589 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005590 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005591 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005592
Douglas Gregor71d17402009-12-15 00:01:57 +00005593 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005594 step_iterator NextStep = Step;
5595 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005596 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005597 (NextStep->Kind == SK_ConstructorInitialization ||
5598 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005599 // The need for zero-initialization is recorded directly into
5600 // the call to the object's constructor within the next step.
5601 ConstructorInitRequiresZeroInit = true;
5602 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005603 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005604 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005605 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5606 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005607 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005608 Kind.getRange().getBegin());
5609
5610 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5611 TSInfo->getType().getNonLValueExprType(S.Context),
5612 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005613 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005614 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005615 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005616 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005617 break;
5618 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005619
5620 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005621 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005622 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005623 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005624 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5625 if (Result.isInvalid())
5626 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005627 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005628
5629 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005630 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005631 if (ConvTy != Sema::Compatible &&
5632 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005633 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005634 == Sema::Compatible)
5635 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005636 if (CurInitExprRes.isInvalid())
5637 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005638 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005639
Douglas Gregora41a8c52010-04-22 00:20:18 +00005640 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005641 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5642 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005643 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005644 getAssignmentAction(Entity),
5645 &Complained)) {
5646 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005647 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005648 } else if (Complained)
5649 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005650 break;
5651 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005652
5653 case SK_StringInit: {
5654 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005655 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005656 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005657 break;
5658 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005659
5660 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005661 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005662 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005663 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005664 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005665
5666 case SK_ArrayInit:
5667 // Okay: we checked everything before creating this step. Note that
5668 // this is a GNU extension.
5669 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005670 << Step->Type << CurInit.get()->getType()
5671 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005672
5673 // If the destination type is an incomplete array type, update the
5674 // type accordingly.
5675 if (ResultType) {
5676 if (const IncompleteArrayType *IncompleteDest
5677 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5678 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005679 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005680 *ResultType = S.Context.getConstantArrayType(
5681 IncompleteDest->getElementType(),
5682 ConstantSource->getSize(),
5683 ArrayType::Normal, 0);
5684 }
5685 }
5686 }
John McCallf85e1932011-06-15 23:02:42 +00005687 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005688
Richard Smith0f163e92012-02-15 22:38:09 +00005689 case SK_ParenthesizedArrayInit:
5690 // Okay: we checked everything before creating this step. Note that
5691 // this is a GNU extension.
5692 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5693 << CurInit.get()->getSourceRange();
5694 break;
5695
John McCallf85e1932011-06-15 23:02:42 +00005696 case SK_PassByIndirectCopyRestore:
5697 case SK_PassByIndirectRestore:
5698 checkIndirectCopyRestoreSource(S, CurInit.get());
5699 CurInit = S.Owned(new (S.Context)
5700 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5701 Step->Kind == SK_PassByIndirectCopyRestore));
5702 break;
5703
5704 case SK_ProduceObjCObject:
5705 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005706 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005707 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005708 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005709
5710 case SK_StdInitializerList: {
5711 QualType Dest = Step->Type;
5712 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005713 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005714 (void)Success;
5715 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005716
5717 // If the element type has a destructor, check it.
5718 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5719 if (!RD->hasIrrelevantDestructor()) {
5720 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5721 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5722 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5723 S.PDiag(diag::err_access_dtor_temp) << E);
Richard Smith82f145d2013-05-04 06:44:46 +00005724 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5725 return ExprError();
Sebastian Redl28357452012-03-05 19:35:43 +00005726 }
5727 }
5728 }
5729
Sebastian Redl2b916b82012-01-17 22:49:42 +00005730 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005731 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5732 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005733 unsigned NumInits = ILE->getNumInits();
5734 SmallVector<Expr*, 16> Converted(NumInits);
5735 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5736 S.Context.getConstantArrayType(E,
5737 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5738 NumInits),
5739 ArrayType::Normal, 0));
5740 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5741 0, HiddenArray);
5742 for (unsigned i = 0; i < NumInits; ++i) {
5743 Element.setElementIndex(i);
5744 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005745 ExprResult Res = S.PerformCopyInitialization(
5746 Element, Init.get()->getExprLoc(), Init,
5747 /*TopLevelOfInitList=*/ true);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005748 assert(!Res.isInvalid() && "Result changed since try phase.");
5749 Converted[i] = Res.take();
5750 }
5751 InitListExpr *Semantic = new (S.Context)
5752 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005753 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005754 Semantic->setSyntacticForm(ILE);
5755 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005756 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005757 CurInit = S.Owned(Semantic);
5758 break;
5759 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005760 case SK_OCLSamplerInit: {
5761 assert(Step->Type->isSamplerT() &&
5762 "Sampler initialization on non sampler type.");
5763
5764 QualType SourceType = CurInit.get()->getType();
5765 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5766
5767 if (EntityKind == InitializedEntity::EK_Parameter) {
5768 if (!SourceType->isSamplerT())
5769 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5770 << SourceType;
5771 } else if (EntityKind != InitializedEntity::EK_Variable) {
5772 llvm_unreachable("Invalid EntityKind!");
5773 }
5774
5775 break;
5776 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005777 case SK_OCLZeroEvent: {
5778 assert(Step->Type->isEventT() &&
5779 "Event initialization on non event type.");
5780
5781 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5782 CK_ZeroToOCLEvent,
5783 CurInit.get()->getValueKind());
5784 break;
5785 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005786 }
5787 }
John McCall15d7d122010-11-11 03:21:53 +00005788
5789 // Diagnose non-fatal problems with the completed initialization.
5790 if (Entity.getKind() == InitializedEntity::EK_Member &&
5791 cast<FieldDecl>(Entity.getDecl())->isBitField())
5792 S.CheckBitFieldInitialization(Kind.getLocation(),
5793 cast<FieldDecl>(Entity.getDecl()),
5794 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005795
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005796 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005797}
5798
Richard Smithd5bc8672012-12-08 02:01:17 +00005799/// Somewhere within T there is an uninitialized reference subobject.
5800/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005801static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5802 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005803 if (T->isReferenceType()) {
5804 S.Diag(Loc, diag::err_reference_without_init)
5805 << T.getNonReferenceType();
5806 return true;
5807 }
5808
5809 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5810 if (!RD || !RD->hasUninitializedReferenceMember())
5811 return false;
5812
5813 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5814 FE = RD->field_end(); FI != FE; ++FI) {
5815 if (FI->isUnnamedBitfield())
5816 continue;
5817
5818 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5819 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5820 return true;
5821 }
5822 }
5823
5824 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5825 BE = RD->bases_end();
5826 BI != BE; ++BI) {
5827 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5828 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5829 return true;
5830 }
5831 }
5832
5833 return false;
5834}
5835
5836
Douglas Gregor20093b42009-12-09 23:02:17 +00005837//===----------------------------------------------------------------------===//
5838// Diagnose initialization failures
5839//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00005840
5841/// Emit notes associated with an initialization that failed due to a
5842/// "simple" conversion failure.
5843static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5844 Expr *op) {
5845 QualType destType = entity.getType();
5846 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5847 op->getType()->isObjCObjectPointerType()) {
5848
5849 // Emit a possible note about the conversion failing because the
5850 // operand is a message send with a related result type.
5851 S.EmitRelatedResultTypeNote(op);
5852
5853 // Emit a possible note about a return failing because we're
5854 // expecting a related result type.
5855 if (entity.getKind() == InitializedEntity::EK_Result)
5856 S.EmitRelatedResultTypeNoteForReturn(destType);
5857 }
5858}
5859
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005860bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005861 const InitializedEntity &Entity,
5862 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005863 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005864 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005865 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005866
Douglas Gregord6542d82009-12-22 15:35:07 +00005867 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005868 switch (Failure) {
5869 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005870 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005871 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005872 // Dig out the reference subobject which is uninitialized and diagnose it.
5873 // If this is value-initialization, this could be nested some way within
5874 // the target type.
5875 assert(Kind.getKind() == InitializationKind::IK_Value ||
5876 DestType->isReferenceType());
5877 bool Diagnosed =
5878 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5879 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5880 (void)Diagnosed;
5881 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005882 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005883 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005884 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005885
Douglas Gregor20093b42009-12-09 23:02:17 +00005886 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00005887 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00005888 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00005889 case FK_ArrayNeedsInitListOrStringLiteral:
5890 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
5891 break;
5892 case FK_ArrayNeedsInitListOrWideStringLiteral:
5893 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
5894 break;
5895 case FK_NarrowStringIntoWideCharArray:
5896 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
5897 break;
5898 case FK_WideStringIntoCharArray:
5899 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
5900 break;
5901 case FK_IncompatWideStringIntoWideChar:
5902 S.Diag(Kind.getLocation(),
5903 diag::err_array_init_incompat_wide_string_into_wchar);
5904 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005905 case FK_ArrayTypeMismatch:
5906 case FK_NonConstantArrayInit:
5907 S.Diag(Kind.getLocation(),
5908 (Failure == FK_ArrayTypeMismatch
5909 ? diag::err_array_init_different_type
5910 : diag::err_array_init_non_constant_array))
5911 << DestType.getNonReferenceType()
5912 << Args[0]->getType()
5913 << Args[0]->getSourceRange();
5914 break;
5915
John McCall73076432012-01-05 00:13:19 +00005916 case FK_VariableLengthArrayHasInitializer:
5917 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5918 << Args[0]->getSourceRange();
5919 break;
5920
John McCall6bb80172010-03-30 21:47:33 +00005921 case FK_AddressOfOverloadFailed: {
5922 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005923 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005924 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005925 true,
5926 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005927 break;
John McCall6bb80172010-03-30 21:47:33 +00005928 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005929
Douglas Gregor20093b42009-12-09 23:02:17 +00005930 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005931 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005932 switch (FailedOverloadResult) {
5933 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005934 if (Failure == FK_UserConversionOverloadFailed)
5935 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5936 << Args[0]->getType() << DestType
5937 << Args[0]->getSourceRange();
5938 else
5939 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5940 << DestType << Args[0]->getType()
5941 << Args[0]->getSourceRange();
5942
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005943 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005944 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005945
Douglas Gregor20093b42009-12-09 23:02:17 +00005946 case OR_No_Viable_Function:
5947 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5948 << Args[0]->getType() << DestType.getNonReferenceType()
5949 << Args[0]->getSourceRange();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005950 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005951 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005952
Douglas Gregor20093b42009-12-09 23:02:17 +00005953 case OR_Deleted: {
5954 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5955 << Args[0]->getType() << DestType.getNonReferenceType()
5956 << Args[0]->getSourceRange();
5957 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005958 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005959 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5960 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005961 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005962 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005963 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005964 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005965 }
5966 break;
5967 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005968
Douglas Gregor20093b42009-12-09 23:02:17 +00005969 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005970 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005971 }
5972 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005973
Douglas Gregor20093b42009-12-09 23:02:17 +00005974 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005975 if (isa<InitListExpr>(Args[0])) {
5976 S.Diag(Kind.getLocation(),
5977 diag::err_lvalue_reference_bind_to_initlist)
5978 << DestType.getNonReferenceType().isVolatileQualified()
5979 << DestType.getNonReferenceType()
5980 << Args[0]->getSourceRange();
5981 break;
5982 }
5983 // Intentional fallthrough
5984
Douglas Gregor20093b42009-12-09 23:02:17 +00005985 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005986 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005987 Failure == FK_NonConstLValueReferenceBindingToTemporary
5988 ? diag::err_lvalue_reference_bind_to_temporary
5989 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005990 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005991 << DestType.getNonReferenceType()
5992 << Args[0]->getType()
5993 << Args[0]->getSourceRange();
5994 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005995
Douglas Gregor20093b42009-12-09 23:02:17 +00005996 case FK_RValueReferenceBindingToLValue:
5997 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005998 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005999 << Args[0]->getSourceRange();
6000 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006001
Douglas Gregor20093b42009-12-09 23:02:17 +00006002 case FK_ReferenceInitDropsQualifiers:
6003 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6004 << DestType.getNonReferenceType()
6005 << Args[0]->getType()
6006 << Args[0]->getSourceRange();
6007 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006008
Douglas Gregor20093b42009-12-09 23:02:17 +00006009 case FK_ReferenceInitFailed:
6010 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6011 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006012 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006013 << Args[0]->getType()
6014 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006015 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006016 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006017
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006018 case FK_ConversionFailed: {
6019 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006020 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006021 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006022 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006023 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006024 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006025 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006026 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6027 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006028 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006029 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006030 }
John Wiegley429bb272011-04-08 18:41:53 +00006031
6032 case FK_ConversionFromPropertyFailed:
6033 // No-op. This error has already been reported.
6034 break;
6035
Douglas Gregord87b61f2009-12-10 17:56:55 +00006036 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006037 SourceRange R;
6038
6039 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006040 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006041 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006042 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006043 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006044
Douglas Gregor19311e72010-09-08 21:40:08 +00006045 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6046 if (Kind.isCStyleOrFunctionalCast())
6047 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6048 << R;
6049 else
6050 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6051 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006052 break;
6053 }
6054
6055 case FK_ReferenceBindingToInitList:
6056 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6057 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6058 break;
6059
6060 case FK_InitListBadDestinationType:
6061 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6062 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6063 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006064
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006065 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006066 case FK_ConstructorOverloadFailed: {
6067 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006068 if (Args.size())
6069 ArgsRange = SourceRange(Args.front()->getLocStart(),
6070 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006071
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006072 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006073 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006074 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006075 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006076 }
6077
Douglas Gregor51c56d62009-12-14 20:49:26 +00006078 // FIXME: Using "DestType" for the entity we're printing is probably
6079 // bad.
6080 switch (FailedOverloadResult) {
6081 case OR_Ambiguous:
6082 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6083 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006084 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006085 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006086
Douglas Gregor51c56d62009-12-14 20:49:26 +00006087 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006088 if (Kind.getKind() == InitializationKind::IK_Default &&
6089 (Entity.getKind() == InitializedEntity::EK_Base ||
6090 Entity.getKind() == InitializedEntity::EK_Member) &&
6091 isa<CXXConstructorDecl>(S.CurContext)) {
6092 // This is implicit default initialization of a member or
6093 // base within a constructor. If no viable function was
6094 // found, notify the user that she needs to explicitly
6095 // initialize this base/member.
6096 CXXConstructorDecl *Constructor
6097 = cast<CXXConstructorDecl>(S.CurContext);
6098 if (Entity.getKind() == InitializedEntity::EK_Base) {
6099 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006100 << (Constructor->getInheritedConstructor() ? 2 :
6101 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006102 << S.Context.getTypeDeclType(Constructor->getParent())
6103 << /*base=*/0
6104 << Entity.getType();
6105
6106 RecordDecl *BaseDecl
6107 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6108 ->getDecl();
6109 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6110 << S.Context.getTagDeclType(BaseDecl);
6111 } else {
6112 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006113 << (Constructor->getInheritedConstructor() ? 2 :
6114 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006115 << S.Context.getTypeDeclType(Constructor->getParent())
6116 << /*member=*/1
6117 << Entity.getName();
6118 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6119
6120 if (const RecordType *Record
6121 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006122 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006123 diag::note_previous_decl)
6124 << S.Context.getTagDeclType(Record->getDecl());
6125 }
6126 break;
6127 }
6128
Douglas Gregor51c56d62009-12-14 20:49:26 +00006129 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6130 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006131 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006132 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006133
Douglas Gregor51c56d62009-12-14 20:49:26 +00006134 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006135 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006136 OverloadingResult Ovl
6137 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006138 if (Ovl != OR_Deleted) {
6139 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6140 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006141 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006142 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006143 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006144
6145 // If this is a defaulted or implicitly-declared function, then
6146 // it was implicitly deleted. Make it clear that the deletion was
6147 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006148 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006149 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006150 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006151 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006152 else
6153 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6154 << true << DestType << ArgsRange;
6155
6156 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006157 break;
6158 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006159
Douglas Gregor51c56d62009-12-14 20:49:26 +00006160 case OR_Success:
6161 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006162 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006163 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006164 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006165
Douglas Gregor99a2e602009-12-16 01:38:02 +00006166 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006167 if (Entity.getKind() == InitializedEntity::EK_Member &&
6168 isa<CXXConstructorDecl>(S.CurContext)) {
6169 // This is implicit default-initialization of a const member in
6170 // a constructor. Complain that it needs to be explicitly
6171 // initialized.
6172 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6173 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006174 << (Constructor->getInheritedConstructor() ? 2 :
6175 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006176 << S.Context.getTypeDeclType(Constructor->getParent())
6177 << /*const=*/1
6178 << Entity.getName();
6179 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6180 << Entity.getName();
6181 } else {
6182 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6183 << DestType << (bool)DestType->getAs<RecordType>();
6184 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006185 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006186
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006187 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006188 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006189 diag::err_init_incomplete_type);
6190 break;
6191
Sebastian Redl14b0c192011-09-24 17:48:00 +00006192 case FK_ListInitializationFailed: {
6193 // Run the init list checker again to emit diagnostics.
6194 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6195 QualType DestType = Entity.getType();
6196 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00006197 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00006198 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00006199 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006200 assert(DiagnoseInitList.HadError() &&
6201 "Inconsistent init list check result.");
6202 break;
6203 }
John McCall5acb0c92011-10-17 18:40:02 +00006204
6205 case FK_PlaceholderType: {
6206 // FIXME: Already diagnosed!
6207 break;
6208 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006209
6210 case FK_InitListElementCopyFailure: {
6211 // Try to perform all copies again.
6212 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6213 unsigned NumInits = InitList->getNumInits();
6214 QualType DestType = Entity.getType();
6215 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006216 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006217 (void)Success;
6218 assert(Success && "Where did the std::initializer_list go?");
6219 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6220 S.Context.getConstantArrayType(E,
6221 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6222 NumInits),
6223 ArrayType::Normal, 0));
6224 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6225 0, HiddenArray);
6226 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6227 // where the init list type is wrong, e.g.
6228 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6229 // FIXME: Emit a note if we hit the limit?
6230 int ErrorCount = 0;
6231 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6232 Element.setElementIndex(i);
6233 ExprResult Init = S.Owned(InitList->getInit(i));
6234 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6235 .isInvalid())
6236 ++ErrorCount;
6237 }
6238 break;
6239 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006240
6241 case FK_ExplicitConstructor: {
6242 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6243 << Args[0]->getSourceRange();
6244 OverloadCandidateSet::iterator Best;
6245 OverloadingResult Ovl
6246 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006247 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006248 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6249 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6250 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6251 break;
6252 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006253 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006254
Douglas Gregora41a8c52010-04-22 00:20:18 +00006255 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006256 return true;
6257}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006258
Chris Lattner5f9e2722011-07-23 10:55:15 +00006259void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006260 switch (SequenceKind) {
6261 case FailedSequence: {
6262 OS << "Failed sequence: ";
6263 switch (Failure) {
6264 case FK_TooManyInitsForReference:
6265 OS << "too many initializers for reference";
6266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006267
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006268 case FK_ArrayNeedsInitList:
6269 OS << "array requires initializer list";
6270 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006271
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006272 case FK_ArrayNeedsInitListOrStringLiteral:
6273 OS << "array requires initializer list or string literal";
6274 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006275
Hans Wennborg0ff50742013-05-15 11:03:04 +00006276 case FK_ArrayNeedsInitListOrWideStringLiteral:
6277 OS << "array requires initializer list or wide string literal";
6278 break;
6279
6280 case FK_NarrowStringIntoWideCharArray:
6281 OS << "narrow string into wide char array";
6282 break;
6283
6284 case FK_WideStringIntoCharArray:
6285 OS << "wide string into char array";
6286 break;
6287
6288 case FK_IncompatWideStringIntoWideChar:
6289 OS << "incompatible wide string into wide char array";
6290 break;
6291
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006292 case FK_ArrayTypeMismatch:
6293 OS << "array type mismatch";
6294 break;
6295
6296 case FK_NonConstantArrayInit:
6297 OS << "non-constant array initializer";
6298 break;
6299
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006300 case FK_AddressOfOverloadFailed:
6301 OS << "address of overloaded function failed";
6302 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006303
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006304 case FK_ReferenceInitOverloadFailed:
6305 OS << "overload resolution for reference initialization failed";
6306 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006307
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006308 case FK_NonConstLValueReferenceBindingToTemporary:
6309 OS << "non-const lvalue reference bound to temporary";
6310 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006311
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006312 case FK_NonConstLValueReferenceBindingToUnrelated:
6313 OS << "non-const lvalue reference bound to unrelated type";
6314 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006315
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006316 case FK_RValueReferenceBindingToLValue:
6317 OS << "rvalue reference bound to an lvalue";
6318 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006319
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006320 case FK_ReferenceInitDropsQualifiers:
6321 OS << "reference initialization drops qualifiers";
6322 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006323
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006324 case FK_ReferenceInitFailed:
6325 OS << "reference initialization failed";
6326 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006327
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006328 case FK_ConversionFailed:
6329 OS << "conversion failed";
6330 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006331
John Wiegley429bb272011-04-08 18:41:53 +00006332 case FK_ConversionFromPropertyFailed:
6333 OS << "conversion from property failed";
6334 break;
6335
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006336 case FK_TooManyInitsForScalar:
6337 OS << "too many initializers for scalar";
6338 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006339
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006340 case FK_ReferenceBindingToInitList:
6341 OS << "referencing binding to initializer list";
6342 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006343
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006344 case FK_InitListBadDestinationType:
6345 OS << "initializer list for non-aggregate, non-scalar type";
6346 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006347
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006348 case FK_UserConversionOverloadFailed:
6349 OS << "overloading failed for user-defined conversion";
6350 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006351
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006352 case FK_ConstructorOverloadFailed:
6353 OS << "constructor overloading failed";
6354 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006355
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006356 case FK_DefaultInitOfConst:
6357 OS << "default initialization of a const variable";
6358 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006359
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006360 case FK_Incomplete:
6361 OS << "initialization of incomplete type";
6362 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006363
6364 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006365 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006366 break;
6367
John McCall73076432012-01-05 00:13:19 +00006368 case FK_VariableLengthArrayHasInitializer:
6369 OS << "variable length array has an initializer";
6370 break;
6371
John McCall5acb0c92011-10-17 18:40:02 +00006372 case FK_PlaceholderType:
6373 OS << "initializer expression isn't contextually valid";
6374 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006375
6376 case FK_ListConstructorOverloadFailed:
6377 OS << "list constructor overloading failed";
6378 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006379
6380 case FK_InitListElementCopyFailure:
6381 OS << "copy construction of initializer list element failed";
6382 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006383
6384 case FK_ExplicitConstructor:
6385 OS << "list copy initialization chose explicit constructor";
6386 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006387 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006388 OS << '\n';
6389 return;
6390 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006391
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006392 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006393 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006394 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006395
Sebastian Redl7491c492011-06-05 13:59:11 +00006396 case NormalSequence:
6397 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006398 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006400
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006401 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6402 if (S != step_begin()) {
6403 OS << " -> ";
6404 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006405
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006406 switch (S->Kind) {
6407 case SK_ResolveAddressOfOverloadedFunction:
6408 OS << "resolve address of overloaded function";
6409 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006410
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006411 case SK_CastDerivedToBaseRValue:
6412 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6413 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006414
Sebastian Redl906082e2010-07-20 04:20:21 +00006415 case SK_CastDerivedToBaseXValue:
6416 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6417 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006418
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006419 case SK_CastDerivedToBaseLValue:
6420 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6421 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006422
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006423 case SK_BindReference:
6424 OS << "bind reference to lvalue";
6425 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006426
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006427 case SK_BindReferenceToTemporary:
6428 OS << "bind reference to a temporary";
6429 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006430
Douglas Gregor523d46a2010-04-18 07:40:54 +00006431 case SK_ExtraneousCopyToTemporary:
6432 OS << "extraneous C++03 copy to temporary";
6433 break;
6434
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006435 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006436 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006437 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006438
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006439 case SK_QualificationConversionRValue:
6440 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006441 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006442
Sebastian Redl906082e2010-07-20 04:20:21 +00006443 case SK_QualificationConversionXValue:
6444 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006445 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006446
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006447 case SK_QualificationConversionLValue:
6448 OS << "qualification conversion (lvalue)";
6449 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006450
Jordan Rose1fd1e282013-04-11 00:58:58 +00006451 case SK_LValueToRValue:
6452 OS << "load (lvalue to rvalue)";
6453 break;
6454
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006455 case SK_ConversionSequence:
6456 OS << "implicit conversion sequence (";
6457 S->ICS->DebugPrint(); // FIXME: use OS
6458 OS << ")";
6459 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006460
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006461 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006462 OS << "list aggregate initialization";
6463 break;
6464
6465 case SK_ListConstructorCall:
6466 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006467 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006468
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006469 case SK_UnwrapInitList:
6470 OS << "unwrap reference initializer list";
6471 break;
6472
6473 case SK_RewrapInitList:
6474 OS << "rewrap reference initializer list";
6475 break;
6476
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006477 case SK_ConstructorInitialization:
6478 OS << "constructor initialization";
6479 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006480
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006481 case SK_ZeroInitialization:
6482 OS << "zero initialization";
6483 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006484
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006485 case SK_CAssignment:
6486 OS << "C assignment";
6487 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006488
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006489 case SK_StringInit:
6490 OS << "string initialization";
6491 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006492
6493 case SK_ObjCObjectConversion:
6494 OS << "Objective-C object conversion";
6495 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006496
6497 case SK_ArrayInit:
6498 OS << "array initialization";
6499 break;
John McCallf85e1932011-06-15 23:02:42 +00006500
Richard Smith0f163e92012-02-15 22:38:09 +00006501 case SK_ParenthesizedArrayInit:
6502 OS << "parenthesized array initialization";
6503 break;
6504
John McCallf85e1932011-06-15 23:02:42 +00006505 case SK_PassByIndirectCopyRestore:
6506 OS << "pass by indirect copy and restore";
6507 break;
6508
6509 case SK_PassByIndirectRestore:
6510 OS << "pass by indirect restore";
6511 break;
6512
6513 case SK_ProduceObjCObject:
6514 OS << "Objective-C object retension";
6515 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006516
6517 case SK_StdInitializerList:
6518 OS << "std::initializer_list from initializer list";
6519 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006520
Guy Benyei21f18c42013-02-07 10:55:47 +00006521 case SK_OCLSamplerInit:
6522 OS << "OpenCL sampler_t from integer constant";
6523 break;
6524
Guy Benyeie6b9d802013-01-20 12:31:11 +00006525 case SK_OCLZeroEvent:
6526 OS << "OpenCL event_t from zero";
6527 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006528 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006529
6530 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006531 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006532
6533 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006534}
6535
6536void InitializationSequence::dump() const {
6537 dump(llvm::errs());
6538}
6539
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006540static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6541 QualType EntityType,
6542 const Expr *PreInit,
6543 const Expr *PostInit) {
6544 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6545 return;
6546
6547 // A narrowing conversion can only appear as the final implicit conversion in
6548 // an initialization sequence.
6549 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6550 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6551 return;
6552
6553 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6554 const StandardConversionSequence *SCS = 0;
6555 switch (ICS.getKind()) {
6556 case ImplicitConversionSequence::StandardConversion:
6557 SCS = &ICS.Standard;
6558 break;
6559 case ImplicitConversionSequence::UserDefinedConversion:
6560 SCS = &ICS.UserDefined.After;
6561 break;
6562 case ImplicitConversionSequence::AmbiguousConversion:
6563 case ImplicitConversionSequence::EllipsisConversion:
6564 case ImplicitConversionSequence::BadConversion:
6565 return;
6566 }
6567
6568 // Determine the type prior to the narrowing conversion. If a conversion
6569 // operator was used, this may be different from both the type of the entity
6570 // and of the pre-initialization expression.
6571 QualType PreNarrowingType = PreInit->getType();
6572 if (Seq.step_begin() + 1 != Seq.step_end())
6573 PreNarrowingType = Seq.step_end()[-2].Type;
6574
6575 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6576 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006577 QualType ConstantType;
6578 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6579 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006580 case NK_Not_Narrowing:
6581 // No narrowing occurred.
6582 return;
6583
6584 case NK_Type_Narrowing:
6585 // This was a floating-to-integer conversion, which is always considered a
6586 // narrowing conversion even if the value is a constant and can be
6587 // represented exactly as an integer.
6588 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006589 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006590 diag::warn_init_list_type_narrowing
6591 : S.isSFINAEContext()?
6592 diag::err_init_list_type_narrowing_sfinae
6593 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006594 << PostInit->getSourceRange()
6595 << PreNarrowingType.getLocalUnqualifiedType()
6596 << EntityType.getLocalUnqualifiedType();
6597 break;
6598
6599 case NK_Constant_Narrowing:
6600 // A constant value was narrowed.
6601 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006602 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006603 diag::warn_init_list_constant_narrowing
6604 : S.isSFINAEContext()?
6605 diag::err_init_list_constant_narrowing_sfinae
6606 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006607 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006608 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006609 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006610 break;
6611
6612 case NK_Variable_Narrowing:
6613 // A variable's value may have been narrowed.
6614 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006615 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006616 diag::warn_init_list_variable_narrowing
6617 : S.isSFINAEContext()?
6618 diag::err_init_list_variable_narrowing_sfinae
6619 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006620 << PostInit->getSourceRange()
6621 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006622 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006623 break;
6624 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006625
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006626 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006627 llvm::raw_svector_ostream OS(StaticCast);
6628 OS << "static_cast<";
6629 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6630 // It's important to use the typedef's name if there is one so that the
6631 // fixit doesn't break code using types like int64_t.
6632 //
6633 // FIXME: This will break if the typedef requires qualification. But
6634 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006635 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006636 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006637 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006638 else {
6639 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6640 // with a broken cast.
6641 return;
6642 }
6643 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006644 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6645 << PostInit->getSourceRange()
6646 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006647 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006648 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006649}
6650
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006651//===----------------------------------------------------------------------===//
6652// Initialization helper functions
6653//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006654bool
6655Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6656 ExprResult Init) {
6657 if (Init.isInvalid())
6658 return false;
6659
6660 Expr *InitE = Init.get();
6661 assert(InitE && "No initialization expression");
6662
Douglas Gregor3c394c52012-07-31 22:15:04 +00006663 InitializationKind Kind
6664 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006665 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006666 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006667}
6668
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006669ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006670Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6671 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006672 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006673 bool TopLevelOfInitList,
6674 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006675 if (Init.isInvalid())
6676 return ExprError();
6677
John McCall15d7d122010-11-11 03:21:53 +00006678 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006679 assert(InitE && "No initialization expression?");
6680
6681 if (EqualLoc.isInvalid())
6682 EqualLoc = InitE->getLocStart();
6683
6684 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006685 EqualLoc,
6686 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006687 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006688 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006689
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006690 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006691
6692 if (!Result.isInvalid() && TopLevelOfInitList)
6693 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6694 InitE, Result.get());
6695
6696 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006697}