blob: 2e11bc98acbdb738bd517ff027fd2ff24e1e5049 [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);
Richard Smith6242a452013-05-31 02:56:17 +0000824
825 if (ElemType->isReferenceType())
826 return CheckReferenceType(Entity, IList, ElemType, Index,
827 StructuredList, StructuredIndex);
828
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000829 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000830 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
831 unsigned newIndex = 0;
832 unsigned newStructuredIndex = 0;
833 InitListExpr *newStructuredList
834 = getStructuredSubobjectInit(IList, Index, ElemType,
835 StructuredList, StructuredIndex,
836 SubInitList->getSourceRange());
837 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
838 newStructuredList, newStructuredIndex);
839 ++StructuredIndex;
840 ++Index;
841 return;
842 }
843 assert(SemaRef.getLangOpts().CPlusPlus &&
844 "non-aggregate records are only possible in C++");
845 // C++ initialization is handled later.
846 }
847
Richard Smith6242a452013-05-31 02:56:17 +0000848 if (ElemType->isScalarType())
John McCallfef8b342011-02-21 07:57:55 +0000849 return CheckScalarType(Entity, IList, ElemType, Index,
850 StructuredList, StructuredIndex);
Anders Carlssond28b4282009-08-27 17:18:13 +0000851
John McCallfef8b342011-02-21 07:57:55 +0000852 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
853 // arrayType can be incomplete if we're initializing a flexible
854 // array member. There's nothing we can do with the completed
855 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000856
Hans Wennborg0ff50742013-05-15 11:03:04 +0000857 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000858 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000859 CheckStringInit(expr, ElemType, arrayType, SemaRef);
860 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000861 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000862 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000863 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000864 }
John McCallfef8b342011-02-21 07:57:55 +0000865
866 // Fall through for subaggregate initialization.
867
David Blaikie4e4d0842012-03-11 07:00:24 +0000868 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000869 // C++ [dcl.init.aggr]p12:
870 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000871 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000872 // an initializer-list. If the initializer can initialize a
873 // member, the member is initialized. [...]
874
875 // FIXME: Better EqualLoc?
876 InitializationKind Kind =
877 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000878 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000879
880 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000881 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000882 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000883 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000884 if (Result.isInvalid())
885 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000886
Sebastian Redl14b0c192011-09-24 17:48:00 +0000887 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000888 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000889 }
John McCallfef8b342011-02-21 07:57:55 +0000890 ++Index;
891 return;
892 }
893
894 // Fall through for subaggregate initialization
895 } else {
896 // C99 6.7.8p13:
897 //
898 // The initializer for a structure or union object that has
899 // automatic storage duration shall be either an initializer
900 // list as described below, or a single expression that has
901 // compatible structure or union type. In the latter case, the
902 // initial value of the object, including unnamed members, is
903 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000904 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000905 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000906 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
907 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000908 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000909 if (ExprRes.isInvalid())
910 hadError = true;
911 else {
912 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000913 if (ExprRes.isInvalid())
914 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000915 }
916 UpdateStructuredListElement(StructuredList, StructuredIndex,
917 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000918 ++Index;
919 return;
920 }
John Wiegley429bb272011-04-08 18:41:53 +0000921 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000922 // Fall through for subaggregate initialization
923 }
924
925 // C++ [dcl.init.aggr]p12:
926 //
927 // [...] Otherwise, if the member is itself a non-empty
928 // subaggregate, brace elision is assumed and the initializer is
929 // considered for the initialization of the first member of
930 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000931 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000932 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000933 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
934 StructuredIndex);
935 ++StructuredIndex;
936 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000937 if (!VerifyOnly) {
938 // We cannot initialize this element, so let
939 // PerformCopyInitialization produce the appropriate diagnostic.
940 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
941 SemaRef.Owned(expr),
942 /*TopLevelOfInitList=*/true);
943 }
John McCallfef8b342011-02-21 07:57:55 +0000944 hadError = true;
945 ++Index;
946 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000947 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000948}
949
Eli Friedman0c706c22011-09-19 23:17:44 +0000950void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
951 InitListExpr *IList, QualType DeclType,
952 unsigned &Index,
953 InitListExpr *StructuredList,
954 unsigned &StructuredIndex) {
955 assert(Index == 0 && "Index in explicit init list must be zero");
956
957 // As an extension, clang supports complex initializers, which initialize
958 // a complex number component-wise. When an explicit initializer list for
959 // a complex number contains two two initializers, this extension kicks in:
960 // it exepcts the initializer list to contain two elements convertible to
961 // the element type of the complex type. The first element initializes
962 // the real part, and the second element intitializes the imaginary part.
963
964 if (IList->getNumInits() != 2)
965 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
966 StructuredIndex);
967
968 // This is an extension in C. (The builtin _Complex type does not exist
969 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000970 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000971 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
972 << IList->getSourceRange();
973
974 // Initialize the complex number.
975 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
976 InitializedEntity ElementEntity =
977 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
978
979 for (unsigned i = 0; i < 2; ++i) {
980 ElementEntity.setElementIndex(Index);
981 CheckSubElementType(ElementEntity, IList, elementType, Index,
982 StructuredList, StructuredIndex);
983 }
984}
985
986
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000987void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000988 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000989 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000990 InitListExpr *StructuredList,
991 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000992 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000993 if (!VerifyOnly)
994 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000995 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000996 diag::warn_cxx98_compat_empty_scalar_initializer :
997 diag::err_empty_scalar_initializer)
998 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000999 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +00001000 ++Index;
1001 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +00001002 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001003 }
John McCallb934c2d2010-11-11 00:46:36 +00001004
1005 Expr *expr = IList->getInit(Index);
1006 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001007 if (!VerifyOnly)
1008 SemaRef.Diag(SubIList->getLocStart(),
1009 diag::warn_many_braces_around_scalar_init)
1010 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001011
1012 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1013 StructuredIndex);
1014 return;
1015 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001016 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001017 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001018 diag::err_designator_for_scalar_init)
1019 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001020 hadError = true;
1021 ++Index;
1022 ++StructuredIndex;
1023 return;
1024 }
1025
Sebastian Redl14b0c192011-09-24 17:48:00 +00001026 if (VerifyOnly) {
1027 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1028 hadError = true;
1029 ++Index;
1030 return;
1031 }
1032
John McCallb934c2d2010-11-11 00:46:36 +00001033 ExprResult Result =
1034 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001035 SemaRef.Owned(expr),
1036 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001037
1038 Expr *ResultExpr = 0;
1039
1040 if (Result.isInvalid())
1041 hadError = true; // types weren't compatible.
1042 else {
1043 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001044
John McCallb934c2d2010-11-11 00:46:36 +00001045 if (ResultExpr != expr) {
1046 // The type was promoted, update initializer list.
1047 IList->setInit(Index, ResultExpr);
1048 }
1049 }
1050 if (hadError)
1051 ++StructuredIndex;
1052 else
1053 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1054 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001055}
1056
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001057void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1058 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001059 unsigned &Index,
1060 InitListExpr *StructuredList,
1061 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001062 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001063 // FIXME: It would be wonderful if we could point at the actual member. In
1064 // general, it would be useful to pass location information down the stack,
1065 // so that we know the location (or decl) of the "current object" being
1066 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001067 if (!VerifyOnly)
1068 SemaRef.Diag(IList->getLocStart(),
1069 diag::err_init_reference_member_uninitialized)
1070 << DeclType
1071 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001072 hadError = true;
1073 ++Index;
1074 ++StructuredIndex;
1075 return;
1076 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001077
1078 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001079 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001080 if (!VerifyOnly)
1081 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1082 << DeclType << IList->getSourceRange();
1083 hadError = true;
1084 ++Index;
1085 ++StructuredIndex;
1086 return;
1087 }
1088
1089 if (VerifyOnly) {
1090 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1091 hadError = true;
1092 ++Index;
1093 return;
1094 }
1095
1096 ExprResult Result =
1097 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1098 SemaRef.Owned(expr),
1099 /*TopLevelOfInitList=*/true);
1100
1101 if (Result.isInvalid())
1102 hadError = true;
1103
1104 expr = Result.takeAs<Expr>();
1105 IList->setInit(Index, expr);
1106
1107 if (hadError)
1108 ++StructuredIndex;
1109 else
1110 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1111 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001112}
1113
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001114void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001115 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001116 unsigned &Index,
1117 InitListExpr *StructuredList,
1118 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001119 const VectorType *VT = DeclType->getAs<VectorType>();
1120 unsigned maxElements = VT->getNumElements();
1121 unsigned numEltsInit = 0;
1122 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001123
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001124 if (Index >= IList->getNumInits()) {
1125 // Make sure the element type can be value-initialized.
1126 if (VerifyOnly)
1127 CheckValueInitializable(
1128 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1129 return;
1130 }
1131
David Blaikie4e4d0842012-03-11 07:00:24 +00001132 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001133 // If the initializing element is a vector, try to copy-initialize
1134 // instead of breaking it apart (which is doomed to failure anyway).
1135 Expr *Init = IList->getInit(Index);
1136 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001137 if (VerifyOnly) {
1138 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1139 hadError = true;
1140 ++Index;
1141 return;
1142 }
1143
John McCall20e047a2010-10-30 00:11:39 +00001144 ExprResult Result =
1145 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001146 SemaRef.Owned(Init),
1147 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001148
1149 Expr *ResultExpr = 0;
1150 if (Result.isInvalid())
1151 hadError = true; // types weren't compatible.
1152 else {
1153 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001154
John McCall20e047a2010-10-30 00:11:39 +00001155 if (ResultExpr != Init) {
1156 // The type was promoted, update initializer list.
1157 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001158 }
1159 }
John McCall20e047a2010-10-30 00:11:39 +00001160 if (hadError)
1161 ++StructuredIndex;
1162 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001163 UpdateStructuredListElement(StructuredList, StructuredIndex,
1164 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001165 ++Index;
1166 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001167 }
Mike Stump1eb44332009-09-09 15:08:12 +00001168
John McCall20e047a2010-10-30 00:11:39 +00001169 InitializedEntity ElementEntity =
1170 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001171
John McCall20e047a2010-10-30 00:11:39 +00001172 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1173 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001174 if (Index >= IList->getNumInits()) {
1175 if (VerifyOnly)
1176 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001177 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001178 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001179
John McCall20e047a2010-10-30 00:11:39 +00001180 ElementEntity.setElementIndex(Index);
1181 CheckSubElementType(ElementEntity, IList, elementType, Index,
1182 StructuredList, StructuredIndex);
1183 }
1184 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001185 }
John McCall20e047a2010-10-30 00:11:39 +00001186
1187 InitializedEntity ElementEntity =
1188 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001189
John McCall20e047a2010-10-30 00:11:39 +00001190 // OpenCL initializers allows vectors to be constructed from vectors.
1191 for (unsigned i = 0; i < maxElements; ++i) {
1192 // Don't attempt to go past the end of the init list
1193 if (Index >= IList->getNumInits())
1194 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001195
John McCall20e047a2010-10-30 00:11:39 +00001196 ElementEntity.setElementIndex(Index);
1197
1198 QualType IType = IList->getInit(Index)->getType();
1199 if (!IType->isVectorType()) {
1200 CheckSubElementType(ElementEntity, IList, elementType, Index,
1201 StructuredList, StructuredIndex);
1202 ++numEltsInit;
1203 } else {
1204 QualType VecType;
1205 const VectorType *IVT = IType->getAs<VectorType>();
1206 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001207
John McCall20e047a2010-10-30 00:11:39 +00001208 if (IType->isExtVectorType())
1209 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1210 else
1211 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001212 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001213 CheckSubElementType(ElementEntity, IList, VecType, Index,
1214 StructuredList, StructuredIndex);
1215 numEltsInit += numIElts;
1216 }
1217 }
1218
1219 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001220 if (numEltsInit != maxElements) {
1221 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001222 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001223 diag::err_vector_incorrect_num_initializers)
1224 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1225 hadError = true;
1226 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001227}
1228
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001229void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001230 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001231 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001232 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001233 unsigned &Index,
1234 InitListExpr *StructuredList,
1235 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001236 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1237
Steve Naroff0cca7492008-05-01 22:18:59 +00001238 // Check for the special-case of initializing an array with a string.
1239 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001240 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1241 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001242 // We place the string literal directly into the resulting
1243 // initializer list. This is the only place where the structure
1244 // of the structured initializer list doesn't match exactly,
1245 // because doing so would involve allocating one character
1246 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001247 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001248 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1249 UpdateStructuredListElement(StructuredList, StructuredIndex,
1250 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001251 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1252 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001253 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001254 return;
1255 }
1256 }
John McCallce6c9b72011-02-21 07:22:22 +00001257 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001258 // Check for VLAs; in standard C it would be possible to check this
1259 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1260 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001261 if (!VerifyOnly)
1262 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1263 diag::err_variable_object_no_init)
1264 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001265 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001266 ++Index;
1267 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001268 return;
1269 }
1270
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001272 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1273 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001274 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001275 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001276 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001277 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001278 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001279 maxElementsKnown = true;
1280 }
1281
John McCallce6c9b72011-02-21 07:22:22 +00001282 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001283 while (Index < IList->getNumInits()) {
1284 Expr *Init = IList->getInit(Index);
1285 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001286 // If we're not the subobject that matches up with the '{' for
1287 // the designator, we shouldn't be handling the
1288 // designator. Return immediately.
1289 if (!SubobjectIsDesignatorContext)
1290 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001291
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001292 // Handle this designated initializer. elementIndex will be
1293 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001294 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001295 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001296 StructuredList, StructuredIndex, true,
1297 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001298 hadError = true;
1299 continue;
1300 }
1301
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001302 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001303 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001304 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001305 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001306 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001307
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001308 // If the array is of incomplete type, keep track of the number of
1309 // elements in the initializer.
1310 if (!maxElementsKnown && elementIndex > maxElements)
1311 maxElements = elementIndex;
1312
Douglas Gregor05c13a32009-01-22 00:58:24 +00001313 continue;
1314 }
1315
1316 // If we know the maximum number of elements, and we've already
1317 // hit it, stop consuming elements in the initializer list.
1318 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001319 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001320
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001321 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001322 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001323 Entity);
1324 // Check this element.
1325 CheckSubElementType(ElementEntity, IList, elementType, Index,
1326 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001327 ++elementIndex;
1328
1329 // If the array is of incomplete type, keep track of the number of
1330 // elements in the initializer.
1331 if (!maxElementsKnown && elementIndex > maxElements)
1332 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001333 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001334 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001335 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001336 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001337 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001338 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001339 // Sizing an array implicitly to zero is not allowed by ISO C,
1340 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001341 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001342 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001343 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001344
Mike Stump1eb44332009-09-09 15:08:12 +00001345 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001346 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001347 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001348 if (!hadError && VerifyOnly) {
1349 // Check if there are any members of the array that get value-initialized.
1350 // If so, check if doing that is possible.
1351 // FIXME: This needs to detect holes left by designated initializers too.
1352 if (maxElementsKnown && elementIndex < maxElements)
1353 CheckValueInitializable(InitializedEntity::InitializeElement(
1354 SemaRef.Context, 0, Entity));
1355 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001356}
1357
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001358bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1359 Expr *InitExpr,
1360 FieldDecl *Field,
1361 bool TopLevelObject) {
1362 // Handle GNU flexible array initializers.
1363 unsigned FlexArrayDiag;
1364 if (isa<InitListExpr>(InitExpr) &&
1365 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1366 // Empty flexible array init always allowed as an extension
1367 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001368 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001369 // Disallow flexible array init in C++; it is not required for gcc
1370 // compatibility, and it needs work to IRGen correctly in general.
1371 FlexArrayDiag = diag::err_flexible_array_init;
1372 } else if (!TopLevelObject) {
1373 // Disallow flexible array init on non-top-level object
1374 FlexArrayDiag = diag::err_flexible_array_init;
1375 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1376 // Disallow flexible array init on anything which is not a variable.
1377 FlexArrayDiag = diag::err_flexible_array_init;
1378 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1379 // Disallow flexible array init on local variables.
1380 FlexArrayDiag = diag::err_flexible_array_init;
1381 } else {
1382 // Allow other cases.
1383 FlexArrayDiag = diag::ext_flexible_array_init;
1384 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001385
1386 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001387 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001388 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001389 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001390 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1391 << Field;
1392 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001393
1394 return FlexArrayDiag != diag::ext_flexible_array_init;
1395}
1396
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001397void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001398 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001399 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001400 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001401 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001402 unsigned &Index,
1403 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001404 unsigned &StructuredIndex,
1405 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001406 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Eli Friedmanb85f7072008-05-19 19:16:24 +00001408 // If the record is invalid, some of it's members are invalid. To avoid
1409 // confusion, we forgo checking the intializer for the entire record.
1410 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001411 // Assume it was supposed to consume a single initializer.
1412 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001413 hadError = true;
1414 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001415 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001416
1417 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001418 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001419
1420 // If there's a default initializer, use it.
1421 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1422 if (VerifyOnly)
1423 return;
1424 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1425 Field != FieldEnd; ++Field) {
1426 if (Field->hasInClassInitializer()) {
1427 StructuredList->setInitializedFieldInUnion(*Field);
1428 // FIXME: Actually build a CXXDefaultInitExpr?
1429 return;
1430 }
1431 }
1432 }
1433
1434 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001435 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1436 Field != FieldEnd; ++Field) {
1437 if (Field->getDeclName()) {
1438 if (VerifyOnly)
1439 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001440 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001441 else
David Blaikie581deb32012-06-06 20:45:41 +00001442 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001443 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001444 }
1445 }
1446 return;
1447 }
1448
Douglas Gregor05c13a32009-01-22 00:58:24 +00001449 // If structDecl is a forward declaration, this loop won't do
1450 // anything except look at designated initializers; That's okay,
1451 // because an error should get printed out elsewhere. It might be
1452 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001453 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001454 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001455 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001456 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001457 while (Index < IList->getNumInits()) {
1458 Expr *Init = IList->getInit(Index);
1459
1460 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001461 // If we're not the subobject that matches up with the '{' for
1462 // the designator, we shouldn't be handling the
1463 // designator. Return immediately.
1464 if (!SubobjectIsDesignatorContext)
1465 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001466
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001467 // Handle this designated initializer. Field will be updated to
1468 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001469 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001470 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001471 StructuredList, StructuredIndex,
1472 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001473 hadError = true;
1474
Douglas Gregordfb5e592009-02-12 19:00:39 +00001475 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001476
1477 // Disable check for missing fields when designators are used.
1478 // This matches gcc behaviour.
1479 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001480 continue;
1481 }
1482
1483 if (Field == FieldEnd) {
1484 // We've run out of fields. We're done.
1485 break;
1486 }
1487
Douglas Gregordfb5e592009-02-12 19:00:39 +00001488 // We've already initialized a member of a union. We're done.
1489 if (InitializedSomething && DeclType->isUnionType())
1490 break;
1491
Douglas Gregor44b43212008-12-11 16:49:14 +00001492 // If we've hit the flexible array member at the end, we're done.
1493 if (Field->getType()->isIncompleteArrayType())
1494 break;
1495
Douglas Gregor0bb76892009-01-29 16:53:55 +00001496 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001497 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001498 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001499 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001500 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001501
Douglas Gregor54001c12011-06-29 21:51:31 +00001502 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001503 bool InvalidUse;
1504 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001505 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001506 else
David Blaikie581deb32012-06-06 20:45:41 +00001507 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001508 IList->getInit(Index)->getLocStart());
1509 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001510 ++Index;
1511 ++Field;
1512 hadError = true;
1513 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001514 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001515
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001516 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001517 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001518 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1519 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001520 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001521
Sebastian Redl14b0c192011-09-24 17:48:00 +00001522 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001523 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001524 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001525 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001526
1527 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001528 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001529
John McCall80639de2010-03-11 19:32:38 +00001530 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001531 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1532 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1533 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001534 // It is possible we have one or more unnamed bitfields remaining.
1535 // Find first (if any) named field and emit warning.
1536 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1537 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001538 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001539 SemaRef.Diag(IList->getSourceRange().getEnd(),
1540 diag::warn_missing_field_initializers) << it->getName();
1541 break;
1542 }
1543 }
1544 }
1545
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001546 // Check that any remaining fields can be value-initialized.
1547 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1548 !Field->getType()->isIncompleteArrayType()) {
1549 // FIXME: Should check for holes left by designated initializers too.
1550 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001551 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001552 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001553 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001554 }
1555 }
1556
Mike Stump1eb44332009-09-09 15:08:12 +00001557 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001558 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001559 return;
1560
David Blaikie581deb32012-06-06 20:45:41 +00001561 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001562 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001563 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001564 ++Index;
1565 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001566 }
1567
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001568 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001569 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001570
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001571 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001572 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001573 StructuredList, StructuredIndex);
1574 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001575 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001576 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001577}
Steve Naroff0cca7492008-05-01 22:18:59 +00001578
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001579/// \brief Expand a field designator that refers to a member of an
1580/// anonymous struct or union into a series of field designators that
1581/// refers to the field within the appropriate subobject.
1582///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001583static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001584 DesignatedInitExpr *DIE,
1585 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001586 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001587 typedef DesignatedInitExpr::Designator Designator;
1588
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001589 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001590 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001591 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1592 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1593 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001594 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001595 DIE->getDesignator(DesigIdx)->getDotLoc(),
1596 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1597 else
1598 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1599 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001600 assert(isa<FieldDecl>(*PI));
1601 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001602 }
1603
1604 // Expand the current designator into the set of replacement
1605 // designators, so we have a full subobject path down to where the
1606 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001607 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001608 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001609}
Mike Stump1eb44332009-09-09 15:08:12 +00001610
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001611/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001612/// corresponds to FieldName.
1613static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1614 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001615 if (!FieldName)
1616 return 0;
1617
Francois Picheta0e27f02010-12-22 03:46:10 +00001618 assert(AnonField->isAnonymousStructOrUnion());
1619 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001620 while (IndirectFieldDecl *IF =
1621 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001622 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001623 return IF;
1624 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001625 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001626 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001627}
1628
Sebastian Redl14b0c192011-09-24 17:48:00 +00001629static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1630 DesignatedInitExpr *DIE) {
1631 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1632 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1633 for (unsigned I = 0; I < NumIndexExprs; ++I)
1634 IndexExprs[I] = DIE->getSubExpr(I + 1);
1635 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001636 DIE->size(), IndexExprs,
1637 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001638 DIE->usesGNUSyntax(), DIE->getInit());
1639}
1640
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001641namespace {
1642
1643// Callback to only accept typo corrections that are for field members of
1644// the given struct or union.
1645class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1646 public:
1647 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1648 : Record(RD) {}
1649
1650 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1651 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1652 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1653 }
1654
1655 private:
1656 RecordDecl *Record;
1657};
1658
1659}
1660
Douglas Gregor05c13a32009-01-22 00:58:24 +00001661/// @brief Check the well-formedness of a C99 designated initializer.
1662///
1663/// Determines whether the designated initializer @p DIE, which
1664/// resides at the given @p Index within the initializer list @p
1665/// IList, is well-formed for a current object of type @p DeclType
1666/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001667/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001668/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001669///
1670/// @param IList The initializer list in which this designated
1671/// initializer occurs.
1672///
Douglas Gregor71199712009-04-15 04:56:10 +00001673/// @param DIE The designated initializer expression.
1674///
1675/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001676///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001677/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001678/// into which the designation in @p DIE should refer.
1679///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001680/// @param NextField If non-NULL and the first designator in @p DIE is
1681/// a field, this will be set to the field declaration corresponding
1682/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001683///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001684/// @param NextElementIndex If non-NULL and the first designator in @p
1685/// DIE is an array designator or GNU array-range designator, this
1686/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001687///
1688/// @param Index Index into @p IList where the designated initializer
1689/// @p DIE occurs.
1690///
Douglas Gregor4c678342009-01-28 21:54:33 +00001691/// @param StructuredList The initializer list expression that
1692/// describes all of the subobject initializers in the order they'll
1693/// actually be initialized.
1694///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001695/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001696bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001697InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001698 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001699 DesignatedInitExpr *DIE,
1700 unsigned DesigIdx,
1701 QualType &CurrentObjectType,
1702 RecordDecl::field_iterator *NextField,
1703 llvm::APSInt *NextElementIndex,
1704 unsigned &Index,
1705 InitListExpr *StructuredList,
1706 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001707 bool FinishSubobjectInit,
1708 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001709 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001710 // Check the actual initialization for the designated object type.
1711 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001712
1713 // Temporarily remove the designator expression from the
1714 // initializer list that the child calls see, so that we don't try
1715 // to re-process the designator.
1716 unsigned OldIndex = Index;
1717 IList->setInit(OldIndex, DIE->getInit());
1718
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001719 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001720 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001721
1722 // Restore the designated initializer expression in the syntactic
1723 // form of the initializer list.
1724 if (IList->getInit(OldIndex) != DIE->getInit())
1725 DIE->setInit(IList->getInit(OldIndex));
1726 IList->setInit(OldIndex, DIE);
1727
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001728 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001729 }
1730
Douglas Gregor71199712009-04-15 04:56:10 +00001731 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001732 bool IsFirstDesignator = (DesigIdx == 0);
1733 if (!VerifyOnly) {
1734 assert((IsFirstDesignator || StructuredList) &&
1735 "Need a non-designated initializer list to start from");
1736
1737 // Determine the structural initializer list that corresponds to the
1738 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001739 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001740 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1741 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001742 SourceRange(D->getLocStart(),
1743 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001744 assert(StructuredList && "Expected a structured initializer list");
1745 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001746
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001747 if (D->isFieldDesignator()) {
1748 // C99 6.7.8p7:
1749 //
1750 // If a designator has the form
1751 //
1752 // . identifier
1753 //
1754 // then the current object (defined below) shall have
1755 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001756 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001757 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001758 if (!RT) {
1759 SourceLocation Loc = D->getDotLoc();
1760 if (Loc.isInvalid())
1761 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001762 if (!VerifyOnly)
1763 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001764 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001765 ++Index;
1766 return true;
1767 }
1768
Douglas Gregor4c678342009-01-28 21:54:33 +00001769 // Note: we perform a linear search of the fields here, despite
1770 // the fact that we have a faster lookup method, because we always
1771 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001772 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001773 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001774 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001775 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001776 Field = RT->getDecl()->field_begin(),
1777 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001778 for (; Field != FieldEnd; ++Field) {
1779 if (Field->isUnnamedBitfield())
1780 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781
Francois Picheta0e27f02010-12-22 03:46:10 +00001782 // If we find a field representing an anonymous field, look in the
1783 // IndirectFieldDecl that follow for the designated initializer.
1784 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1785 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001786 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001787 // In verify mode, don't modify the original.
1788 if (VerifyOnly)
1789 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001790 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1791 D = DIE->getDesignator(DesigIdx);
1792 break;
1793 }
1794 }
David Blaikie581deb32012-06-06 20:45:41 +00001795 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001796 break;
1797 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001798 break;
1799
1800 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001801 }
1802
Douglas Gregor4c678342009-01-28 21:54:33 +00001803 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001804 if (VerifyOnly) {
1805 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001806 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001807 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001808
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001809 // There was no normal field in the struct with the designated
1810 // name. Perform another lookup for this name, which may find
1811 // something that we can't designate (e.g., a member function),
1812 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001813 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001814 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001815 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001816 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001817 // Name lookup didn't find anything. Determine whether this
1818 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001819 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001820 TypoCorrection Corrected = SemaRef.CorrectTypo(
1821 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001822 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001823 RT->getDecl());
1824 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001825 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001826 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001827 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001828 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001829 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001830 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001831 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001832 << FieldName << CurrentObjectType << CorrectedQuotedStr
1833 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001834 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001835 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001836 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001837 } else {
1838 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1839 << FieldName << CurrentObjectType;
1840 ++Index;
1841 return true;
1842 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001843 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001844
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001845 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001846 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001847 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001848 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001849 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001850 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001851 ++Index;
1852 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001853 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001854
Francois Picheta0e27f02010-12-22 03:46:10 +00001855 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001856 // The replacement field comes from typo correction; find it
1857 // in the list of fields.
1858 FieldIndex = 0;
1859 Field = RT->getDecl()->field_begin();
1860 for (; Field != FieldEnd; ++Field) {
1861 if (Field->isUnnamedBitfield())
1862 continue;
1863
David Blaikie581deb32012-06-06 20:45:41 +00001864 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001865 Field->getIdentifier() == ReplacementField->getIdentifier())
1866 break;
1867
1868 ++FieldIndex;
1869 }
1870 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001871 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001872
1873 // All of the fields of a union are located at the same place in
1874 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001875 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001876 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001877 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001878 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001879 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001880
Douglas Gregor54001c12011-06-29 21:51:31 +00001881 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001882 bool InvalidUse;
1883 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001884 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001885 else
David Blaikie581deb32012-06-06 20:45:41 +00001886 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001887 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001888 ++Index;
1889 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001890 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001891
Sebastian Redl14b0c192011-09-24 17:48:00 +00001892 if (!VerifyOnly) {
1893 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001894 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Sebastian Redl14b0c192011-09-24 17:48:00 +00001896 // Make sure that our non-designated initializer list has space
1897 // for a subobject corresponding to this field.
1898 if (FieldIndex >= StructuredList->getNumInits())
1899 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1900 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001901
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001902 // This designator names a flexible array member.
1903 if (Field->getType()->isIncompleteArrayType()) {
1904 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001905 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001906 // We can't designate an object within the flexible array
1907 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001908 if (!VerifyOnly) {
1909 DesignatedInitExpr::Designator *NextD
1910 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001911 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001912 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001913 << SourceRange(NextD->getLocStart(),
1914 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001915 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001916 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001917 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001918 Invalid = true;
1919 }
1920
Chris Lattner9046c222010-10-10 17:49:49 +00001921 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1922 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001923 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001924 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001925 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001926 diag::err_flexible_array_init_needs_braces)
1927 << DIE->getInit()->getSourceRange();
1928 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001929 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001930 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001931 Invalid = true;
1932 }
1933
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001934 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001935 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001936 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001937 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001938
1939 if (Invalid) {
1940 ++Index;
1941 return true;
1942 }
1943
1944 // Initialize the array.
1945 bool prevHadError = hadError;
1946 unsigned newStructuredIndex = FieldIndex;
1947 unsigned OldIndex = Index;
1948 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001949
1950 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001951 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001952 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001953 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001954
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001955 IList->setInit(OldIndex, DIE);
1956 if (hadError && !prevHadError) {
1957 ++Field;
1958 ++FieldIndex;
1959 if (NextField)
1960 *NextField = Field;
1961 StructuredIndex = FieldIndex;
1962 return true;
1963 }
1964 } else {
1965 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001966 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001967 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001968
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001969 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001970 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001971 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1972 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001973 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001974 true, false))
1975 return true;
1976 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001977
1978 // Find the position of the next field to be initialized in this
1979 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001980 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001981 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001982
1983 // If this the first designator, our caller will continue checking
1984 // the rest of this struct/class/union subobject.
1985 if (IsFirstDesignator) {
1986 if (NextField)
1987 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001988 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001989 return false;
1990 }
1991
Douglas Gregor34e79462009-01-28 23:36:17 +00001992 if (!FinishSubobjectInit)
1993 return false;
1994
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001995 // We've already initialized something in the union; we're done.
1996 if (RT->getDecl()->isUnion())
1997 return hadError;
1998
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001999 // Check the remaining fields within this class/struct/union subobject.
2000 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002001
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002002 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002003 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002004 return hadError && !prevHadError;
2005 }
2006
2007 // C99 6.7.8p6:
2008 //
2009 // If a designator has the form
2010 //
2011 // [ constant-expression ]
2012 //
2013 // then the current object (defined below) shall have array
2014 // type and the expression shall be an integer constant
2015 // expression. If the array is of unknown size, any
2016 // nonnegative value is valid.
2017 //
2018 // Additionally, cope with the GNU extension that permits
2019 // designators of the form
2020 //
2021 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002022 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002023 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002024 if (!VerifyOnly)
2025 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2026 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002027 ++Index;
2028 return true;
2029 }
2030
2031 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00002032 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2033 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002034 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002035 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002036 DesignatedEndIndex = DesignatedStartIndex;
2037 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002038 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002039
Mike Stump1eb44332009-09-09 15:08:12 +00002040 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002041 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002042 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002043 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002044 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002045
Chris Lattnere0fd8322011-02-19 22:28:58 +00002046 // Codegen can't handle evaluating array range designators that have side
2047 // effects, because we replicate the AST value for each initialized element.
2048 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2049 // elements with something that has a side effect, so codegen can emit an
2050 // "error unsupported" error instead of miscompiling the app.
2051 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002052 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002053 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002054 }
2055
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002056 if (isa<ConstantArrayType>(AT)) {
2057 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002058 DesignatedStartIndex
2059 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002060 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002061 DesignatedEndIndex
2062 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002063 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2064 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002065 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002066 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002067 diag::err_array_designator_too_large)
2068 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2069 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002070 ++Index;
2071 return true;
2072 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002073 } else {
2074 // Make sure the bit-widths and signedness match.
2075 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002076 DesignatedEndIndex
2077 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002078 else if (DesignatedStartIndex.getBitWidth() <
2079 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002080 DesignatedStartIndex
2081 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002082 DesignatedStartIndex.setIsUnsigned(true);
2083 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002084 }
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Douglas Gregor4c678342009-01-28 21:54:33 +00002086 // Make sure that our non-designated initializer list has space
2087 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002088 if (!VerifyOnly &&
2089 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002090 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002091 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002092
Douglas Gregor34e79462009-01-28 23:36:17 +00002093 // Repeatedly perform subobject initializations in the range
2094 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002095
Douglas Gregor34e79462009-01-28 23:36:17 +00002096 // Move to the next designator
2097 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2098 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002099
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002100 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002101 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002102
Douglas Gregor34e79462009-01-28 23:36:17 +00002103 while (DesignatedStartIndex <= DesignatedEndIndex) {
2104 // Recurse to check later designated subobjects.
2105 QualType ElementType = AT->getElementType();
2106 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002107
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002108 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002109 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2110 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002111 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002112 (DesignatedStartIndex == DesignatedEndIndex),
2113 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002114 return true;
2115
2116 // Move to the next index in the array that we'll be initializing.
2117 ++DesignatedStartIndex;
2118 ElementIndex = DesignatedStartIndex.getZExtValue();
2119 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002120
2121 // If this the first designator, our caller will continue checking
2122 // the rest of this array subobject.
2123 if (IsFirstDesignator) {
2124 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002125 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002126 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002127 return false;
2128 }
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Douglas Gregor34e79462009-01-28 23:36:17 +00002130 if (!FinishSubobjectInit)
2131 return false;
2132
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002133 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002134 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002135 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002136 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002137 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002138 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002139}
2140
Douglas Gregor4c678342009-01-28 21:54:33 +00002141// Get the structured initializer list for a subobject of type
2142// @p CurrentObjectType.
2143InitListExpr *
2144InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2145 QualType CurrentObjectType,
2146 InitListExpr *StructuredList,
2147 unsigned StructuredIndex,
2148 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002149 if (VerifyOnly)
2150 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002151 Expr *ExistingInit = 0;
2152 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002153 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002154 else if (StructuredIndex < StructuredList->getNumInits())
2155 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Douglas Gregor4c678342009-01-28 21:54:33 +00002157 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2158 return Result;
2159
2160 if (ExistingInit) {
2161 // We are creating an initializer list that initializes the
2162 // subobjects of the current object, but there was already an
2163 // initialization that completely initialized the current
2164 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002165 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002166 // struct X { int a, b; };
2167 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002168 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002169 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2170 // designated initializer re-initializes the whole
2171 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002172 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002173 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002174 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002175 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002176 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002177 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002178 << ExistingInit->getSourceRange();
2179 }
2180
Mike Stump1eb44332009-09-09 15:08:12 +00002181 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002182 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002183 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002184 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002185
Eli Friedman5c89c392012-02-23 02:25:10 +00002186 QualType ResultType = CurrentObjectType;
2187 if (!ResultType->isArrayType())
2188 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2189 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002190
Douglas Gregorfa219202009-03-20 23:58:33 +00002191 // Pre-allocate storage for the structured initializer list.
2192 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002193 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002194 bool GotNumInits = false;
2195 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002196 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002197 GotNumInits = true;
2198 } else if (Index < IList->getNumInits()) {
2199 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002200 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002201 GotNumInits = true;
2202 }
Douglas Gregor08457732009-03-21 18:13:52 +00002203 }
2204
Mike Stump1eb44332009-09-09 15:08:12 +00002205 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002206 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2207 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2208 NumElements = CAType->getSize().getZExtValue();
2209 // Simple heuristic so that we don't allocate a very large
2210 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002211 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002212 NumElements = 0;
2213 }
John McCall183700f2009-09-21 23:43:11 +00002214 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002215 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002216 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002217 RecordDecl *RDecl = RType->getDecl();
2218 if (RDecl->isUnion())
2219 NumElements = 1;
2220 else
Mike Stump1eb44332009-09-09 15:08:12 +00002221 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002222 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002223 }
2224
Ted Kremenek709210f2010-04-13 23:39:13 +00002225 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002226
Douglas Gregor4c678342009-01-28 21:54:33 +00002227 // Link this new initializer list into the structured initializer
2228 // lists.
2229 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002230 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002231 else {
2232 Result->setSyntacticForm(IList);
2233 SyntacticToSemantic[IList] = Result;
2234 }
2235
2236 return Result;
2237}
2238
2239/// Update the initializer at index @p StructuredIndex within the
2240/// structured initializer list to the value @p expr.
2241void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2242 unsigned &StructuredIndex,
2243 Expr *expr) {
2244 // No structured initializer list to update
2245 if (!StructuredList)
2246 return;
2247
Ted Kremenek709210f2010-04-13 23:39:13 +00002248 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2249 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002250 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002251 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002252 diag::warn_initializer_overrides)
2253 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002254 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002255 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002256 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002257 << PrevInit->getSourceRange();
2258 }
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Douglas Gregor4c678342009-01-28 21:54:33 +00002260 ++StructuredIndex;
2261}
2262
Douglas Gregor05c13a32009-01-22 00:58:24 +00002263/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002264/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002265/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002266/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002267/// failure. Returns the index expression, possibly with an implicit cast
2268/// added, on success. If everything went okay, Value will receive the
2269/// value of the constant expression.
2270static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002271CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002272 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002273
2274 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002275 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2276 if (Result.isInvalid())
2277 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002278
Chris Lattner3bf68932009-04-25 21:59:05 +00002279 if (Value.isSigned() && Value.isNegative())
2280 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002281 << Value.toString(10) << Index->getSourceRange();
2282
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002283 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002284 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002285}
2286
John McCall60d7b3a2010-08-24 06:29:42 +00002287ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002288 SourceLocation Loc,
2289 bool GNUSyntax,
2290 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002291 typedef DesignatedInitExpr::Designator ASTDesignator;
2292
2293 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002294 SmallVector<ASTDesignator, 32> Designators;
2295 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002296
2297 // Build designators and check array designator expressions.
2298 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2299 const Designator &D = Desig.getDesignator(Idx);
2300 switch (D.getKind()) {
2301 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002302 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002303 D.getFieldLoc()));
2304 break;
2305
2306 case Designator::ArrayDesignator: {
2307 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2308 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002309 if (!Index->isTypeDependent() && !Index->isValueDependent())
2310 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2311 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002312 Invalid = true;
2313 else {
2314 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002315 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002316 D.getRBracketLoc()));
2317 InitExpressions.push_back(Index);
2318 }
2319 break;
2320 }
2321
2322 case Designator::ArrayRangeDesignator: {
2323 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2324 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2325 llvm::APSInt StartValue;
2326 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002327 bool StartDependent = StartIndex->isTypeDependent() ||
2328 StartIndex->isValueDependent();
2329 bool EndDependent = EndIndex->isTypeDependent() ||
2330 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002331 if (!StartDependent)
2332 StartIndex =
2333 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2334 if (!EndDependent)
2335 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2336
2337 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002338 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002339 else {
2340 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002341 if (StartDependent || EndDependent) {
2342 // Nothing to compute.
2343 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002344 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002345 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002346 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002347
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002348 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002349 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002350 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002351 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2352 Invalid = true;
2353 } else {
2354 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002355 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002356 D.getEllipsisLoc(),
2357 D.getRBracketLoc()));
2358 InitExpressions.push_back(StartIndex);
2359 InitExpressions.push_back(EndIndex);
2360 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002361 }
2362 break;
2363 }
2364 }
2365 }
2366
2367 if (Invalid || Init.isInvalid())
2368 return ExprError();
2369
2370 // Clear out the expressions within the designation.
2371 Desig.ClearExprs(*this);
2372
2373 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002374 = DesignatedInitExpr::Create(Context,
2375 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002376 InitExpressions, Loc, GNUSyntax,
2377 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002378
David Blaikie4e4d0842012-03-11 07:00:24 +00002379 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002380 Diag(DIE->getLocStart(), diag::ext_designated_init)
2381 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002382
Douglas Gregor05c13a32009-01-22 00:58:24 +00002383 return Owned(DIE);
2384}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002385
Douglas Gregor20093b42009-12-09 23:02:17 +00002386//===----------------------------------------------------------------------===//
2387// Initialization entity
2388//===----------------------------------------------------------------------===//
2389
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002390InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002391 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002392 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002393{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002394 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2395 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002396 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002397 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002398 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002399 Type = VT->getElementType();
2400 } else {
2401 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2402 assert(CT && "Unexpected type");
2403 Kind = EK_ComplexElement;
2404 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002405 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002406}
2407
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002408InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002409 CXXBaseSpecifier *Base,
2410 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002411{
2412 InitializedEntity Result;
2413 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002414 Result.Base = reinterpret_cast<uintptr_t>(Base);
2415 if (IsInheritedVirtualBase)
2416 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002417
Douglas Gregord6542d82009-12-22 15:35:07 +00002418 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002419 return Result;
2420}
2421
Douglas Gregor99a2e602009-12-16 01:38:02 +00002422DeclarationName InitializedEntity::getName() const {
2423 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002424 case EK_Parameter: {
2425 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2426 return (D ? D->getDeclName() : DeclarationName());
2427 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002428
2429 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002430 case EK_Member:
2431 return VariableOrMember->getDeclName();
2432
Douglas Gregor47736542012-02-15 16:57:26 +00002433 case EK_LambdaCapture:
2434 return Capture.Var->getDeclName();
2435
Douglas Gregor99a2e602009-12-16 01:38:02 +00002436 case EK_Result:
2437 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002438 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002439 case EK_Temporary:
2440 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002441 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002442 case EK_ArrayElement:
2443 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002444 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002445 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002446 case EK_CompoundLiteralInit:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002447 return DeclarationName();
2448 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002449
David Blaikie7530c032012-01-17 06:56:22 +00002450 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002451}
2452
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002453DeclaratorDecl *InitializedEntity::getDecl() const {
2454 switch (getKind()) {
2455 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002456 case EK_Member:
2457 return VariableOrMember;
2458
John McCallf85e1932011-06-15 23:02:42 +00002459 case EK_Parameter:
2460 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2461
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002462 case EK_Result:
2463 case EK_Exception:
2464 case EK_New:
2465 case EK_Temporary:
2466 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002467 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002468 case EK_ArrayElement:
2469 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002470 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002471 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002472 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002473 case EK_CompoundLiteralInit:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002474 return 0;
2475 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002476
David Blaikie7530c032012-01-17 06:56:22 +00002477 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002478}
2479
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002480bool InitializedEntity::allowsNRVO() const {
2481 switch (getKind()) {
2482 case EK_Result:
2483 case EK_Exception:
2484 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002485
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002486 case EK_Variable:
2487 case EK_Parameter:
2488 case EK_Member:
2489 case EK_New:
2490 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002491 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002492 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002493 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002494 case EK_ArrayElement:
2495 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002496 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002497 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002498 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002499 break;
2500 }
2501
2502 return false;
2503}
2504
Douglas Gregor20093b42009-12-09 23:02:17 +00002505//===----------------------------------------------------------------------===//
2506// Initialization sequence
2507//===----------------------------------------------------------------------===//
2508
2509void InitializationSequence::Step::Destroy() {
2510 switch (Kind) {
2511 case SK_ResolveAddressOfOverloadedFunction:
2512 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002513 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002514 case SK_CastDerivedToBaseLValue:
2515 case SK_BindReference:
2516 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002517 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002518 case SK_UserConversion:
2519 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002520 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002521 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002522 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002523 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002524 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002525 case SK_UnwrapInitList:
2526 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002527 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002528 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002529 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002530 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002531 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002532 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002533 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002534 case SK_PassByIndirectCopyRestore:
2535 case SK_PassByIndirectRestore:
2536 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002537 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002538 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002539 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002540 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541
Douglas Gregor20093b42009-12-09 23:02:17 +00002542 case SK_ConversionSequence:
2543 delete ICS;
2544 }
2545}
2546
Douglas Gregorb70cf442010-03-26 20:14:36 +00002547bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002548 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002549}
2550
2551bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002552 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002553 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002554
Douglas Gregorb70cf442010-03-26 20:14:36 +00002555 switch (getFailureKind()) {
2556 case FK_TooManyInitsForReference:
2557 case FK_ArrayNeedsInitList:
2558 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002559 case FK_ArrayNeedsInitListOrWideStringLiteral:
2560 case FK_NarrowStringIntoWideCharArray:
2561 case FK_WideStringIntoCharArray:
2562 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002563 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2564 case FK_NonConstLValueReferenceBindingToTemporary:
2565 case FK_NonConstLValueReferenceBindingToUnrelated:
2566 case FK_RValueReferenceBindingToLValue:
2567 case FK_ReferenceInitDropsQualifiers:
2568 case FK_ReferenceInitFailed:
2569 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002570 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002571 case FK_TooManyInitsForScalar:
2572 case FK_ReferenceBindingToInitList:
2573 case FK_InitListBadDestinationType:
2574 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002575 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002576 case FK_ArrayTypeMismatch:
2577 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002578 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002579 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002580 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002581 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002582 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002583 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002584
Douglas Gregorb70cf442010-03-26 20:14:36 +00002585 case FK_ReferenceInitOverloadFailed:
2586 case FK_UserConversionOverloadFailed:
2587 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002588 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002589 return FailedOverloadResult == OR_Ambiguous;
2590 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002591
David Blaikie7530c032012-01-17 06:56:22 +00002592 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002593}
2594
Douglas Gregord6e44a32010-04-16 22:09:46 +00002595bool InitializationSequence::isConstructorInitialization() const {
2596 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2597}
2598
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002599void
2600InitializationSequence
2601::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2602 DeclAccessPair Found,
2603 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002604 Step S;
2605 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2606 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002607 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002608 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002609 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002610 Steps.push_back(S);
2611}
2612
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002613void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002614 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002615 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002616 switch (VK) {
2617 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2618 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2619 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002620 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002621 S.Type = BaseType;
2622 Steps.push_back(S);
2623}
2624
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002625void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002626 bool BindingTemporary) {
2627 Step S;
2628 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2629 S.Type = T;
2630 Steps.push_back(S);
2631}
2632
Douglas Gregor523d46a2010-04-18 07:40:54 +00002633void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2634 Step S;
2635 S.Kind = SK_ExtraneousCopyToTemporary;
2636 S.Type = T;
2637 Steps.push_back(S);
2638}
2639
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002640void
2641InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2642 DeclAccessPair FoundDecl,
2643 QualType T,
2644 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002645 Step S;
2646 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002647 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002648 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002649 S.Function.Function = Function;
2650 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002651 Steps.push_back(S);
2652}
2653
2654void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002655 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002656 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002657 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002658 switch (VK) {
2659 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002660 S.Kind = SK_QualificationConversionRValue;
2661 break;
John McCall5baba9d2010-08-25 10:28:54 +00002662 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002663 S.Kind = SK_QualificationConversionXValue;
2664 break;
John McCall5baba9d2010-08-25 10:28:54 +00002665 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002666 S.Kind = SK_QualificationConversionLValue;
2667 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002668 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002669 S.Type = Ty;
2670 Steps.push_back(S);
2671}
2672
Jordan Rose1fd1e282013-04-11 00:58:58 +00002673void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2674 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2675
2676 Step S;
2677 S.Kind = SK_LValueToRValue;
2678 S.Type = Ty;
2679 Steps.push_back(S);
2680}
2681
Douglas Gregor20093b42009-12-09 23:02:17 +00002682void InitializationSequence::AddConversionSequenceStep(
2683 const ImplicitConversionSequence &ICS,
2684 QualType T) {
2685 Step S;
2686 S.Kind = SK_ConversionSequence;
2687 S.Type = T;
2688 S.ICS = new ImplicitConversionSequence(ICS);
2689 Steps.push_back(S);
2690}
2691
Douglas Gregord87b61f2009-12-10 17:56:55 +00002692void InitializationSequence::AddListInitializationStep(QualType T) {
2693 Step S;
2694 S.Kind = SK_ListInitialization;
2695 S.Type = T;
2696 Steps.push_back(S);
2697}
2698
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002700InitializationSequence
2701::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2702 AccessSpecifier Access,
2703 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002704 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002705 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002706 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002707 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2708 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002709 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002710 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002711 S.Function.Function = Constructor;
2712 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002713 Steps.push_back(S);
2714}
2715
Douglas Gregor71d17402009-12-15 00:01:57 +00002716void InitializationSequence::AddZeroInitializationStep(QualType T) {
2717 Step S;
2718 S.Kind = SK_ZeroInitialization;
2719 S.Type = T;
2720 Steps.push_back(S);
2721}
2722
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002723void InitializationSequence::AddCAssignmentStep(QualType T) {
2724 Step S;
2725 S.Kind = SK_CAssignment;
2726 S.Type = T;
2727 Steps.push_back(S);
2728}
2729
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002730void InitializationSequence::AddStringInitStep(QualType T) {
2731 Step S;
2732 S.Kind = SK_StringInit;
2733 S.Type = T;
2734 Steps.push_back(S);
2735}
2736
Douglas Gregor569c3162010-08-07 11:51:51 +00002737void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2738 Step S;
2739 S.Kind = SK_ObjCObjectConversion;
2740 S.Type = T;
2741 Steps.push_back(S);
2742}
2743
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002744void InitializationSequence::AddArrayInitStep(QualType T) {
2745 Step S;
2746 S.Kind = SK_ArrayInit;
2747 S.Type = T;
2748 Steps.push_back(S);
2749}
2750
Richard Smith0f163e92012-02-15 22:38:09 +00002751void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2752 Step S;
2753 S.Kind = SK_ParenthesizedArrayInit;
2754 S.Type = T;
2755 Steps.push_back(S);
2756}
2757
John McCallf85e1932011-06-15 23:02:42 +00002758void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2759 bool shouldCopy) {
2760 Step s;
2761 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2762 : SK_PassByIndirectRestore);
2763 s.Type = type;
2764 Steps.push_back(s);
2765}
2766
2767void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2768 Step S;
2769 S.Kind = SK_ProduceObjCObject;
2770 S.Type = T;
2771 Steps.push_back(S);
2772}
2773
Sebastian Redl2b916b82012-01-17 22:49:42 +00002774void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2775 Step S;
2776 S.Kind = SK_StdInitializerList;
2777 S.Type = T;
2778 Steps.push_back(S);
2779}
2780
Guy Benyei21f18c42013-02-07 10:55:47 +00002781void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2782 Step S;
2783 S.Kind = SK_OCLSamplerInit;
2784 S.Type = T;
2785 Steps.push_back(S);
2786}
2787
Guy Benyeie6b9d802013-01-20 12:31:11 +00002788void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2789 Step S;
2790 S.Kind = SK_OCLZeroEvent;
2791 S.Type = T;
2792 Steps.push_back(S);
2793}
2794
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002795void InitializationSequence::RewrapReferenceInitList(QualType T,
2796 InitListExpr *Syntactic) {
2797 assert(Syntactic->getNumInits() == 1 &&
2798 "Can only rewrap trivial init lists.");
2799 Step S;
2800 S.Kind = SK_UnwrapInitList;
2801 S.Type = Syntactic->getInit(0)->getType();
2802 Steps.insert(Steps.begin(), S);
2803
2804 S.Kind = SK_RewrapInitList;
2805 S.Type = T;
2806 S.WrappingSyntacticList = Syntactic;
2807 Steps.push_back(S);
2808}
2809
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002811 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002812 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002813 this->Failure = Failure;
2814 this->FailedOverloadResult = Result;
2815}
2816
2817//===----------------------------------------------------------------------===//
2818// Attempt initialization
2819//===----------------------------------------------------------------------===//
2820
John McCallf85e1932011-06-15 23:02:42 +00002821static void MaybeProduceObjCObject(Sema &S,
2822 InitializationSequence &Sequence,
2823 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002824 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002825
2826 /// When initializing a parameter, produce the value if it's marked
2827 /// __attribute__((ns_consumed)).
2828 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2829 if (!Entity.isParameterConsumed())
2830 return;
2831
2832 assert(Entity.getType()->isObjCRetainableType() &&
2833 "consuming an object of unretainable type?");
2834 Sequence.AddProduceObjCObjectStep(Entity.getType());
2835
2836 /// When initializing a return value, if the return type is a
2837 /// retainable type, then returns need to immediately retain the
2838 /// object. If an autorelease is required, it will be done at the
2839 /// last instant.
2840 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2841 if (!Entity.getType()->isObjCRetainableType())
2842 return;
2843
2844 Sequence.AddProduceObjCObjectStep(Entity.getType());
2845 }
2846}
2847
Richard Smithf4bb8d02012-07-05 08:39:21 +00002848/// \brief When initializing from init list via constructor, handle
2849/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002850///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002851/// \return true if we have handled initialization of an object of type
2852/// std::initializer_list<T>, false otherwise.
2853static bool TryInitializerListConstruction(Sema &S,
2854 InitListExpr *List,
2855 QualType DestType,
2856 InitializationSequence &Sequence) {
2857 QualType E;
2858 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002859 return false;
2860
Richard Smithf4bb8d02012-07-05 08:39:21 +00002861 // Check that each individual element can be copy-constructed. But since we
2862 // have no place to store further information, we'll recalculate everything
2863 // later.
2864 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2865 S.Context.getConstantArrayType(E,
2866 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2867 List->getNumInits()),
2868 ArrayType::Normal, 0));
2869 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2870 0, HiddenArray);
2871 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2872 Element.setElementIndex(i);
2873 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2874 Sequence.SetFailed(
2875 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002876 return true;
2877 }
2878 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002879 Sequence.AddStdInitializerListConstructionStep(DestType);
2880 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002881}
2882
Sebastian Redl96715b22012-02-04 21:27:39 +00002883static OverloadingResult
2884ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002885 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002886 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002887 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002888 OverloadCandidateSet::iterator &Best,
2889 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002890 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002891 CandidateSet.clear();
2892
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002893 for (ArrayRef<NamedDecl *>::iterator
2894 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002895 NamedDecl *D = *Con;
2896 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2897 bool SuppressUserConversions = false;
2898
2899 // Find the constructor (which may be a template).
2900 CXXConstructorDecl *Constructor = 0;
2901 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2902 if (ConstructorTmpl)
2903 Constructor = cast<CXXConstructorDecl>(
2904 ConstructorTmpl->getTemplatedDecl());
2905 else {
2906 Constructor = cast<CXXConstructorDecl>(D);
2907
2908 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002909 // suppress user-defined conversions on the arguments. We do the same for
2910 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002911 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002912 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002913 SuppressUserConversions = true;
2914 }
2915
2916 if (!Constructor->isInvalidDecl() &&
2917 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002918 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002919 if (ConstructorTmpl)
2920 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002921 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002922 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002923 else {
2924 // C++ [over.match.copy]p1:
2925 // - When initializing a temporary to be bound to the first parameter
2926 // of a constructor that takes a reference to possibly cv-qualified
2927 // T as its first argument, called with a single argument in the
2928 // context of direct-initialization, explicit conversion functions
2929 // are also considered.
2930 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002931 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00002932 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002933 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002934 SuppressUserConversions,
2935 /*PartialOverloading=*/false,
2936 /*AllowExplicit=*/AllowExplicitConv);
2937 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002938 }
2939 }
2940
2941 // Perform overload resolution and return the result.
2942 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2943}
2944
Sebastian Redl10f04a62011-12-22 14:44:04 +00002945/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2946/// enumerates the constructors of the initialized entity and performs overload
2947/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002948/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002949/// class type.
2950static void TryConstructorInitialization(Sema &S,
2951 const InitializedEntity &Entity,
2952 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002953 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002954 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002955 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002956 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00002957 "InitListSyntax must come with a single initializer list argument.");
2958
Sebastian Redl10f04a62011-12-22 14:44:04 +00002959 // The type we're constructing needs to be complete.
2960 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002961 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002962 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002963 }
2964
2965 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2966 assert(DestRecordType && "Constructor initialization requires record type");
2967 CXXRecordDecl *DestRecordDecl
2968 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2969
Sebastian Redl96715b22012-02-04 21:27:39 +00002970 // Build the candidate set directly in the initialization sequence
2971 // structure, so that it will persist if we fail.
2972 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2973
2974 // Determine whether we are allowed to call explicit constructors or
2975 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002976 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002977 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002978
Sebastian Redl10f04a62011-12-22 14:44:04 +00002979 // - Otherwise, if T is a class type, constructors are considered. The
2980 // applicable constructors are enumerated, and the best one is chosen
2981 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00002982 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002983 // The container holding the constructors can under certain conditions
2984 // be changed while iterating (e.g. because of deserialization).
2985 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00002986 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00002987
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002988 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002989 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002990 bool AsInitializerList = false;
2991
2992 // C++11 [over.match.list]p1:
2993 // When objects of non-aggregate type T are list-initialized, overload
2994 // resolution selects the constructor in two phases:
2995 // - Initially, the candidate functions are the initializer-list
2996 // constructors of the class T and the argument list consists of the
2997 // initializer list as a single argument.
2998 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002999 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003000 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003001
3002 // If the initializer list has no elements and T has a default constructor,
3003 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003004 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003005 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003006 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003007 CopyInitialization, AllowExplicit,
3008 /*OnlyListConstructor=*/true,
3009 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003010
3011 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003012 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003013 }
3014
3015 // C++11 [over.match.list]p1:
3016 // - If no viable initializer-list constructor is found, overload resolution
3017 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003018 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003019 // elements of the initializer list.
3020 if (Result == OR_No_Viable_Function) {
3021 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003022 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003023 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003024 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003025 /*OnlyListConstructors=*/false,
3026 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003027 }
3028 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003029 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003030 InitializationSequence::FK_ListConstructorOverloadFailed :
3031 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003032 Result);
3033 return;
3034 }
3035
Richard Smithf4bb8d02012-07-05 08:39:21 +00003036 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003037 // If a program calls for the default initialization of an object
3038 // of a const-qualified type T, T shall be a class type with a
3039 // user-provided default constructor.
3040 if (Kind.getKind() == InitializationKind::IK_Default &&
3041 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003042 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003043 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3044 return;
3045 }
3046
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003047 // C++11 [over.match.list]p1:
3048 // In copy-list-initialization, if an explicit constructor is chosen, the
3049 // initializer is ill-formed.
3050 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3051 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3052 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3053 return;
3054 }
3055
Sebastian Redl10f04a62011-12-22 14:44:04 +00003056 // Add the constructor initialization step. Any cv-qualification conversion is
3057 // subsumed by the initialization.
3058 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003059 Sequence.AddConstructorInitializationStep(CtorDecl,
3060 Best->FoundDecl.getAccess(),
3061 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003062 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003063}
3064
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003065static bool
3066ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3067 Expr *Initializer,
3068 QualType &SourceType,
3069 QualType &UnqualifiedSourceType,
3070 QualType UnqualifiedTargetType,
3071 InitializationSequence &Sequence) {
3072 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3073 S.Context.OverloadTy) {
3074 DeclAccessPair Found;
3075 bool HadMultipleCandidates = false;
3076 if (FunctionDecl *Fn
3077 = S.ResolveAddressOfOverloadedFunction(Initializer,
3078 UnqualifiedTargetType,
3079 false, Found,
3080 &HadMultipleCandidates)) {
3081 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3082 HadMultipleCandidates);
3083 SourceType = Fn->getType();
3084 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3085 } else if (!UnqualifiedTargetType->isRecordType()) {
3086 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3087 return true;
3088 }
3089 }
3090 return false;
3091}
3092
3093static void TryReferenceInitializationCore(Sema &S,
3094 const InitializedEntity &Entity,
3095 const InitializationKind &Kind,
3096 Expr *Initializer,
3097 QualType cv1T1, QualType T1,
3098 Qualifiers T1Quals,
3099 QualType cv2T2, QualType T2,
3100 Qualifiers T2Quals,
3101 InitializationSequence &Sequence);
3102
Richard Smithf4bb8d02012-07-05 08:39:21 +00003103static void TryValueInitialization(Sema &S,
3104 const InitializedEntity &Entity,
3105 const InitializationKind &Kind,
3106 InitializationSequence &Sequence,
3107 InitListExpr *InitList = 0);
3108
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003109static void TryListInitialization(Sema &S,
3110 const InitializedEntity &Entity,
3111 const InitializationKind &Kind,
3112 InitListExpr *InitList,
3113 InitializationSequence &Sequence);
3114
3115/// \brief Attempt list initialization of a reference.
3116static void TryReferenceListInitialization(Sema &S,
3117 const InitializedEntity &Entity,
3118 const InitializationKind &Kind,
3119 InitListExpr *InitList,
3120 InitializationSequence &Sequence)
3121{
3122 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003123 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003124 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3125 return;
3126 }
3127
3128 QualType DestType = Entity.getType();
3129 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3130 Qualifiers T1Quals;
3131 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3132
3133 // Reference initialization via an initializer list works thus:
3134 // If the initializer list consists of a single element that is
3135 // reference-related to the referenced type, bind directly to that element
3136 // (possibly creating temporaries).
3137 // Otherwise, initialize a temporary with the initializer list and
3138 // bind to that.
3139 if (InitList->getNumInits() == 1) {
3140 Expr *Initializer = InitList->getInit(0);
3141 QualType cv2T2 = Initializer->getType();
3142 Qualifiers T2Quals;
3143 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3144
3145 // If this fails, creating a temporary wouldn't work either.
3146 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3147 T1, Sequence))
3148 return;
3149
3150 SourceLocation DeclLoc = Initializer->getLocStart();
3151 bool dummy1, dummy2, dummy3;
3152 Sema::ReferenceCompareResult RefRelationship
3153 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3154 dummy2, dummy3);
3155 if (RefRelationship >= Sema::Ref_Related) {
3156 // Try to bind the reference here.
3157 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3158 T1Quals, cv2T2, T2, T2Quals, Sequence);
3159 if (Sequence)
3160 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3161 return;
3162 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003163
3164 // Update the initializer if we've resolved an overloaded function.
3165 if (Sequence.step_begin() != Sequence.step_end())
3166 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003167 }
3168
3169 // Not reference-related. Create a temporary and bind to that.
3170 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3171
3172 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3173 if (Sequence) {
3174 if (DestType->isRValueReferenceType() ||
3175 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3176 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3177 else
3178 Sequence.SetFailed(
3179 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3180 }
3181}
3182
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003183/// \brief Attempt list initialization (C++0x [dcl.init.list])
3184static void TryListInitialization(Sema &S,
3185 const InitializedEntity &Entity,
3186 const InitializationKind &Kind,
3187 InitListExpr *InitList,
3188 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003189 QualType DestType = Entity.getType();
3190
Sebastian Redl14b0c192011-09-24 17:48:00 +00003191 // C++ doesn't allow scalar initialization with more than one argument.
3192 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003193 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003194 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3195 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3196 return;
3197 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003198 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003199 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003200 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003201 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003202 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003203 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003204 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003205 return;
3206 }
3207
Richard Smithf4bb8d02012-07-05 08:39:21 +00003208 // C++11 [dcl.init.list]p3:
3209 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003210 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003211 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003212 // - Otherwise, if the initializer list has no elements and T is a
3213 // class type with a default constructor, the object is
3214 // value-initialized.
3215 if (InitList->getNumInits() == 0) {
3216 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003217 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003218 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3219 return;
3220 }
3221 }
3222
3223 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3224 // an initializer_list object constructed [...]
3225 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3226 return;
3227
3228 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003229 Expr *InitListAsExpr = InitList;
3230 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003231 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003232 } else
3233 Sequence.SetFailed(
3234 InitializationSequence::FK_InitListBadDestinationType);
3235 return;
3236 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003237 }
3238
Sebastian Redl14b0c192011-09-24 17:48:00 +00003239 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003240 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003241 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00003242 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003243 if (CheckInitList.HadError()) {
3244 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3245 return;
3246 }
3247
3248 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003249 Sequence.AddListInitializationStep(DestType);
3250}
Douglas Gregor20093b42009-12-09 23:02:17 +00003251
3252/// \brief Try a reference initialization that involves calling a conversion
3253/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003254static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3255 const InitializedEntity &Entity,
3256 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003257 Expr *Initializer,
3258 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003259 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003260 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003261 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3262 QualType T1 = cv1T1.getUnqualifiedType();
3263 QualType cv2T2 = Initializer->getType();
3264 QualType T2 = cv2T2.getUnqualifiedType();
3265
3266 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003267 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003268 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003269 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003270 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003271 ObjCConversion,
3272 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003273 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003274 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003275 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003276 (void)ObjCLifetimeConversion;
3277
Douglas Gregor20093b42009-12-09 23:02:17 +00003278 // Build the candidate set directly in the initialization sequence
3279 // structure, so that it will persist if we fail.
3280 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3281 CandidateSet.clear();
3282
3283 // Determine whether we are allowed to call explicit constructors or
3284 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003285 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003286 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3287
Douglas Gregor20093b42009-12-09 23:02:17 +00003288 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003289 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3290 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003291 // The type we're converting to is a class type. Enumerate its constructors
3292 // to see if there is a suitable conversion.
3293 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003294
David Blaikie3bc93e32012-12-19 00:45:41 +00003295 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003296 // The container holding the constructors can under certain conditions
3297 // be changed while iterating (e.g. because of deserialization).
3298 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003299 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003300 for (SmallVector<NamedDecl*, 16>::iterator
3301 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3302 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003303 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3304
Douglas Gregor20093b42009-12-09 23:02:17 +00003305 // Find the constructor (which may be a template).
3306 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003307 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 if (ConstructorTmpl)
3309 Constructor = cast<CXXConstructorDecl>(
3310 ConstructorTmpl->getTemplatedDecl());
3311 else
John McCall9aa472c2010-03-19 07:35:19 +00003312 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003313
Douglas Gregor20093b42009-12-09 23:02:17 +00003314 if (!Constructor->isInvalidDecl() &&
3315 Constructor->isConvertingConstructor(AllowExplicit)) {
3316 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003317 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003318 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003319 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003320 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003321 else
John McCall9aa472c2010-03-19 07:35:19 +00003322 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003323 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003324 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003325 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003326 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003327 }
John McCall572fc622010-08-17 07:23:57 +00003328 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3329 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003330
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003331 const RecordType *T2RecordType = 0;
3332 if ((T2RecordType = T2->getAs<RecordType>()) &&
3333 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003334 // The type we're converting from is a class type, enumerate its conversion
3335 // functions.
3336 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3337
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003338 std::pair<CXXRecordDecl::conversion_iterator,
3339 CXXRecordDecl::conversion_iterator>
3340 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3341 for (CXXRecordDecl::conversion_iterator
3342 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003343 NamedDecl *D = *I;
3344 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3345 if (isa<UsingShadowDecl>(D))
3346 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003347
Douglas Gregor20093b42009-12-09 23:02:17 +00003348 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3349 CXXConversionDecl *Conv;
3350 if (ConvTemplate)
3351 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3352 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003353 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003354
Douglas Gregor20093b42009-12-09 23:02:17 +00003355 // If the conversion function doesn't return a reference type,
3356 // it can't be considered for this conversion unless we're allowed to
3357 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358 // FIXME: Do we need to make sure that we only consider conversion
3359 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003360 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003361 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003362 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3363 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003364 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003365 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003366 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003367 else
John McCall9aa472c2010-03-19 07:35:19 +00003368 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003369 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003370 }
3371 }
3372 }
John McCall572fc622010-08-17 07:23:57 +00003373 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3374 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375
Douglas Gregor20093b42009-12-09 23:02:17 +00003376 SourceLocation DeclLoc = Initializer->getLocStart();
3377
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003379 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003380 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003381 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003382 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003383
Douglas Gregor20093b42009-12-09 23:02:17 +00003384 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003385 // This is the overload that will be used for this initialization step if we
3386 // use this initialization. Mark it as referenced.
3387 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003388
Eli Friedman03981012009-12-11 02:42:07 +00003389 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003390 if (isa<CXXConversionDecl>(Function))
3391 T2 = Function->getResultType();
3392 else
3393 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003394
3395 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003396 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003397 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003398 T2.getNonLValueExprType(S.Context),
3399 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003400
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003402 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003403 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003404 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003405 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003406 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003407 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003408
Douglas Gregor20093b42009-12-09 23:02:17 +00003409 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003410 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003411 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003412 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003413 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003414 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003415 NewDerivedToBase, NewObjCConversion,
3416 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003417 if (NewRefRelationship == Sema::Ref_Incompatible) {
3418 // If the type we've converted to is not reference-related to the
3419 // type we're looking for, then there is another conversion step
3420 // we need to perform to produce a temporary of the right type
3421 // that we'll be binding to.
3422 ImplicitConversionSequence ICS;
3423 ICS.setStandard();
3424 ICS.Standard = Best->FinalConversion;
3425 T2 = ICS.Standard.getToType(2);
3426 Sequence.AddConversionSequenceStep(ICS, T2);
3427 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003428 Sequence.AddDerivedToBaseCastStep(
3429 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003430 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003431 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003432 else if (NewObjCConversion)
3433 Sequence.AddObjCObjectConversionStep(
3434 S.Context.getQualifiedType(T1,
3435 T2.getNonReferenceType().getQualifiers()));
3436
Douglas Gregor20093b42009-12-09 23:02:17 +00003437 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003438 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003439
Douglas Gregor20093b42009-12-09 23:02:17 +00003440 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3441 return OR_Success;
3442}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003443
Richard Smith83da2e72011-10-19 16:55:56 +00003444static void CheckCXX98CompatAccessibleCopy(Sema &S,
3445 const InitializedEntity &Entity,
3446 Expr *CurInitExpr);
3447
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003448/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3449static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003450 const InitializedEntity &Entity,
3451 const InitializationKind &Kind,
3452 Expr *Initializer,
3453 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003454 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003455 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003456 Qualifiers T1Quals;
3457 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003458 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003459 Qualifiers T2Quals;
3460 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003461
Douglas Gregor20093b42009-12-09 23:02:17 +00003462 // If the initializer is the address of an overloaded function, try
3463 // to resolve the overloaded function. If all goes well, T2 is the
3464 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003465 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3466 T1, Sequence))
3467 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003468
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003469 // Delegate everything else to a subfunction.
3470 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3471 T1Quals, cv2T2, T2, T2Quals, Sequence);
3472}
3473
Jordan Rose1fd1e282013-04-11 00:58:58 +00003474/// Converts the target of reference initialization so that it has the
3475/// appropriate qualifiers and value kind.
3476///
3477/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3478/// \code
3479/// int x;
3480/// const int &r = x;
3481/// \endcode
3482///
3483/// In this case the reference is binding to a bitfield lvalue, which isn't
3484/// valid. Perform a load to create a lifetime-extended temporary instead.
3485/// \code
3486/// const int &r = someStruct.bitfield;
3487/// \endcode
3488static ExprValueKind
3489convertQualifiersAndValueKindIfNecessary(Sema &S,
3490 InitializationSequence &Sequence,
3491 Expr *Initializer,
3492 QualType cv1T1,
3493 Qualifiers T1Quals,
3494 Qualifiers T2Quals,
3495 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003496 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003497 Initializer->refersToVectorElement();
3498
3499 if (IsNonAddressableType) {
3500 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3501 // lvalue reference to a non-volatile const type, or the reference shall be
3502 // an rvalue reference.
3503 //
3504 // If not, we can't make a temporary and bind to that. Give up and allow the
3505 // error to be diagnosed later.
3506 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3507 assert(Initializer->isGLValue());
3508 return Initializer->getValueKind();
3509 }
3510
3511 // Force a load so we can materialize a temporary.
3512 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3513 return VK_RValue;
3514 }
3515
3516 if (T1Quals != T2Quals) {
3517 Sequence.AddQualificationConversionStep(cv1T1,
3518 Initializer->getValueKind());
3519 }
3520
3521 return Initializer->getValueKind();
3522}
3523
3524
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003525/// \brief Reference initialization without resolving overloaded functions.
3526static void TryReferenceInitializationCore(Sema &S,
3527 const InitializedEntity &Entity,
3528 const InitializationKind &Kind,
3529 Expr *Initializer,
3530 QualType cv1T1, QualType T1,
3531 Qualifiers T1Quals,
3532 QualType cv2T2, QualType T2,
3533 Qualifiers T2Quals,
3534 InitializationSequence &Sequence) {
3535 QualType DestType = Entity.getType();
3536 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003537 // Compute some basic properties of the types and the initializer.
3538 bool isLValueRef = DestType->isLValueReferenceType();
3539 bool isRValueRef = !isLValueRef;
3540 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003541 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003542 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003543 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003544 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003545 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003546 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003547
Douglas Gregor20093b42009-12-09 23:02:17 +00003548 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003550 // "cv2 T2" as follows:
3551 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003552 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003553 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003554 // Note the analogous bullet points for rvlaue refs to functions. Because
3555 // there are no function rvalues in C++, rvalue refs to functions are treated
3556 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003557 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003558 bool T1Function = T1->isFunctionType();
3559 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003560 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003561 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003562 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003563 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003564 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003565 // reference-compatible with "cv2 T2," or
3566 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003567 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003568 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003569 // can occur. However, we do pay attention to whether it is a bit-field
3570 // to decide whether we're actually binding to a temporary created from
3571 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003572 if (DerivedToBase)
3573 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003574 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003575 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003576 else if (ObjCConversion)
3577 Sequence.AddObjCObjectConversionStep(
3578 S.Context.getQualifiedType(T1, T2Quals));
3579
Jordan Rose1fd1e282013-04-11 00:58:58 +00003580 ExprValueKind ValueKind =
3581 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3582 cv1T1, T1Quals, T2Quals,
3583 isLValueRef);
3584 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003585 return;
3586 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003587
3588 // - has a class type (i.e., T2 is a class type), where T1 is not
3589 // reference-related to T2, and can be implicitly converted to an
3590 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3591 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003592 // applicable conversion functions (13.3.1.6) and choosing the best
3593 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003594 // If we have an rvalue ref to function type here, the rhs must be
3595 // an rvalue.
3596 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3597 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003598 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003599 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003600 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003601 Sequence);
3602 if (ConvOvlResult == OR_Success)
3603 return;
John McCall1d318332010-01-12 00:44:57 +00003604 if (ConvOvlResult != OR_No_Viable_Function) {
3605 Sequence.SetOverloadFailure(
3606 InitializationSequence::FK_ReferenceInitOverloadFailed,
3607 ConvOvlResult);
3608 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003609 }
3610 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003611
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003612 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003613 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003614 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003615 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003616 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3617 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3618 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003619 Sequence.SetOverloadFailure(
3620 InitializationSequence::FK_ReferenceInitOverloadFailed,
3621 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003622 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003623 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003624 ? (RefRelationship == Sema::Ref_Related
3625 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3626 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3627 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003628
Douglas Gregor20093b42009-12-09 23:02:17 +00003629 return;
3630 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003631
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003632 // - If the initializer expression
3633 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3634 // "cv1 T1" is reference-compatible with "cv2 T2"
3635 // Note: functions are handled below.
3636 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003637 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003638 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003639 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003640 (InitCategory.isXValue() ||
3641 (InitCategory.isPRValue() && T2->isRecordType()) ||
3642 (InitCategory.isPRValue() && T2->isArrayType()))) {
3643 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3644 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003645 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3646 // compiler the freedom to perform a copy here or bind to the
3647 // object, while C++0x requires that we bind directly to the
3648 // object. Hence, we always bind to the object without making an
3649 // extra copy. However, in C++03 requires that we check for the
3650 // presence of a suitable copy constructor:
3651 //
3652 // The constructor that would be used to make the copy shall
3653 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003654 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003655 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003656 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003657 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003658 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003659
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003660 if (DerivedToBase)
3661 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3662 ValueKind);
3663 else if (ObjCConversion)
3664 Sequence.AddObjCObjectConversionStep(
3665 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003666
Jordan Rose1fd1e282013-04-11 00:58:58 +00003667 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3668 Initializer, cv1T1,
3669 T1Quals, T2Quals,
3670 isLValueRef);
3671
3672 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003674 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003675
3676 // - has a class type (i.e., T2 is a class type), where T1 is not
3677 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003678 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3679 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003680 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003681 if (RefRelationship == Sema::Ref_Incompatible) {
3682 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3683 Kind, Initializer,
3684 /*AllowRValues=*/true,
3685 Sequence);
3686 if (ConvOvlResult)
3687 Sequence.SetOverloadFailure(
3688 InitializationSequence::FK_ReferenceInitOverloadFailed,
3689 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003690
Douglas Gregor20093b42009-12-09 23:02:17 +00003691 return;
3692 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003693
Douglas Gregordefa32e2013-03-26 23:59:23 +00003694 if ((RefRelationship == Sema::Ref_Compatible ||
3695 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3696 isRValueRef && InitCategory.isLValue()) {
3697 Sequence.SetFailed(
3698 InitializationSequence::FK_RValueReferenceBindingToLValue);
3699 return;
3700 }
3701
Douglas Gregor20093b42009-12-09 23:02:17 +00003702 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3703 return;
3704 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003705
3706 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003707 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003709 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003710
Douglas Gregor20093b42009-12-09 23:02:17 +00003711 // Determine whether we are allowed to call explicit constructors or
3712 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003713 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003714
3715 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3716
John McCallf85e1932011-06-15 23:02:42 +00003717 ImplicitConversionSequence ICS
3718 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003719 /*SuppressUserConversions*/ false,
3720 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003721 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003722 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3723 /*AllowObjCWritebackConversion=*/false);
3724
3725 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003726 // FIXME: Use the conversion function set stored in ICS to turn
3727 // this into an overloading ambiguity diagnostic. However, we need
3728 // to keep that set as an OverloadCandidateSet rather than as some
3729 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003730 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3731 Sequence.SetOverloadFailure(
3732 InitializationSequence::FK_ReferenceInitOverloadFailed,
3733 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003734 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3735 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003736 else
3737 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003738 return;
John McCallf85e1932011-06-15 23:02:42 +00003739 } else {
3740 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003741 }
3742
3743 // [...] If T1 is reference-related to T2, cv1 must be the
3744 // same cv-qualification as, or greater cv-qualification
3745 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003746 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3747 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003748 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003749 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003750 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3751 return;
3752 }
3753
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003754 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003755 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003756 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003757 InitCategory.isLValue()) {
3758 Sequence.SetFailed(
3759 InitializationSequence::FK_RValueReferenceBindingToLValue);
3760 return;
3761 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003762
Douglas Gregor20093b42009-12-09 23:02:17 +00003763 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3764 return;
3765}
3766
3767/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003768/// (C++ [dcl.init.string], C99 6.7.8).
3769static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003770 const InitializedEntity &Entity,
3771 const InitializationKind &Kind,
3772 Expr *Initializer,
3773 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003774 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003775}
3776
Douglas Gregor71d17402009-12-15 00:01:57 +00003777/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003779 const InitializedEntity &Entity,
3780 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003781 InitializationSequence &Sequence,
3782 InitListExpr *InitList) {
3783 assert((!InitList || InitList->getNumInits() == 0) &&
3784 "Shouldn't use value-init for non-empty init lists");
3785
Richard Smith1d0c9a82012-02-14 21:14:13 +00003786 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003787 //
3788 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003789 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790
Douglas Gregor71d17402009-12-15 00:01:57 +00003791 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003792 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003793
Douglas Gregor71d17402009-12-15 00:01:57 +00003794 if (const RecordType *RT = T->getAs<RecordType>()) {
3795 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003796 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003797 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003798 // C++98:
3799 // -- if T is a class type (clause 9) with a user-declared constructor
3800 // (12.1), then the default constructor for T is called (and the
3801 // initialization is ill-formed if T has no accessible default
3802 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003803 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003804 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003805 } else {
3806 // C++11:
3807 // -- if T is a class type (clause 9) with either no default constructor
3808 // (12.1 [class.ctor]) or a default constructor that is user-provided
3809 // or deleted, then the object is default-initialized;
3810 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3811 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003812 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003813 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814
Richard Smith1d0c9a82012-02-14 21:14:13 +00003815 // -- if T is a (possibly cv-qualified) non-union class type without a
3816 // user-provided or deleted default constructor, then the object is
3817 // zero-initialized and, if T has a non-trivial default constructor,
3818 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003819 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3820 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003821 if (NeedZeroInitialization)
3822 Sequence.AddZeroInitializationStep(Entity.getType());
3823
Richard Smithd5bc8672012-12-08 02:01:17 +00003824 // C++03:
3825 // -- if T is a non-union class type without a user-declared constructor,
3826 // then every non-static data member and base class component of T is
3827 // value-initialized;
3828 // [...] A program that calls for [...] value-initialization of an
3829 // entity of reference type is ill-formed.
3830 //
3831 // C++11 doesn't need this handling, because value-initialization does not
3832 // occur recursively there, and the implicit default constructor is
3833 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003834 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003835 ClassDecl->hasUninitializedReferenceMember()) {
3836 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3837 return;
3838 }
3839
Richard Smithf4bb8d02012-07-05 08:39:21 +00003840 // If this is list-value-initialization, pass the empty init list on when
3841 // building the constructor call. This affects the semantics of a few
3842 // things (such as whether an explicit default constructor can be called).
3843 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003844 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003845 bool InitListSyntax = InitList;
3846
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003847 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3848 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003849 }
3850 }
3851
Douglas Gregord6542d82009-12-22 15:35:07 +00003852 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003853}
3854
Douglas Gregor99a2e602009-12-16 01:38:02 +00003855/// \brief Attempt default initialization (C++ [dcl.init]p6).
3856static void TryDefaultInitialization(Sema &S,
3857 const InitializedEntity &Entity,
3858 const InitializationKind &Kind,
3859 InitializationSequence &Sequence) {
3860 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003861
Douglas Gregor99a2e602009-12-16 01:38:02 +00003862 // C++ [dcl.init]p6:
3863 // To default-initialize an object of type T means:
3864 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003865 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3866
Douglas Gregor99a2e602009-12-16 01:38:02 +00003867 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3868 // constructor for T is called (and the initialization is ill-formed if
3869 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003870 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003871 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003872 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003873 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003874
Douglas Gregor99a2e602009-12-16 01:38:02 +00003875 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003876
Douglas Gregor99a2e602009-12-16 01:38:02 +00003877 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003878 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003879 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003880 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003881 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003882 return;
3883 }
3884
3885 // If the destination type has a lifetime property, zero-initialize it.
3886 if (DestType.getQualifiers().hasObjCLifetime()) {
3887 Sequence.AddZeroInitializationStep(Entity.getType());
3888 return;
3889 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003890}
3891
Douglas Gregor20093b42009-12-09 23:02:17 +00003892/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3893/// which enumerates all conversion functions and performs overload resolution
3894/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003895static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003896 const InitializedEntity &Entity,
3897 const InitializationKind &Kind,
3898 Expr *Initializer,
3899 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003900 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003901 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3902 QualType SourceType = Initializer->getType();
3903 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3904 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003905
Douglas Gregor4a520a22009-12-14 17:27:33 +00003906 // Build the candidate set directly in the initialization sequence
3907 // structure, so that it will persist if we fail.
3908 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3909 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003910
Douglas Gregor4a520a22009-12-14 17:27:33 +00003911 // Determine whether we are allowed to call explicit constructors or
3912 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003913 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003914
Douglas Gregor4a520a22009-12-14 17:27:33 +00003915 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3916 // The type we're converting to is a class type. Enumerate its constructors
3917 // to see if there is a suitable conversion.
3918 CXXRecordDecl *DestRecordDecl
3919 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003920
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003921 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003922 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003923 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003924 // The container holding the constructors can under certain conditions
3925 // be changed while iterating. To be safe we copy the lookup results
3926 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003927 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003928 for (SmallVector<NamedDecl*, 8>::iterator
3929 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003930 Con != ConEnd; ++Con) {
3931 NamedDecl *D = *Con;
3932 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003933
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003934 // Find the constructor (which may be a template).
3935 CXXConstructorDecl *Constructor = 0;
3936 FunctionTemplateDecl *ConstructorTmpl
3937 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003938 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003939 Constructor = cast<CXXConstructorDecl>(
3940 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003941 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003942 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003943
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003944 if (!Constructor->isInvalidDecl() &&
3945 Constructor->isConvertingConstructor(AllowExplicit)) {
3946 if (ConstructorTmpl)
3947 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3948 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003949 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003950 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003951 else
3952 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003953 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003954 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003955 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003956 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003957 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003958 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003959
3960 SourceLocation DeclLoc = Initializer->getLocStart();
3961
Douglas Gregor4a520a22009-12-14 17:27:33 +00003962 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3963 // The type we're converting from is a class type, enumerate its conversion
3964 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003965
Eli Friedman33c2da92009-12-20 22:12:03 +00003966 // We can only enumerate the conversion functions for a complete type; if
3967 // the type isn't complete, simply skip this step.
3968 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3969 CXXRecordDecl *SourceRecordDecl
3970 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003971
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003972 std::pair<CXXRecordDecl::conversion_iterator,
3973 CXXRecordDecl::conversion_iterator>
3974 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3975 for (CXXRecordDecl::conversion_iterator
3976 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003977 NamedDecl *D = *I;
3978 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3979 if (isa<UsingShadowDecl>(D))
3980 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003981
Eli Friedman33c2da92009-12-20 22:12:03 +00003982 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3983 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003984 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003985 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003986 else
John McCall32daa422010-03-31 01:36:47 +00003987 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003988
Eli Friedman33c2da92009-12-20 22:12:03 +00003989 if (AllowExplicit || !Conv->isExplicit()) {
3990 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003991 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003992 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003993 CandidateSet);
3994 else
John McCall9aa472c2010-03-19 07:35:19 +00003995 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003996 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003997 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003998 }
3999 }
4000 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001
4002 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004003 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004004 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004005 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004006 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004007 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004008 Result);
4009 return;
4010 }
John McCall1d318332010-01-12 00:44:57 +00004011
Douglas Gregor4a520a22009-12-14 17:27:33 +00004012 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004013 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004014 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004015
Douglas Gregor4a520a22009-12-14 17:27:33 +00004016 if (isa<CXXConstructorDecl>(Function)) {
4017 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004018 // subsumed by the initialization. Per DR5, the created temporary is of the
4019 // cv-unqualified type of the destination.
4020 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4021 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004022 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004023 return;
4024 }
4025
4026 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004027 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004028 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004029 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004030 // the resulting temporary object (possible to create an object of
4031 // a base class type). That copy is not a separate conversion, so
4032 // we just make a note of the actual destination type (possibly a
4033 // base class of the type returned by the conversion function) and
4034 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004035 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4036 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004037 return;
4038 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004039
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004040 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4041 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004042
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004043 // If the conversion following the call to the conversion function
4044 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004045 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4046 Best->FinalConversion.Third) {
4047 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004048 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004049 ICS.Standard = Best->FinalConversion;
4050 Sequence.AddConversionSequenceStep(ICS, DestType);
4051 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004052}
4053
John McCallf85e1932011-06-15 23:02:42 +00004054/// The non-zero enum values here are indexes into diagnostic alternatives.
4055enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4056
4057/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004058static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004059 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004060 // Skip parens.
4061 e = e->IgnoreParens();
4062
4063 // Skip address-of nodes.
4064 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4065 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004066 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4067 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004068
4069 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004070 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4071 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004072 case CK_Dependent:
4073 case CK_BitCast:
4074 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004075 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004076 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004077
4078 case CK_ArrayToPointerDecay:
4079 return IIK_nonscalar;
4080
4081 case CK_NullToPointer:
4082 return IIK_okay;
4083
4084 default:
4085 break;
4086 }
4087
4088 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004089 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004090 // set isWeakAccess to true, to mean that there will be an implicit
4091 // load which requires a cleanup.
4092 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4093 isWeakAccess = true;
4094
John McCallc03fa492011-06-27 23:59:58 +00004095 if (!isAddressOf) return IIK_nonlocal;
4096
John McCallf4b88a42012-03-10 09:33:50 +00004097 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4098 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004099
4100 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004101
4102 // If we have a conditional operator, check both sides.
4103 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004104 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4105 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004106 return iik;
4107
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004108 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004109
4110 // These are never scalar.
4111 } else if (isa<ArraySubscriptExpr>(e)) {
4112 return IIK_nonscalar;
4113
4114 // Otherwise, it needs to be a null pointer constant.
4115 } else {
4116 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4117 ? IIK_okay : IIK_nonlocal);
4118 }
4119
4120 return IIK_nonlocal;
4121}
4122
4123/// Check whether the given expression is a valid operand for an
4124/// indirect copy/restore.
4125static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4126 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004127 bool isWeakAccess = false;
4128 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4129 // If isWeakAccess to true, there will be an implicit
4130 // load which requires a cleanup.
4131 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4132 S.ExprNeedsCleanups = true;
4133
John McCallf85e1932011-06-15 23:02:42 +00004134 if (iik == IIK_okay) return;
4135
4136 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4137 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4138 << src->getSourceRange();
4139}
4140
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004141/// \brief Determine whether we have compatible array types for the
4142/// purposes of GNU by-copy array initialization.
4143static bool hasCompatibleArrayTypes(ASTContext &Context,
4144 const ArrayType *Dest,
4145 const ArrayType *Source) {
4146 // If the source and destination array types are equivalent, we're
4147 // done.
4148 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4149 return true;
4150
4151 // Make sure that the element types are the same.
4152 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4153 return false;
4154
4155 // The only mismatch we allow is when the destination is an
4156 // incomplete array type and the source is a constant array type.
4157 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4158}
4159
John McCallf85e1932011-06-15 23:02:42 +00004160static bool tryObjCWritebackConversion(Sema &S,
4161 InitializationSequence &Sequence,
4162 const InitializedEntity &Entity,
4163 Expr *Initializer) {
4164 bool ArrayDecay = false;
4165 QualType ArgType = Initializer->getType();
4166 QualType ArgPointee;
4167 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4168 ArrayDecay = true;
4169 ArgPointee = ArgArrayType->getElementType();
4170 ArgType = S.Context.getPointerType(ArgPointee);
4171 }
4172
4173 // Handle write-back conversion.
4174 QualType ConvertedArgType;
4175 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4176 ConvertedArgType))
4177 return false;
4178
4179 // We should copy unless we're passing to an argument explicitly
4180 // marked 'out'.
4181 bool ShouldCopy = true;
4182 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4183 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4184
4185 // Do we need an lvalue conversion?
4186 if (ArrayDecay || Initializer->isGLValue()) {
4187 ImplicitConversionSequence ICS;
4188 ICS.setStandard();
4189 ICS.Standard.setAsIdentityConversion();
4190
4191 QualType ResultType;
4192 if (ArrayDecay) {
4193 ICS.Standard.First = ICK_Array_To_Pointer;
4194 ResultType = S.Context.getPointerType(ArgPointee);
4195 } else {
4196 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4197 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4198 }
4199
4200 Sequence.AddConversionSequenceStep(ICS, ResultType);
4201 }
4202
4203 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4204 return true;
4205}
4206
Guy Benyei21f18c42013-02-07 10:55:47 +00004207static bool TryOCLSamplerInitialization(Sema &S,
4208 InitializationSequence &Sequence,
4209 QualType DestType,
4210 Expr *Initializer) {
4211 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4212 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4213 return false;
4214
4215 Sequence.AddOCLSamplerInitStep(DestType);
4216 return true;
4217}
4218
Guy Benyeie6b9d802013-01-20 12:31:11 +00004219//
4220// OpenCL 1.2 spec, s6.12.10
4221//
4222// The event argument can also be used to associate the
4223// async_work_group_copy with a previous async copy allowing
4224// an event to be shared by multiple async copies; otherwise
4225// event should be zero.
4226//
4227static bool TryOCLZeroEventInitialization(Sema &S,
4228 InitializationSequence &Sequence,
4229 QualType DestType,
4230 Expr *Initializer) {
4231 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4232 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4233 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4234 return false;
4235
4236 Sequence.AddOCLZeroEventStep(DestType);
4237 return true;
4238}
4239
Douglas Gregor20093b42009-12-09 23:02:17 +00004240InitializationSequence::InitializationSequence(Sema &S,
4241 const InitializedEntity &Entity,
4242 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004243 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004244 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004245 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246
John McCall76da55d2013-04-16 07:28:30 +00004247 // Eliminate non-overload placeholder types in the arguments. We
4248 // need to do this before checking whether types are dependent
4249 // because lowering a pseudo-object expression might well give us
4250 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004251 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004252 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4253 // FIXME: should we be doing this here?
4254 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4255 if (result.isInvalid()) {
4256 SetFailed(FK_PlaceholderType);
4257 return;
4258 }
4259 Args[I] = result.take();
4260 }
4261
Douglas Gregor20093b42009-12-09 23:02:17 +00004262 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263 // The semantics of initializers are as follows. The destination type is
4264 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004265 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004266 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004267 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004268 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004269
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004270 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004271 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004272 SequenceKind = DependentSequence;
4273 return;
4274 }
4275
Sebastian Redl7491c492011-06-05 13:59:11 +00004276 // Almost everything is a normal sequence.
4277 setSequenceKind(NormalSequence);
4278
Douglas Gregor20093b42009-12-09 23:02:17 +00004279 QualType SourceType;
4280 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004281 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004282 Initializer = Args[0];
4283 if (!isa<InitListExpr>(Initializer))
4284 SourceType = Initializer->getType();
4285 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004286
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004287 // - If the initializer is a (non-parenthesized) braced-init-list, the
4288 // object is list-initialized (8.5.4).
4289 if (Kind.getKind() != InitializationKind::IK_Direct) {
4290 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4291 TryListInitialization(S, Entity, Kind, InitList, *this);
4292 return;
4293 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004295
Douglas Gregor20093b42009-12-09 23:02:17 +00004296 // - If the destination type is a reference type, see 8.5.3.
4297 if (DestType->isReferenceType()) {
4298 // C++0x [dcl.init.ref]p1:
4299 // A variable declared to be a T& or T&&, that is, "reference to type T"
4300 // (8.3.2), shall be initialized by an object, or function, of type T or
4301 // by an object that can be converted into a T.
4302 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004303 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004304 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004305 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004306 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004307 return;
4308 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309
Douglas Gregor20093b42009-12-09 23:02:17 +00004310 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004311 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004312 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004313 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004314 return;
4315 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316
Douglas Gregor99a2e602009-12-16 01:38:02 +00004317 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004318 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004319 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004320 return;
4321 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004322
John McCallce6c9b72011-02-21 07:22:22 +00004323 // - If the destination type is an array of characters, an array of
4324 // char16_t, an array of char32_t, or an array of wchar_t, and the
4325 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004326 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004327 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004328 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004329 if (Initializer && isa<VariableArrayType>(DestAT)) {
4330 SetFailed(FK_VariableLengthArrayHasInitializer);
4331 return;
4332 }
4333
Hans Wennborg0ff50742013-05-15 11:03:04 +00004334 if (Initializer) {
4335 switch (IsStringInit(Initializer, DestAT, Context)) {
4336 case SIF_None:
4337 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4338 return;
4339 case SIF_NarrowStringIntoWideChar:
4340 SetFailed(FK_NarrowStringIntoWideCharArray);
4341 return;
4342 case SIF_WideStringIntoChar:
4343 SetFailed(FK_WideStringIntoCharArray);
4344 return;
4345 case SIF_IncompatWideStringIntoWideChar:
4346 SetFailed(FK_IncompatWideStringIntoWideChar);
4347 return;
4348 case SIF_Other:
4349 break;
4350 }
John McCallce6c9b72011-02-21 07:22:22 +00004351 }
4352
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004353 // Note: as an GNU C extension, we allow initialization of an
4354 // array from a compound literal that creates an array of the same
4355 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004356 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004357 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4358 Initializer->getType()->isArrayType()) {
4359 const ArrayType *SourceAT
4360 = Context.getAsArrayType(Initializer->getType());
4361 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004362 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004363 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004364 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004365 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004366 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004367 }
Richard Smith0f163e92012-02-15 22:38:09 +00004368 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004369 // Note: as a GNU C++ extension, we allow list-initialization of a
4370 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004371 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004372 Entity.getKind() == InitializedEntity::EK_Member &&
4373 Initializer && isa<InitListExpr>(Initializer)) {
4374 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4375 *this);
4376 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004377 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004378 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004379 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4380 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004381 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004382 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004383
Douglas Gregor20093b42009-12-09 23:02:17 +00004384 return;
4385 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004386
John McCallf85e1932011-06-15 23:02:42 +00004387 // Determine whether we should consider writeback conversions for
4388 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004389 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004390 Entity.getKind() == InitializedEntity::EK_Parameter;
4391
4392 // We're at the end of the line for C: it's either a write-back conversion
4393 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004394 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004395 // If allowed, check whether this is an Objective-C writeback conversion.
4396 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004397 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004398 return;
4399 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004400
4401 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4402 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004403
4404 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4405 return;
4406
John McCallf85e1932011-06-15 23:02:42 +00004407 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004408 AddCAssignmentStep(DestType);
4409 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004410 return;
4411 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004412
David Blaikie4e4d0842012-03-11 07:00:24 +00004413 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004414
Douglas Gregor20093b42009-12-09 23:02:17 +00004415 // - If the destination type is a (possibly cv-qualified) class type:
4416 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004417 // - If the initialization is direct-initialization, or if it is
4418 // copy-initialization where the cv-unqualified version of the
4419 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004420 // class of the destination, constructors are considered. [...]
4421 if (Kind.getKind() == InitializationKind::IK_Direct ||
4422 (Kind.getKind() == InitializationKind::IK_Copy &&
4423 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4424 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004425 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004426 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004427 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004428 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004429 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004430 // used) to a derived class thereof are enumerated as described in
4431 // 13.3.1.4, and the best one is chosen through overload resolution
4432 // (13.3).
4433 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004434 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004435 return;
4436 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004437
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004438 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004439 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004440 return;
4441 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004442 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004443
4444 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004445 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004446 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004447 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4448 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004449 return;
4450 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451
Douglas Gregor20093b42009-12-09 23:02:17 +00004452 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004453 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004454 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004455 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004456 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004457
4458 ImplicitConversionSequence ICS
4459 = S.TryImplicitConversion(Initializer, Entity.getType(),
4460 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004461 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004462 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004463 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4464 allowObjCWritebackConversion);
4465
4466 if (ICS.isStandard() &&
4467 ICS.Standard.Second == ICK_Writeback_Conversion) {
4468 // Objective-C ARC writeback conversion.
4469
4470 // We should copy unless we're passing to an argument explicitly
4471 // marked 'out'.
4472 bool ShouldCopy = true;
4473 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4474 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4475
4476 // If there was an lvalue adjustment, add it as a separate conversion.
4477 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4478 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4479 ImplicitConversionSequence LvalueICS;
4480 LvalueICS.setStandard();
4481 LvalueICS.Standard.setAsIdentityConversion();
4482 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4483 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004484 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004485 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004486
4487 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004488 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004489 DeclAccessPair dap;
4490 if (Initializer->getType() == Context.OverloadTy &&
4491 !S.ResolveAddressOfOverloadedFunction(Initializer
4492 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004493 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004494 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004495 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004496 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004497 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004498
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004499 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004500 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004501}
4502
4503InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004504 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004505 StepEnd = Steps.end();
4506 Step != StepEnd; ++Step)
4507 Step->Destroy();
4508}
4509
4510//===----------------------------------------------------------------------===//
4511// Perform initialization
4512//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004513static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004514getAssignmentAction(const InitializedEntity &Entity) {
4515 switch(Entity.getKind()) {
4516 case InitializedEntity::EK_Variable:
4517 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004518 case InitializedEntity::EK_Exception:
4519 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004520 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004521 return Sema::AA_Initializing;
4522
4523 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004524 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004525 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4526 return Sema::AA_Sending;
4527
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004528 return Sema::AA_Passing;
4529
4530 case InitializedEntity::EK_Result:
4531 return Sema::AA_Returning;
4532
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004533 case InitializedEntity::EK_Temporary:
4534 // FIXME: Can we tell apart casting vs. converting?
4535 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004536
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004537 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004538 case InitializedEntity::EK_ArrayElement:
4539 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004540 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004541 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004542 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004543 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004544 return Sema::AA_Initializing;
4545 }
4546
David Blaikie7530c032012-01-17 06:56:22 +00004547 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004548}
4549
Richard Smith774d8b42013-01-08 00:08:23 +00004550/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004551/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004552static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004553 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004554 case InitializedEntity::EK_ArrayElement:
4555 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004556 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004557 case InitializedEntity::EK_New:
4558 case InitializedEntity::EK_Variable:
4559 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004560 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004561 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004562 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004563 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004564 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004565 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004566 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004567 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004569 case InitializedEntity::EK_Parameter:
4570 case InitializedEntity::EK_Temporary:
4571 return true;
4572 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004573
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004574 llvm_unreachable("missed an InitializedEntity kind?");
4575}
4576
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004577/// \brief Whether the given entity, when initialized with an object
4578/// created for that initialization, requires destruction.
4579static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4580 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004581 case InitializedEntity::EK_Result:
4582 case InitializedEntity::EK_New:
4583 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004584 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004585 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004586 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004587 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004588 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004589 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004590
Richard Smith774d8b42013-01-08 00:08:23 +00004591 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004592 case InitializedEntity::EK_Variable:
4593 case InitializedEntity::EK_Parameter:
4594 case InitializedEntity::EK_Temporary:
4595 case InitializedEntity::EK_ArrayElement:
4596 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004597 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004598 return true;
4599 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004600
4601 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004602}
4603
Richard Smith83da2e72011-10-19 16:55:56 +00004604/// \brief Look for copy and move constructors and constructor templates, for
4605/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4606static void LookupCopyAndMoveConstructors(Sema &S,
4607 OverloadCandidateSet &CandidateSet,
4608 CXXRecordDecl *Class,
4609 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004610 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004611 // The container holding the constructors can under certain conditions
4612 // be changed while iterating (e.g. because of deserialization).
4613 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004614 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004615 for (SmallVector<NamedDecl*, 16>::iterator
4616 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4617 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004618 CXXConstructorDecl *Constructor = 0;
4619
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004620 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004621 // Handle copy/moveconstructors, only.
4622 if (!Constructor || Constructor->isInvalidDecl() ||
4623 !Constructor->isCopyOrMoveConstructor() ||
4624 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4625 continue;
4626
4627 DeclAccessPair FoundDecl
4628 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4629 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004630 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004631 continue;
4632 }
4633
4634 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004635 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004636 if (ConstructorTmpl->isInvalidDecl())
4637 continue;
4638
4639 Constructor = cast<CXXConstructorDecl>(
4640 ConstructorTmpl->getTemplatedDecl());
4641 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4642 continue;
4643
4644 // FIXME: Do we need to limit this to copy-constructor-like
4645 // candidates?
4646 DeclAccessPair FoundDecl
4647 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4648 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004649 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004650 }
4651}
4652
4653/// \brief Get the location at which initialization diagnostics should appear.
4654static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4655 Expr *Initializer) {
4656 switch (Entity.getKind()) {
4657 case InitializedEntity::EK_Result:
4658 return Entity.getReturnLoc();
4659
4660 case InitializedEntity::EK_Exception:
4661 return Entity.getThrowLoc();
4662
4663 case InitializedEntity::EK_Variable:
4664 return Entity.getDecl()->getLocation();
4665
Douglas Gregor47736542012-02-15 16:57:26 +00004666 case InitializedEntity::EK_LambdaCapture:
4667 return Entity.getCaptureLoc();
4668
Richard Smith83da2e72011-10-19 16:55:56 +00004669 case InitializedEntity::EK_ArrayElement:
4670 case InitializedEntity::EK_Member:
4671 case InitializedEntity::EK_Parameter:
4672 case InitializedEntity::EK_Temporary:
4673 case InitializedEntity::EK_New:
4674 case InitializedEntity::EK_Base:
4675 case InitializedEntity::EK_Delegating:
4676 case InitializedEntity::EK_VectorElement:
4677 case InitializedEntity::EK_ComplexElement:
4678 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004679 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith83da2e72011-10-19 16:55:56 +00004680 return Initializer->getLocStart();
4681 }
4682 llvm_unreachable("missed an InitializedEntity kind?");
4683}
4684
Douglas Gregor523d46a2010-04-18 07:40:54 +00004685/// \brief Make a (potentially elidable) temporary copy of the object
4686/// provided by the given initializer by calling the appropriate copy
4687/// constructor.
4688///
4689/// \param S The Sema object used for type-checking.
4690///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004691/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004692/// the type of the initializer expression or a superclass thereof.
4693///
James Dennett1dfbd922012-06-14 21:40:34 +00004694/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004695///
4696/// \param CurInit The initializer expression.
4697///
4698/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4699/// is permitted in C++03 (but not C++0x) when binding a reference to
4700/// an rvalue.
4701///
4702/// \returns An expression that copies the initializer expression into
4703/// a temporary object, or an error expression if a copy could not be
4704/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004705static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004706 QualType T,
4707 const InitializedEntity &Entity,
4708 ExprResult CurInit,
4709 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004710 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004711 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004712 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004713 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004714 Class = cast<CXXRecordDecl>(Record->getDecl());
4715 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004716 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004717
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004718 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004719 // When certain criteria are met, an implementation is allowed to
4720 // omit the copy/move construction of a class object, even if the
4721 // copy/move constructor and/or destructor for the object have
4722 // side effects. [...]
4723 // - when a temporary class object that has not been bound to a
4724 // reference (12.2) would be copied/moved to a class object
4725 // with the same cv-unqualified type, the copy/move operation
4726 // can be omitted by constructing the temporary object
4727 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004729 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004730 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004731 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004732 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004733 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004734 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004735
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004736 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004737 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004738 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004739
Douglas Gregorcc15f012011-01-21 19:38:21 +00004740 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004741 // Only consider constructors and constructor templates. Per
4742 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4743 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004744 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004745 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004746
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004747 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4748
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004749 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004750 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004751 case OR_Success:
4752 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004753
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004754 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004755 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4756 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4757 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004758 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004759 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004760 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004761 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004762 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004763 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004764
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004765 case OR_Ambiguous:
4766 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004767 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004768 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004769 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004770 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004771
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004772 case OR_Deleted:
4773 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004774 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004775 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004776 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004777 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004778 }
4779
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004780 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004781 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004782 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004783
Anders Carlsson9a68a672010-04-21 18:47:17 +00004784 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004785 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004786
4787 if (IsExtraneousCopy) {
4788 // If this is a totally extraneous copy for C++03 reference
4789 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004790 // expression. We don't generate an (elided) copy operation here
4791 // because doing so would require us to pass down a flag to avoid
4792 // infinite recursion, where each step adds another extraneous,
4793 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004794
Douglas Gregor2559a702010-04-18 07:57:34 +00004795 // Instantiate the default arguments of any extra parameters in
4796 // the selected copy constructor, as if we were going to create a
4797 // proper call to the copy constructor.
4798 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4799 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4800 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004801 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004802 break;
4803
4804 // Build the default argument expression; we don't actually care
4805 // if this succeeds or not, because this routine will complain
4806 // if there was a problem.
4807 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4808 }
4809
Douglas Gregor523d46a2010-04-18 07:40:54 +00004810 return S.Owned(CurInitExpr);
4811 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004812
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004813 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004814 // constructor call (we might have derived-to-base conversions, or
4815 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004816 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004817 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004818
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004819 // Actually perform the constructor call.
4820 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004821 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004822 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004823 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004824 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004825 CXXConstructExpr::CK_Complete,
4826 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004827
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004828 // If we're supposed to bind temporaries, do so.
4829 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4830 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004831 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004832}
Douglas Gregor20093b42009-12-09 23:02:17 +00004833
Richard Smith83da2e72011-10-19 16:55:56 +00004834/// \brief Check whether elidable copy construction for binding a reference to
4835/// a temporary would have succeeded if we were building in C++98 mode, for
4836/// -Wc++98-compat.
4837static void CheckCXX98CompatAccessibleCopy(Sema &S,
4838 const InitializedEntity &Entity,
4839 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004840 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004841
4842 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4843 if (!Record)
4844 return;
4845
4846 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4847 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4848 == DiagnosticsEngine::Ignored)
4849 return;
4850
4851 // Find constructors which would have been considered.
4852 OverloadCandidateSet CandidateSet(Loc);
4853 LookupCopyAndMoveConstructors(
4854 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4855
4856 // Perform overload resolution.
4857 OverloadCandidateSet::iterator Best;
4858 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4859
4860 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4861 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4862 << CurInitExpr->getSourceRange();
4863
4864 switch (OR) {
4865 case OR_Success:
4866 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004867 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004868 // FIXME: Check default arguments as far as that's possible.
4869 break;
4870
4871 case OR_No_Viable_Function:
4872 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004873 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004874 break;
4875
4876 case OR_Ambiguous:
4877 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004878 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004879 break;
4880
4881 case OR_Deleted:
4882 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004883 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004884 break;
4885 }
4886}
4887
Douglas Gregora41a8c52010-04-22 00:20:18 +00004888void InitializationSequence::PrintInitLocationNote(Sema &S,
4889 const InitializedEntity &Entity) {
4890 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4891 if (Entity.getDecl()->getLocation().isInvalid())
4892 return;
4893
4894 if (Entity.getDecl()->getDeclName())
4895 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4896 << Entity.getDecl()->getDeclName();
4897 else
4898 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4899 }
4900}
4901
Sebastian Redl3b802322011-07-14 19:07:55 +00004902static bool isReferenceBinding(const InitializationSequence::Step &s) {
4903 return s.Kind == InitializationSequence::SK_BindReference ||
4904 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4905}
4906
Jordan Rose2624b812013-05-06 16:48:12 +00004907/// Returns true if the parameters describe a constructor initialization of
4908/// an explicit temporary object, e.g. "Point(x, y)".
4909static bool isExplicitTemporary(const InitializedEntity &Entity,
4910 const InitializationKind &Kind,
4911 unsigned NumArgs) {
4912 switch (Entity.getKind()) {
4913 case InitializedEntity::EK_Temporary:
4914 case InitializedEntity::EK_CompoundLiteralInit:
4915 break;
4916 default:
4917 return false;
4918 }
4919
4920 switch (Kind.getKind()) {
4921 case InitializationKind::IK_DirectList:
4922 return true;
4923 // FIXME: Hack to work around cast weirdness.
4924 case InitializationKind::IK_Direct:
4925 case InitializationKind::IK_Value:
4926 return NumArgs != 1;
4927 default:
4928 return false;
4929 }
4930}
4931
Sebastian Redl10f04a62011-12-22 14:44:04 +00004932static ExprResult
4933PerformConstructorInitialization(Sema &S,
4934 const InitializedEntity &Entity,
4935 const InitializationKind &Kind,
4936 MultiExprArg Args,
4937 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004938 bool &ConstructorInitRequiresZeroInit,
4939 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004940 unsigned NumArgs = Args.size();
4941 CXXConstructorDecl *Constructor
4942 = cast<CXXConstructorDecl>(Step.Function.Function);
4943 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4944
4945 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004946 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004947 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4948 ? Kind.getEqualLoc()
4949 : Kind.getLocation();
4950
4951 if (Kind.getKind() == InitializationKind::IK_Default) {
4952 // Force even a trivial, implicit default constructor to be
4953 // semantically checked. We do this explicitly because we don't build
4954 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004955 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004956 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004957 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004958 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4959 }
4960
4961 ExprResult CurInit = S.Owned((Expr *)0);
4962
Douglas Gregored878af2012-02-24 23:56:31 +00004963 // C++ [over.match.copy]p1:
4964 // - When initializing a temporary to be bound to the first parameter
4965 // of a constructor that takes a reference to possibly cv-qualified
4966 // T as its first argument, called with a single argument in the
4967 // context of direct-initialization, explicit conversion functions
4968 // are also considered.
4969 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4970 Args.size() == 1 &&
4971 Constructor->isCopyOrMoveConstructor();
4972
Sebastian Redl10f04a62011-12-22 14:44:04 +00004973 // Determine the arguments required to actually perform the constructor
4974 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004975 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004976 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004977 AllowExplicitConv,
4978 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004979 return ExprError();
4980
4981
Jordan Rose2624b812013-05-06 16:48:12 +00004982 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004983 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004984 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00004985 if (S.DiagnoseUseOfDecl(Constructor, Loc))
4986 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004987
4988 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4989 if (!TSInfo)
4990 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004991 SourceRange ParenRange;
4992 if (Kind.getKind() != InitializationKind::IK_DirectList)
4993 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004994
Richard Smithc83c2302012-12-19 01:39:02 +00004995 CurInit = S.Owned(
4996 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4997 TSInfo, ConstructorArgs,
4998 ParenRange, IsListInitialization,
4999 HadMultipleCandidates,
5000 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00005001 } else {
5002 CXXConstructExpr::ConstructionKind ConstructKind =
5003 CXXConstructExpr::CK_Complete;
5004
5005 if (Entity.getKind() == InitializedEntity::EK_Base) {
5006 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5007 CXXConstructExpr::CK_VirtualBase :
5008 CXXConstructExpr::CK_NonVirtualBase;
5009 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5010 ConstructKind = CXXConstructExpr::CK_Delegating;
5011 }
5012
5013 // Only get the parenthesis range if it is a direct construction.
5014 SourceRange parenRange =
5015 Kind.getKind() == InitializationKind::IK_Direct ?
5016 Kind.getParenRange() : SourceRange();
5017
5018 // If the entity allows NRVO, mark the construction as elidable
5019 // unconditionally.
5020 if (Entity.allowsNRVO())
5021 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5022 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005023 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005024 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005025 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005026 ConstructorInitRequiresZeroInit,
5027 ConstructKind,
5028 parenRange);
5029 else
5030 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5031 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005032 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005033 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005034 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005035 ConstructorInitRequiresZeroInit,
5036 ConstructKind,
5037 parenRange);
5038 }
5039 if (CurInit.isInvalid())
5040 return ExprError();
5041
5042 // Only check access if all of that succeeded.
5043 S.CheckConstructorAccess(Loc, Constructor, Entity,
5044 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005045 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5046 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005047
5048 if (shouldBindAsTemporary(Entity))
5049 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5050
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005051 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005052}
5053
Richard Smith36d02af2012-06-04 22:27:30 +00005054/// Determine whether the specified InitializedEntity definitely has a lifetime
5055/// longer than the current full-expression. Conservatively returns false if
5056/// it's unclear.
5057static bool
5058InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5059 const InitializedEntity *Top = &Entity;
5060 while (Top->getParent())
5061 Top = Top->getParent();
5062
5063 switch (Top->getKind()) {
5064 case InitializedEntity::EK_Variable:
5065 case InitializedEntity::EK_Result:
5066 case InitializedEntity::EK_Exception:
5067 case InitializedEntity::EK_Member:
5068 case InitializedEntity::EK_New:
5069 case InitializedEntity::EK_Base:
5070 case InitializedEntity::EK_Delegating:
5071 return true;
5072
5073 case InitializedEntity::EK_ArrayElement:
5074 case InitializedEntity::EK_VectorElement:
5075 case InitializedEntity::EK_BlockElement:
5076 case InitializedEntity::EK_ComplexElement:
5077 // Could not determine what the full initialization is. Assume it might not
5078 // outlive the full-expression.
5079 return false;
5080
5081 case InitializedEntity::EK_Parameter:
5082 case InitializedEntity::EK_Temporary:
5083 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005084 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith36d02af2012-06-04 22:27:30 +00005085 // The entity being initialized might not outlive the full-expression.
5086 return false;
5087 }
5088
5089 llvm_unreachable("unknown entity kind");
5090}
5091
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005092ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005093InitializationSequence::Perform(Sema &S,
5094 const InitializedEntity &Entity,
5095 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005096 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005097 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005098 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005099 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005100 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005101 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005102
Sebastian Redl7491c492011-06-05 13:59:11 +00005103 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005104 // If the declaration is a non-dependent, incomplete array type
5105 // that has an initializer, then its type will be completed once
5106 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005107 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005108 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005109 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005110 if (const IncompleteArrayType *ArrayT
5111 = S.Context.getAsIncompleteArrayType(DeclType)) {
5112 // FIXME: We don't currently have the ability to accurately
5113 // compute the length of an initializer list without
5114 // performing full type-checking of the initializer list
5115 // (since we have to determine where braces are implicitly
5116 // introduced and such). So, we fall back to making the array
5117 // type a dependently-sized array type with no specified
5118 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005119 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005120 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005121
Douglas Gregord87b61f2009-12-10 17:56:55 +00005122 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005123 if (DeclaratorDecl *DD = Entity.getDecl()) {
5124 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5125 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005126 if (IncompleteArrayTypeLoc ArrayLoc =
5127 TL.getAs<IncompleteArrayTypeLoc>())
5128 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005129 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005130 }
5131
5132 *ResultType
5133 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5134 /*NumElts=*/0,
5135 ArrayT->getSizeModifier(),
5136 ArrayT->getIndexTypeCVRQualifiers(),
5137 Brackets);
5138 }
5139
5140 }
5141 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005142 if (Kind.getKind() == InitializationKind::IK_Direct &&
5143 !Kind.isExplicitCast()) {
5144 // Rebuild the ParenListExpr.
5145 SourceRange ParenRange = Kind.getParenRange();
5146 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005147 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005148 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005149 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005150 Kind.isExplicitCast() ||
5151 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005152 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005153 }
5154
Sebastian Redl7491c492011-06-05 13:59:11 +00005155 // No steps means no initialization.
5156 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005157 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005158
Richard Smith80ad52f2013-01-02 11:42:31 +00005159 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005160 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005161 Entity.getKind() != InitializedEntity::EK_Parameter) {
5162 // Produce a C++98 compatibility warning if we are initializing a reference
5163 // from an initializer list. For parameters, we produce a better warning
5164 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005165 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005166 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5167 << Init->getSourceRange();
5168 }
5169
Richard Smith36d02af2012-06-04 22:27:30 +00005170 // Diagnose cases where we initialize a pointer to an array temporary, and the
5171 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005172 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005173 Entity.getType()->isPointerType() &&
5174 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005175 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005176 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5177 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5178 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5179 << Init->getSourceRange();
5180 }
5181
Douglas Gregord6542d82009-12-22 15:35:07 +00005182 QualType DestType = Entity.getType().getNonReferenceType();
5183 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005184 // the same as Entity.getDecl()->getType() in cases involving type merging,
5185 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005186 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005187 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005188 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005189
John McCall60d7b3a2010-08-24 06:29:42 +00005190 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005191
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005192 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005193 // grab the only argument out the Args and place it into the "current"
5194 // initializer.
5195 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005196 case SK_ResolveAddressOfOverloadedFunction:
5197 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005198 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005199 case SK_CastDerivedToBaseLValue:
5200 case SK_BindReference:
5201 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005202 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005203 case SK_UserConversion:
5204 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005205 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005206 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005207 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005208 case SK_ConversionSequence:
5209 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005210 case SK_UnwrapInitList:
5211 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005212 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005213 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005214 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005215 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005216 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005217 case SK_PassByIndirectCopyRestore:
5218 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005219 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005220 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005221 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005222 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005223 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005224 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005225 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005226 break;
John McCallf6a16482010-12-04 03:47:34 +00005227 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005228
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005229 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005230 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005231 case SK_ZeroInitialization:
5232 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005233 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005234
5235 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005236 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005237 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005238 for (step_iterator Step = step_begin(), StepEnd = step_end();
5239 Step != StepEnd; ++Step) {
5240 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005241 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005242
John Wiegley429bb272011-04-08 18:41:53 +00005243 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005244
Douglas Gregor20093b42009-12-09 23:02:17 +00005245 switch (Step->Kind) {
5246 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005247 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005248 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005249 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005250 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5251 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005252 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005253 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005254 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005255 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005256
Douglas Gregor20093b42009-12-09 23:02:17 +00005257 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005258 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005259 case SK_CastDerivedToBaseLValue: {
5260 // We have a derived-to-base cast that produces either an rvalue or an
5261 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005262
John McCallf871d0c2010-08-07 06:22:56 +00005263 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005264
Douglas Gregor20093b42009-12-09 23:02:17 +00005265 // Casts to inaccessible base classes are allowed with C-style casts.
5266 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5267 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005268 CurInit.get()->getLocStart(),
5269 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005270 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005271 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005272
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005273 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5274 QualType T = SourceType;
5275 if (const PointerType *Pointer = T->getAs<PointerType>())
5276 T = Pointer->getPointeeType();
5277 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005278 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005279 cast<CXXRecordDecl>(RecordTy->getDecl()));
5280 }
5281
John McCall5baba9d2010-08-25 10:28:54 +00005282 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005283 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005284 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005285 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005286 VK_XValue :
5287 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005288 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5289 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005290 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005291 CurInit.get(),
5292 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005293 break;
5294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005295
Douglas Gregor20093b42009-12-09 23:02:17 +00005296 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005297 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5298 if (CurInit.get()->refersToBitField()) {
5299 // We don't necessarily have an unambiguous source bit-field.
5300 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005301 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005302 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005303 << (BitField ? BitField->getDeclName() : DeclarationName())
5304 << (BitField != NULL)
John Wiegley429bb272011-04-08 18:41:53 +00005305 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005306 if (BitField)
5307 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5308
John McCallf312b1e2010-08-26 23:41:50 +00005309 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005310 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005311
John Wiegley429bb272011-04-08 18:41:53 +00005312 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005313 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005314 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5315 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005316 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005317 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005318 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005319 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005320
Douglas Gregor20093b42009-12-09 23:02:17 +00005321 // Reference binding does not have any corresponding ASTs.
5322
5323 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005324 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005325 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005326
Douglas Gregor20093b42009-12-09 23:02:17 +00005327 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005328
Douglas Gregor20093b42009-12-09 23:02:17 +00005329 case SK_BindReferenceToTemporary:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005330 // Make sure the "temporary" is actually an rvalue.
5331 assert(CurInit.get()->isRValue() && "not a temporary");
5332
Douglas Gregor20093b42009-12-09 23:02:17 +00005333 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005334 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005335 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005336
Douglas Gregor03e80032011-06-21 17:03:29 +00005337 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005338 CurInit = new (S.Context) MaterializeTemporaryExpr(
5339 Entity.getType().getNonReferenceType(),
5340 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005341 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005342
5343 // If we're binding to an Objective-C object that has lifetime, we
5344 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005345 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005346 CurInit.get()->getType()->isObjCLifetimeType())
5347 S.ExprNeedsCleanups = true;
5348
Douglas Gregor20093b42009-12-09 23:02:17 +00005349 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005350
Douglas Gregor523d46a2010-04-18 07:40:54 +00005351 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005352 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005353 /*IsExtraneousCopy=*/true);
5354 break;
5355
Douglas Gregor20093b42009-12-09 23:02:17 +00005356 case SK_UserConversion: {
5357 // We have a user-defined conversion that invokes either a constructor
5358 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005359 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005360 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005361 FunctionDecl *Fn = Step->Function.Function;
5362 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005363 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005364 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005365 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005366 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005367 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005368 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005369 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005370
Douglas Gregor20093b42009-12-09 23:02:17 +00005371 // Determine the arguments required to actually perform the constructor
5372 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005373 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005374 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005375 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005376 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005377 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005378
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005379 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005380 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005381 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005382 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005383 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005384 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005385 CXXConstructExpr::CK_Complete,
5386 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005387 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005388 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005389
Anders Carlsson9a68a672010-04-21 18:47:17 +00005390 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005391 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005392 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5393 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005394
John McCall2de56d12010-08-25 11:45:40 +00005395 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005396 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5397 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5398 S.IsDerivedFrom(SourceType, Class))
5399 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005400
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005401 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005402 } else {
5403 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005404 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005405 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005406 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005407 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5408 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005409
5410 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005411 // derived-to-base conversion? I believe the answer is "no", because
5412 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005413 ExprResult CurInitExprRes =
5414 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5415 FoundFn, Conversion);
5416 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005417 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005418 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005419
Douglas Gregor20093b42009-12-09 23:02:17 +00005420 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005421 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5422 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005423 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005424 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005425
John McCall2de56d12010-08-25 11:45:40 +00005426 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005427
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005428 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005429 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005430
Sebastian Redl3b802322011-07-14 19:07:55 +00005431 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005432 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5433
5434 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005435 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005436 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005437 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005438 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005439 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005440 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005441 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005442 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5443 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005444 }
5445 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005446
John McCallf871d0c2010-08-07 06:22:56 +00005447 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005448 CurInit.get()->getType(),
5449 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005450 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005451 if (MaybeBindToTemp)
5452 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005453 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005454 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005455 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005456 break;
5457 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005458
Douglas Gregor20093b42009-12-09 23:02:17 +00005459 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005460 case SK_QualificationConversionXValue:
5461 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005462 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005463 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005464 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005465 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005466 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005467 VK_XValue :
5468 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005469 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005470 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005471 }
5472
Jordan Rose1fd1e282013-04-11 00:58:58 +00005473 case SK_LValueToRValue: {
5474 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5475 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5476 CK_LValueToRValue,
5477 CurInit.take(),
5478 /*BasePath=*/0,
5479 VK_RValue));
5480 break;
5481 }
5482
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005483 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005484 Sema::CheckedConversionKind CCK
5485 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5486 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005487 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005488 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005489 ExprResult CurInitExprRes =
5490 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005491 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005492 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005493 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005494 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005495 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005496 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005497
Douglas Gregord87b61f2009-12-10 17:56:55 +00005498 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005499 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005500 // Hack: We must pass *ResultType if available in order to set the type
5501 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5502 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5503 // temporary, not a reference, so we should pass Ty.
5504 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5505 // Since this step is never used for a reference directly, we explicitly
5506 // unwrap references here and rewrap them afterwards.
5507 // We also need to create a InitializeTemporary entity for this.
5508 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005509 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005510 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005511 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5512 InitListChecker PerformInitList(S, InitEntity,
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005513 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005514 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00005515 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005516 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005517 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005518
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005519 if (ResultType) {
5520 if ((*ResultType)->isRValueReferenceType())
5521 Ty = S.Context.getRValueReferenceType(Ty);
5522 else if ((*ResultType)->isLValueReferenceType())
5523 Ty = S.Context.getLValueReferenceType(Ty,
5524 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5525 *ResultType = Ty;
5526 }
5527
5528 InitListExpr *StructuredInitList =
5529 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005530 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005531 CurInit = shouldBindAsTemporary(InitEntity)
5532 ? S.MaybeBindToTemporary(StructuredInitList)
5533 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005534 break;
5535 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005536
Sebastian Redl10f04a62011-12-22 14:44:04 +00005537 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005538 // When an initializer list is passed for a parameter of type "reference
5539 // to object", we don't get an EK_Temporary entity, but instead an
5540 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005541 // FIXME: This is a hack. What we really should do is create a user
5542 // conversion step for this case, but this makes it considerably more
5543 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005544 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5545 Entity.getType().getNonReferenceType());
5546 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005547 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005548 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005549 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5550 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005551 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005552 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5553 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005554 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005555 ConstructorInitRequiresZeroInit,
5556 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005557 break;
5558 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005559
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005560 case SK_UnwrapInitList:
5561 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5562 break;
5563
5564 case SK_RewrapInitList: {
5565 Expr *E = CurInit.take();
5566 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5567 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005568 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005569 ILE->setSyntacticForm(Syntactic);
5570 ILE->setType(E->getType());
5571 ILE->setValueKind(E->getValueKind());
5572 CurInit = S.Owned(ILE);
5573 break;
5574 }
5575
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005576 case SK_ConstructorInitialization: {
5577 // When an initializer list is passed for a parameter of type "reference
5578 // to object", we don't get an EK_Temporary entity, but instead an
5579 // EK_Parameter entity with reference type.
5580 // FIXME: This is a hack. What we really should do is create a user
5581 // conversion step for this case, but this makes it considerably more
5582 // complicated. For now, this will do.
5583 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5584 Entity.getType().getNonReferenceType());
5585 bool UseTemporary = Entity.getType()->isReferenceType();
5586 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5587 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005588 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005589 ConstructorInitRequiresZeroInit,
5590 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005591 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005592 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005593
Douglas Gregor71d17402009-12-15 00:01:57 +00005594 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005595 step_iterator NextStep = Step;
5596 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005597 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005598 (NextStep->Kind == SK_ConstructorInitialization ||
5599 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005600 // The need for zero-initialization is recorded directly into
5601 // the call to the object's constructor within the next step.
5602 ConstructorInitRequiresZeroInit = true;
5603 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005604 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005605 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005606 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5607 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005608 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005609 Kind.getRange().getBegin());
5610
5611 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5612 TSInfo->getType().getNonLValueExprType(S.Context),
5613 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005614 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005615 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005616 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005617 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005618 break;
5619 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005620
5621 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005622 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005623 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005624 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005625 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5626 if (Result.isInvalid())
5627 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005628 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005629
5630 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005631 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005632 if (ConvTy != Sema::Compatible &&
5633 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005634 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005635 == Sema::Compatible)
5636 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005637 if (CurInitExprRes.isInvalid())
5638 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005639 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005640
Douglas Gregora41a8c52010-04-22 00:20:18 +00005641 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005642 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5643 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005644 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005645 getAssignmentAction(Entity),
5646 &Complained)) {
5647 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005648 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005649 } else if (Complained)
5650 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005651 break;
5652 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005653
5654 case SK_StringInit: {
5655 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005656 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005657 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005658 break;
5659 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005660
5661 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005662 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005663 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005664 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005665 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005666
5667 case SK_ArrayInit:
5668 // Okay: we checked everything before creating this step. Note that
5669 // this is a GNU extension.
5670 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005671 << Step->Type << CurInit.get()->getType()
5672 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005673
5674 // If the destination type is an incomplete array type, update the
5675 // type accordingly.
5676 if (ResultType) {
5677 if (const IncompleteArrayType *IncompleteDest
5678 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5679 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005680 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005681 *ResultType = S.Context.getConstantArrayType(
5682 IncompleteDest->getElementType(),
5683 ConstantSource->getSize(),
5684 ArrayType::Normal, 0);
5685 }
5686 }
5687 }
John McCallf85e1932011-06-15 23:02:42 +00005688 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005689
Richard Smith0f163e92012-02-15 22:38:09 +00005690 case SK_ParenthesizedArrayInit:
5691 // Okay: we checked everything before creating this step. Note that
5692 // this is a GNU extension.
5693 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5694 << CurInit.get()->getSourceRange();
5695 break;
5696
John McCallf85e1932011-06-15 23:02:42 +00005697 case SK_PassByIndirectCopyRestore:
5698 case SK_PassByIndirectRestore:
5699 checkIndirectCopyRestoreSource(S, CurInit.get());
5700 CurInit = S.Owned(new (S.Context)
5701 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5702 Step->Kind == SK_PassByIndirectCopyRestore));
5703 break;
5704
5705 case SK_ProduceObjCObject:
5706 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005707 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005708 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005709 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005710
5711 case SK_StdInitializerList: {
5712 QualType Dest = Step->Type;
5713 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005714 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005715 (void)Success;
5716 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005717
5718 // If the element type has a destructor, check it.
5719 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5720 if (!RD->hasIrrelevantDestructor()) {
5721 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5722 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5723 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5724 S.PDiag(diag::err_access_dtor_temp) << E);
Richard Smith82f145d2013-05-04 06:44:46 +00005725 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5726 return ExprError();
Sebastian Redl28357452012-03-05 19:35:43 +00005727 }
5728 }
5729 }
5730
Sebastian Redl2b916b82012-01-17 22:49:42 +00005731 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005732 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5733 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005734 unsigned NumInits = ILE->getNumInits();
5735 SmallVector<Expr*, 16> Converted(NumInits);
5736 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5737 S.Context.getConstantArrayType(E,
5738 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5739 NumInits),
5740 ArrayType::Normal, 0));
5741 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5742 0, HiddenArray);
5743 for (unsigned i = 0; i < NumInits; ++i) {
5744 Element.setElementIndex(i);
5745 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005746 ExprResult Res = S.PerformCopyInitialization(
5747 Element, Init.get()->getExprLoc(), Init,
5748 /*TopLevelOfInitList=*/ true);
Richard Smith2c2f09e2013-05-23 23:20:04 +00005749 if (Res.isInvalid())
5750 return ExprError();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005751 Converted[i] = Res.take();
5752 }
5753 InitListExpr *Semantic = new (S.Context)
5754 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005755 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005756 Semantic->setSyntacticForm(ILE);
5757 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005758 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005759 CurInit = S.Owned(Semantic);
5760 break;
5761 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005762 case SK_OCLSamplerInit: {
5763 assert(Step->Type->isSamplerT() &&
5764 "Sampler initialization on non sampler type.");
5765
5766 QualType SourceType = CurInit.get()->getType();
5767 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5768
5769 if (EntityKind == InitializedEntity::EK_Parameter) {
5770 if (!SourceType->isSamplerT())
5771 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5772 << SourceType;
5773 } else if (EntityKind != InitializedEntity::EK_Variable) {
5774 llvm_unreachable("Invalid EntityKind!");
5775 }
5776
5777 break;
5778 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005779 case SK_OCLZeroEvent: {
5780 assert(Step->Type->isEventT() &&
5781 "Event initialization on non event type.");
5782
5783 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5784 CK_ZeroToOCLEvent,
5785 CurInit.get()->getValueKind());
5786 break;
5787 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005788 }
5789 }
John McCall15d7d122010-11-11 03:21:53 +00005790
5791 // Diagnose non-fatal problems with the completed initialization.
5792 if (Entity.getKind() == InitializedEntity::EK_Member &&
5793 cast<FieldDecl>(Entity.getDecl())->isBitField())
5794 S.CheckBitFieldInitialization(Kind.getLocation(),
5795 cast<FieldDecl>(Entity.getDecl()),
5796 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005797
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005798 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005799}
5800
Richard Smithd5bc8672012-12-08 02:01:17 +00005801/// Somewhere within T there is an uninitialized reference subobject.
5802/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005803static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5804 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005805 if (T->isReferenceType()) {
5806 S.Diag(Loc, diag::err_reference_without_init)
5807 << T.getNonReferenceType();
5808 return true;
5809 }
5810
5811 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5812 if (!RD || !RD->hasUninitializedReferenceMember())
5813 return false;
5814
5815 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5816 FE = RD->field_end(); FI != FE; ++FI) {
5817 if (FI->isUnnamedBitfield())
5818 continue;
5819
5820 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5821 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5822 return true;
5823 }
5824 }
5825
5826 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5827 BE = RD->bases_end();
5828 BI != BE; ++BI) {
5829 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5830 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5831 return true;
5832 }
5833 }
5834
5835 return false;
5836}
5837
5838
Douglas Gregor20093b42009-12-09 23:02:17 +00005839//===----------------------------------------------------------------------===//
5840// Diagnose initialization failures
5841//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00005842
5843/// Emit notes associated with an initialization that failed due to a
5844/// "simple" conversion failure.
5845static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5846 Expr *op) {
5847 QualType destType = entity.getType();
5848 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5849 op->getType()->isObjCObjectPointerType()) {
5850
5851 // Emit a possible note about the conversion failing because the
5852 // operand is a message send with a related result type.
5853 S.EmitRelatedResultTypeNote(op);
5854
5855 // Emit a possible note about a return failing because we're
5856 // expecting a related result type.
5857 if (entity.getKind() == InitializedEntity::EK_Result)
5858 S.EmitRelatedResultTypeNoteForReturn(destType);
5859 }
5860}
5861
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005862bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005863 const InitializedEntity &Entity,
5864 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005865 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005866 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005867 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005868
Douglas Gregord6542d82009-12-22 15:35:07 +00005869 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005870 switch (Failure) {
5871 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005872 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005873 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005874 // Dig out the reference subobject which is uninitialized and diagnose it.
5875 // If this is value-initialization, this could be nested some way within
5876 // the target type.
5877 assert(Kind.getKind() == InitializationKind::IK_Value ||
5878 DestType->isReferenceType());
5879 bool Diagnosed =
5880 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5881 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5882 (void)Diagnosed;
5883 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005884 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005885 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005886 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005887
Douglas Gregor20093b42009-12-09 23:02:17 +00005888 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00005889 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00005890 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00005891 case FK_ArrayNeedsInitListOrStringLiteral:
5892 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
5893 break;
5894 case FK_ArrayNeedsInitListOrWideStringLiteral:
5895 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
5896 break;
5897 case FK_NarrowStringIntoWideCharArray:
5898 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
5899 break;
5900 case FK_WideStringIntoCharArray:
5901 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
5902 break;
5903 case FK_IncompatWideStringIntoWideChar:
5904 S.Diag(Kind.getLocation(),
5905 diag::err_array_init_incompat_wide_string_into_wchar);
5906 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005907 case FK_ArrayTypeMismatch:
5908 case FK_NonConstantArrayInit:
5909 S.Diag(Kind.getLocation(),
5910 (Failure == FK_ArrayTypeMismatch
5911 ? diag::err_array_init_different_type
5912 : diag::err_array_init_non_constant_array))
5913 << DestType.getNonReferenceType()
5914 << Args[0]->getType()
5915 << Args[0]->getSourceRange();
5916 break;
5917
John McCall73076432012-01-05 00:13:19 +00005918 case FK_VariableLengthArrayHasInitializer:
5919 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5920 << Args[0]->getSourceRange();
5921 break;
5922
John McCall6bb80172010-03-30 21:47:33 +00005923 case FK_AddressOfOverloadFailed: {
5924 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005925 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005926 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005927 true,
5928 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005929 break;
John McCall6bb80172010-03-30 21:47:33 +00005930 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005931
Douglas Gregor20093b42009-12-09 23:02:17 +00005932 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005933 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005934 switch (FailedOverloadResult) {
5935 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005936 if (Failure == FK_UserConversionOverloadFailed)
5937 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5938 << Args[0]->getType() << DestType
5939 << Args[0]->getSourceRange();
5940 else
5941 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5942 << DestType << Args[0]->getType()
5943 << Args[0]->getSourceRange();
5944
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005945 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005946 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005947
Douglas Gregor20093b42009-12-09 23:02:17 +00005948 case OR_No_Viable_Function:
5949 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5950 << Args[0]->getType() << DestType.getNonReferenceType()
5951 << Args[0]->getSourceRange();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005952 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005953 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005954
Douglas Gregor20093b42009-12-09 23:02:17 +00005955 case OR_Deleted: {
5956 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5957 << Args[0]->getType() << DestType.getNonReferenceType()
5958 << Args[0]->getSourceRange();
5959 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005960 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005961 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5962 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005963 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005964 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005965 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005966 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005967 }
5968 break;
5969 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005970
Douglas Gregor20093b42009-12-09 23:02:17 +00005971 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005972 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005973 }
5974 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005975
Douglas Gregor20093b42009-12-09 23:02:17 +00005976 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005977 if (isa<InitListExpr>(Args[0])) {
5978 S.Diag(Kind.getLocation(),
5979 diag::err_lvalue_reference_bind_to_initlist)
5980 << DestType.getNonReferenceType().isVolatileQualified()
5981 << DestType.getNonReferenceType()
5982 << Args[0]->getSourceRange();
5983 break;
5984 }
5985 // Intentional fallthrough
5986
Douglas Gregor20093b42009-12-09 23:02:17 +00005987 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005988 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005989 Failure == FK_NonConstLValueReferenceBindingToTemporary
5990 ? diag::err_lvalue_reference_bind_to_temporary
5991 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005992 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005993 << DestType.getNonReferenceType()
5994 << Args[0]->getType()
5995 << Args[0]->getSourceRange();
5996 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005997
Douglas Gregor20093b42009-12-09 23:02:17 +00005998 case FK_RValueReferenceBindingToLValue:
5999 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00006000 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00006001 << Args[0]->getSourceRange();
6002 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006003
Douglas Gregor20093b42009-12-09 23:02:17 +00006004 case FK_ReferenceInitDropsQualifiers:
6005 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6006 << DestType.getNonReferenceType()
6007 << Args[0]->getType()
6008 << Args[0]->getSourceRange();
6009 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006010
Douglas Gregor20093b42009-12-09 23:02:17 +00006011 case FK_ReferenceInitFailed:
6012 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6013 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006014 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006015 << Args[0]->getType()
6016 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006017 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006018 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006019
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006020 case FK_ConversionFailed: {
6021 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006022 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006023 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006024 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006025 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006026 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006027 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006028 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6029 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006030 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006031 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006032 }
John Wiegley429bb272011-04-08 18:41:53 +00006033
6034 case FK_ConversionFromPropertyFailed:
6035 // No-op. This error has already been reported.
6036 break;
6037
Douglas Gregord87b61f2009-12-10 17:56:55 +00006038 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006039 SourceRange R;
6040
6041 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006042 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006043 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006044 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006045 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006046
Douglas Gregor19311e72010-09-08 21:40:08 +00006047 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6048 if (Kind.isCStyleOrFunctionalCast())
6049 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6050 << R;
6051 else
6052 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6053 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006054 break;
6055 }
6056
6057 case FK_ReferenceBindingToInitList:
6058 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6059 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6060 break;
6061
6062 case FK_InitListBadDestinationType:
6063 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6064 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6065 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006066
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006067 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006068 case FK_ConstructorOverloadFailed: {
6069 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006070 if (Args.size())
6071 ArgsRange = SourceRange(Args.front()->getLocStart(),
6072 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006073
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006074 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006075 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006076 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006077 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006078 }
6079
Douglas Gregor51c56d62009-12-14 20:49:26 +00006080 // FIXME: Using "DestType" for the entity we're printing is probably
6081 // bad.
6082 switch (FailedOverloadResult) {
6083 case OR_Ambiguous:
6084 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6085 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006086 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006087 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006088
Douglas Gregor51c56d62009-12-14 20:49:26 +00006089 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006090 if (Kind.getKind() == InitializationKind::IK_Default &&
6091 (Entity.getKind() == InitializedEntity::EK_Base ||
6092 Entity.getKind() == InitializedEntity::EK_Member) &&
6093 isa<CXXConstructorDecl>(S.CurContext)) {
6094 // This is implicit default initialization of a member or
6095 // base within a constructor. If no viable function was
6096 // found, notify the user that she needs to explicitly
6097 // initialize this base/member.
6098 CXXConstructorDecl *Constructor
6099 = cast<CXXConstructorDecl>(S.CurContext);
6100 if (Entity.getKind() == InitializedEntity::EK_Base) {
6101 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006102 << (Constructor->getInheritedConstructor() ? 2 :
6103 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006104 << S.Context.getTypeDeclType(Constructor->getParent())
6105 << /*base=*/0
6106 << Entity.getType();
6107
6108 RecordDecl *BaseDecl
6109 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6110 ->getDecl();
6111 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6112 << S.Context.getTagDeclType(BaseDecl);
6113 } else {
6114 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006115 << (Constructor->getInheritedConstructor() ? 2 :
6116 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006117 << S.Context.getTypeDeclType(Constructor->getParent())
6118 << /*member=*/1
6119 << Entity.getName();
6120 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6121
6122 if (const RecordType *Record
6123 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006124 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006125 diag::note_previous_decl)
6126 << S.Context.getTagDeclType(Record->getDecl());
6127 }
6128 break;
6129 }
6130
Douglas Gregor51c56d62009-12-14 20:49:26 +00006131 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6132 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006133 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006134 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006135
Douglas Gregor51c56d62009-12-14 20:49:26 +00006136 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006137 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006138 OverloadingResult Ovl
6139 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006140 if (Ovl != OR_Deleted) {
6141 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6142 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006143 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006144 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006145 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006146
6147 // If this is a defaulted or implicitly-declared function, then
6148 // it was implicitly deleted. Make it clear that the deletion was
6149 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006150 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006151 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006152 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006153 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006154 else
6155 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6156 << true << DestType << ArgsRange;
6157
6158 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006159 break;
6160 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006161
Douglas Gregor51c56d62009-12-14 20:49:26 +00006162 case OR_Success:
6163 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006164 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006165 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006166 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006167
Douglas Gregor99a2e602009-12-16 01:38:02 +00006168 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006169 if (Entity.getKind() == InitializedEntity::EK_Member &&
6170 isa<CXXConstructorDecl>(S.CurContext)) {
6171 // This is implicit default-initialization of a const member in
6172 // a constructor. Complain that it needs to be explicitly
6173 // initialized.
6174 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6175 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006176 << (Constructor->getInheritedConstructor() ? 2 :
6177 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006178 << S.Context.getTypeDeclType(Constructor->getParent())
6179 << /*const=*/1
6180 << Entity.getName();
6181 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6182 << Entity.getName();
6183 } else {
6184 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6185 << DestType << (bool)DestType->getAs<RecordType>();
6186 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006187 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006188
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006189 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006190 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006191 diag::err_init_incomplete_type);
6192 break;
6193
Sebastian Redl14b0c192011-09-24 17:48:00 +00006194 case FK_ListInitializationFailed: {
6195 // Run the init list checker again to emit diagnostics.
6196 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6197 QualType DestType = Entity.getType();
6198 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00006199 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00006200 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00006201 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006202 assert(DiagnoseInitList.HadError() &&
6203 "Inconsistent init list check result.");
6204 break;
6205 }
John McCall5acb0c92011-10-17 18:40:02 +00006206
6207 case FK_PlaceholderType: {
6208 // FIXME: Already diagnosed!
6209 break;
6210 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006211
6212 case FK_InitListElementCopyFailure: {
6213 // Try to perform all copies again.
6214 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6215 unsigned NumInits = InitList->getNumInits();
6216 QualType DestType = Entity.getType();
6217 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006218 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006219 (void)Success;
6220 assert(Success && "Where did the std::initializer_list go?");
6221 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6222 S.Context.getConstantArrayType(E,
6223 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6224 NumInits),
6225 ArrayType::Normal, 0));
6226 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6227 0, HiddenArray);
6228 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6229 // where the init list type is wrong, e.g.
6230 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6231 // FIXME: Emit a note if we hit the limit?
6232 int ErrorCount = 0;
6233 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6234 Element.setElementIndex(i);
6235 ExprResult Init = S.Owned(InitList->getInit(i));
6236 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6237 .isInvalid())
6238 ++ErrorCount;
6239 }
6240 break;
6241 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006242
6243 case FK_ExplicitConstructor: {
6244 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6245 << Args[0]->getSourceRange();
6246 OverloadCandidateSet::iterator Best;
6247 OverloadingResult Ovl
6248 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006249 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006250 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6251 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6252 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6253 break;
6254 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006256
Douglas Gregora41a8c52010-04-22 00:20:18 +00006257 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006258 return true;
6259}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006260
Chris Lattner5f9e2722011-07-23 10:55:15 +00006261void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006262 switch (SequenceKind) {
6263 case FailedSequence: {
6264 OS << "Failed sequence: ";
6265 switch (Failure) {
6266 case FK_TooManyInitsForReference:
6267 OS << "too many initializers for reference";
6268 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006269
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006270 case FK_ArrayNeedsInitList:
6271 OS << "array requires initializer list";
6272 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006273
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006274 case FK_ArrayNeedsInitListOrStringLiteral:
6275 OS << "array requires initializer list or string literal";
6276 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006277
Hans Wennborg0ff50742013-05-15 11:03:04 +00006278 case FK_ArrayNeedsInitListOrWideStringLiteral:
6279 OS << "array requires initializer list or wide string literal";
6280 break;
6281
6282 case FK_NarrowStringIntoWideCharArray:
6283 OS << "narrow string into wide char array";
6284 break;
6285
6286 case FK_WideStringIntoCharArray:
6287 OS << "wide string into char array";
6288 break;
6289
6290 case FK_IncompatWideStringIntoWideChar:
6291 OS << "incompatible wide string into wide char array";
6292 break;
6293
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006294 case FK_ArrayTypeMismatch:
6295 OS << "array type mismatch";
6296 break;
6297
6298 case FK_NonConstantArrayInit:
6299 OS << "non-constant array initializer";
6300 break;
6301
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006302 case FK_AddressOfOverloadFailed:
6303 OS << "address of overloaded function failed";
6304 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006305
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006306 case FK_ReferenceInitOverloadFailed:
6307 OS << "overload resolution for reference initialization failed";
6308 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006309
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006310 case FK_NonConstLValueReferenceBindingToTemporary:
6311 OS << "non-const lvalue reference bound to temporary";
6312 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006313
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006314 case FK_NonConstLValueReferenceBindingToUnrelated:
6315 OS << "non-const lvalue reference bound to unrelated type";
6316 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006317
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006318 case FK_RValueReferenceBindingToLValue:
6319 OS << "rvalue reference bound to an lvalue";
6320 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006321
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006322 case FK_ReferenceInitDropsQualifiers:
6323 OS << "reference initialization drops qualifiers";
6324 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006325
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006326 case FK_ReferenceInitFailed:
6327 OS << "reference initialization failed";
6328 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006329
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006330 case FK_ConversionFailed:
6331 OS << "conversion failed";
6332 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006333
John Wiegley429bb272011-04-08 18:41:53 +00006334 case FK_ConversionFromPropertyFailed:
6335 OS << "conversion from property failed";
6336 break;
6337
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006338 case FK_TooManyInitsForScalar:
6339 OS << "too many initializers for scalar";
6340 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006341
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006342 case FK_ReferenceBindingToInitList:
6343 OS << "referencing binding to initializer list";
6344 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006345
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006346 case FK_InitListBadDestinationType:
6347 OS << "initializer list for non-aggregate, non-scalar type";
6348 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006349
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006350 case FK_UserConversionOverloadFailed:
6351 OS << "overloading failed for user-defined conversion";
6352 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006353
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006354 case FK_ConstructorOverloadFailed:
6355 OS << "constructor overloading failed";
6356 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006357
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006358 case FK_DefaultInitOfConst:
6359 OS << "default initialization of a const variable";
6360 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006361
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006362 case FK_Incomplete:
6363 OS << "initialization of incomplete type";
6364 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006365
6366 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006367 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006368 break;
6369
John McCall73076432012-01-05 00:13:19 +00006370 case FK_VariableLengthArrayHasInitializer:
6371 OS << "variable length array has an initializer";
6372 break;
6373
John McCall5acb0c92011-10-17 18:40:02 +00006374 case FK_PlaceholderType:
6375 OS << "initializer expression isn't contextually valid";
6376 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006377
6378 case FK_ListConstructorOverloadFailed:
6379 OS << "list constructor overloading failed";
6380 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006381
6382 case FK_InitListElementCopyFailure:
6383 OS << "copy construction of initializer list element failed";
6384 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006385
6386 case FK_ExplicitConstructor:
6387 OS << "list copy initialization chose explicit constructor";
6388 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006389 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006390 OS << '\n';
6391 return;
6392 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006393
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006394 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006395 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006396 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006397
Sebastian Redl7491c492011-06-05 13:59:11 +00006398 case NormalSequence:
6399 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006400 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006401 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006402
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006403 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6404 if (S != step_begin()) {
6405 OS << " -> ";
6406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006407
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006408 switch (S->Kind) {
6409 case SK_ResolveAddressOfOverloadedFunction:
6410 OS << "resolve address of overloaded function";
6411 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006412
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006413 case SK_CastDerivedToBaseRValue:
6414 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6415 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006416
Sebastian Redl906082e2010-07-20 04:20:21 +00006417 case SK_CastDerivedToBaseXValue:
6418 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6419 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006420
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006421 case SK_CastDerivedToBaseLValue:
6422 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6423 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006424
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006425 case SK_BindReference:
6426 OS << "bind reference to lvalue";
6427 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006428
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006429 case SK_BindReferenceToTemporary:
6430 OS << "bind reference to a temporary";
6431 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006432
Douglas Gregor523d46a2010-04-18 07:40:54 +00006433 case SK_ExtraneousCopyToTemporary:
6434 OS << "extraneous C++03 copy to temporary";
6435 break;
6436
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006437 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006438 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006439 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006440
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006441 case SK_QualificationConversionRValue:
6442 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006443 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006444
Sebastian Redl906082e2010-07-20 04:20:21 +00006445 case SK_QualificationConversionXValue:
6446 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006447 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006448
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006449 case SK_QualificationConversionLValue:
6450 OS << "qualification conversion (lvalue)";
6451 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006452
Jordan Rose1fd1e282013-04-11 00:58:58 +00006453 case SK_LValueToRValue:
6454 OS << "load (lvalue to rvalue)";
6455 break;
6456
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006457 case SK_ConversionSequence:
6458 OS << "implicit conversion sequence (";
6459 S->ICS->DebugPrint(); // FIXME: use OS
6460 OS << ")";
6461 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006462
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006463 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006464 OS << "list aggregate initialization";
6465 break;
6466
6467 case SK_ListConstructorCall:
6468 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006469 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006470
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006471 case SK_UnwrapInitList:
6472 OS << "unwrap reference initializer list";
6473 break;
6474
6475 case SK_RewrapInitList:
6476 OS << "rewrap reference initializer list";
6477 break;
6478
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006479 case SK_ConstructorInitialization:
6480 OS << "constructor initialization";
6481 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006482
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006483 case SK_ZeroInitialization:
6484 OS << "zero initialization";
6485 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006486
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006487 case SK_CAssignment:
6488 OS << "C assignment";
6489 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006490
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006491 case SK_StringInit:
6492 OS << "string initialization";
6493 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006494
6495 case SK_ObjCObjectConversion:
6496 OS << "Objective-C object conversion";
6497 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006498
6499 case SK_ArrayInit:
6500 OS << "array initialization";
6501 break;
John McCallf85e1932011-06-15 23:02:42 +00006502
Richard Smith0f163e92012-02-15 22:38:09 +00006503 case SK_ParenthesizedArrayInit:
6504 OS << "parenthesized array initialization";
6505 break;
6506
John McCallf85e1932011-06-15 23:02:42 +00006507 case SK_PassByIndirectCopyRestore:
6508 OS << "pass by indirect copy and restore";
6509 break;
6510
6511 case SK_PassByIndirectRestore:
6512 OS << "pass by indirect restore";
6513 break;
6514
6515 case SK_ProduceObjCObject:
6516 OS << "Objective-C object retension";
6517 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006518
6519 case SK_StdInitializerList:
6520 OS << "std::initializer_list from initializer list";
6521 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006522
Guy Benyei21f18c42013-02-07 10:55:47 +00006523 case SK_OCLSamplerInit:
6524 OS << "OpenCL sampler_t from integer constant";
6525 break;
6526
Guy Benyeie6b9d802013-01-20 12:31:11 +00006527 case SK_OCLZeroEvent:
6528 OS << "OpenCL event_t from zero";
6529 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006530 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006531
6532 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006533 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006534
6535 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006536}
6537
6538void InitializationSequence::dump() const {
6539 dump(llvm::errs());
6540}
6541
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006542static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6543 QualType EntityType,
6544 const Expr *PreInit,
6545 const Expr *PostInit) {
6546 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6547 return;
6548
6549 // A narrowing conversion can only appear as the final implicit conversion in
6550 // an initialization sequence.
6551 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6552 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6553 return;
6554
6555 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6556 const StandardConversionSequence *SCS = 0;
6557 switch (ICS.getKind()) {
6558 case ImplicitConversionSequence::StandardConversion:
6559 SCS = &ICS.Standard;
6560 break;
6561 case ImplicitConversionSequence::UserDefinedConversion:
6562 SCS = &ICS.UserDefined.After;
6563 break;
6564 case ImplicitConversionSequence::AmbiguousConversion:
6565 case ImplicitConversionSequence::EllipsisConversion:
6566 case ImplicitConversionSequence::BadConversion:
6567 return;
6568 }
6569
6570 // Determine the type prior to the narrowing conversion. If a conversion
6571 // operator was used, this may be different from both the type of the entity
6572 // and of the pre-initialization expression.
6573 QualType PreNarrowingType = PreInit->getType();
6574 if (Seq.step_begin() + 1 != Seq.step_end())
6575 PreNarrowingType = Seq.step_end()[-2].Type;
6576
6577 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6578 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006579 QualType ConstantType;
6580 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6581 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006582 case NK_Not_Narrowing:
6583 // No narrowing occurred.
6584 return;
6585
6586 case NK_Type_Narrowing:
6587 // This was a floating-to-integer conversion, which is always considered a
6588 // narrowing conversion even if the value is a constant and can be
6589 // represented exactly as an integer.
6590 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006591 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006592 diag::warn_init_list_type_narrowing
6593 : S.isSFINAEContext()?
6594 diag::err_init_list_type_narrowing_sfinae
6595 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006596 << PostInit->getSourceRange()
6597 << PreNarrowingType.getLocalUnqualifiedType()
6598 << EntityType.getLocalUnqualifiedType();
6599 break;
6600
6601 case NK_Constant_Narrowing:
6602 // A constant value was narrowed.
6603 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006604 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006605 diag::warn_init_list_constant_narrowing
6606 : S.isSFINAEContext()?
6607 diag::err_init_list_constant_narrowing_sfinae
6608 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006609 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006610 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006611 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006612 break;
6613
6614 case NK_Variable_Narrowing:
6615 // A variable's value may have been narrowed.
6616 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006617 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006618 diag::warn_init_list_variable_narrowing
6619 : S.isSFINAEContext()?
6620 diag::err_init_list_variable_narrowing_sfinae
6621 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006622 << PostInit->getSourceRange()
6623 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006624 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006625 break;
6626 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006627
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006628 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006629 llvm::raw_svector_ostream OS(StaticCast);
6630 OS << "static_cast<";
6631 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6632 // It's important to use the typedef's name if there is one so that the
6633 // fixit doesn't break code using types like int64_t.
6634 //
6635 // FIXME: This will break if the typedef requires qualification. But
6636 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006637 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006638 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006639 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006640 else {
6641 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6642 // with a broken cast.
6643 return;
6644 }
6645 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006646 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6647 << PostInit->getSourceRange()
6648 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006649 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006650 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006651}
6652
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006653//===----------------------------------------------------------------------===//
6654// Initialization helper functions
6655//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006656bool
6657Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6658 ExprResult Init) {
6659 if (Init.isInvalid())
6660 return false;
6661
6662 Expr *InitE = Init.get();
6663 assert(InitE && "No initialization expression");
6664
Douglas Gregor3c394c52012-07-31 22:15:04 +00006665 InitializationKind Kind
6666 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006667 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006668 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006669}
6670
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006671ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006672Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6673 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006674 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006675 bool TopLevelOfInitList,
6676 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006677 if (Init.isInvalid())
6678 return ExprError();
6679
John McCall15d7d122010-11-11 03:21:53 +00006680 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006681 assert(InitE && "No initialization expression?");
6682
6683 if (EqualLoc.isInvalid())
6684 EqualLoc = InitE->getLocStart();
6685
6686 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006687 EqualLoc,
6688 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006689 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006690 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006691
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006692 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006693
6694 if (!Result.isInvalid() && TopLevelOfInitList)
6695 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6696 InitE, Result.get());
6697
6698 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006699}