blob: 60c67cd38bbe5fde13fb2f603b0288480b09fd9d [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
Benjamin Kramera7894162012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000249 unsigned &StructuredIndex,
250 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000251 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000252 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000253 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000254 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000255 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000256 unsigned &StructuredIndex,
257 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000258 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000259 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000260 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000261 InitListExpr *StructuredList,
262 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000263 void CheckComplexType(const InitializedEntity &Entity,
264 InitListExpr *IList, QualType DeclType,
265 unsigned &Index,
266 InitListExpr *StructuredList,
267 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000268 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000269 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000270 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000271 InitListExpr *StructuredList,
272 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000273 void CheckReferenceType(const InitializedEntity &Entity,
274 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000275 unsigned &Index,
276 InitListExpr *StructuredList,
277 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000278 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000279 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000280 InitListExpr *StructuredList,
281 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000282 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000283 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000284 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000285 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000286 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000287 unsigned &StructuredIndex,
288 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000289 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000290 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000291 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000292 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000293 InitListExpr *StructuredList,
294 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000295 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000296 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000297 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000298 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000299 RecordDecl::field_iterator *NextField,
300 llvm::APSInt *NextElementIndex,
301 unsigned &Index,
302 InitListExpr *StructuredList,
303 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000304 bool FinishSubobjectInit,
305 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000306 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
307 QualType CurrentObjectType,
308 InitListExpr *StructuredList,
309 unsigned StructuredIndex,
310 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000311 void UpdateStructuredListElement(InitListExpr *StructuredList,
312 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000313 Expr *expr);
314 int numArrayElements(QualType DeclType);
315 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000316
Douglas Gregord6d37de2009-12-22 00:05:34 +0000317 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
318 const InitializedEntity &ParentEntity,
319 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000320 void FillInValueInitializations(const InitializedEntity &Entity,
321 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000322 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
323 Expr *InitExpr, FieldDecl *Field,
324 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000325 void CheckValueInitializable(const InitializedEntity &Entity);
326
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000327public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smith40cba902013-06-06 11:41:05 +0000329 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000330 bool HadError() { return hadError; }
331
332 // @brief Retrieves the fully-structured initializer list used for
333 // semantic analysis and code generation.
334 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
335};
Chris Lattner8b419b92009-02-24 22:48:58 +0000336} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000337
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000338void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
339 assert(VerifyOnly &&
340 "CheckValueInitializable is only inteded for verification mode.");
341
342 SourceLocation Loc;
343 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
344 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000345 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000346 if (InitSeq.Failed())
347 hadError = true;
348}
349
Douglas Gregord6d37de2009-12-22 00:05:34 +0000350void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
351 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000352 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000353 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000354 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000355 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000356 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000357 = InitializedEntity::InitializeMember(Field, &ParentEntity);
358 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000359 // If there's no explicit initializer but we have a default initializer, use
360 // that. This only happens in C++1y, since classes with default
361 // initializers are not aggregates in C++11.
362 if (Field->hasInClassInitializer()) {
363 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
364 ILE->getRBraceLoc(), Field);
365 if (Init < NumInits)
366 ILE->setInit(Init, DIE);
367 else {
368 ILE->updateInit(SemaRef.Context, Init, DIE);
369 RequiresSecondPass = true;
370 }
371 return;
372 }
373
Douglas Gregord6d37de2009-12-22 00:05:34 +0000374 // FIXME: We probably don't need to handle references
375 // specially here, since value-initialization of references is
376 // handled in InitializationSequence.
377 if (Field->getType()->isReferenceType()) {
378 // C++ [dcl.init.aggr]p9:
379 // If an incomplete or empty initializer-list leaves a
380 // member of reference type uninitialized, the program is
381 // ill-formed.
382 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
383 << Field->getType()
384 << ILE->getSyntacticForm()->getSourceRange();
385 SemaRef.Diag(Field->getLocation(),
386 diag::note_uninit_reference_member);
387 hadError = true;
388 return;
389 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390
Douglas Gregord6d37de2009-12-22 00:05:34 +0000391 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
392 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000393 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000394 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000395 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000396 hadError = true;
397 return;
398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000399
John McCall60d7b3a2010-08-24 06:29:42 +0000400 ExprResult MemberInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000401 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000402 if (MemberInit.isInvalid()) {
403 hadError = true;
404 return;
405 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406
Douglas Gregord6d37de2009-12-22 00:05:34 +0000407 if (hadError) {
408 // Do nothing
409 } else if (Init < NumInits) {
410 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000411 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000412 // Value-initialization requires a constructor call, so
413 // extend the initializer list to include the constructor
414 // call and make a note that we'll need to take another pass
415 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000416 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000417 RequiresSecondPass = true;
418 }
419 } else if (InitListExpr *InnerILE
420 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000421 FillInValueInitializations(MemberEntity, InnerILE,
422 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000423}
424
Douglas Gregor4c678342009-01-28 21:54:33 +0000425/// Recursively replaces NULL values within the given initializer list
426/// with expressions that perform value-initialization of the
427/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000428void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000429InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
430 InitListExpr *ILE,
431 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000432 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000433 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000434 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000435 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000436 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Ted Kremenek6217b802009-07-29 21:53:49 +0000438 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000439 const RecordDecl *RDecl = RType->getDecl();
440 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000441 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
442 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000443 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
444 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
445 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
446 FieldEnd = RDecl->field_end();
447 Field != FieldEnd; ++Field) {
448 if (Field->hasInClassInitializer()) {
449 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
450 break;
451 }
452 }
453 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000454 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000455 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
456 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000457 Field != FieldEnd; ++Field) {
458 if (Field->isUnnamedBitfield())
459 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000460
Douglas Gregord6d37de2009-12-22 00:05:34 +0000461 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000462 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000463
David Blaikie581deb32012-06-06 20:45:41 +0000464 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000465 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000466 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000467
Douglas Gregord6d37de2009-12-22 00:05:34 +0000468 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000469
Douglas Gregord6d37de2009-12-22 00:05:34 +0000470 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000471 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000472 break;
473 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000474 }
475
476 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000477 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000478
479 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000481 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000482 unsigned NumInits = ILE->getNumInits();
483 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000484 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000485 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000486 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
487 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000488 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000489 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000490 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000491 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000492 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000493 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000494 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000495 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000496 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000497
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000498
Douglas Gregor87fd7032009-02-02 17:43:21 +0000499 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000500 if (hadError)
501 return;
502
Anders Carlssond3d824d2010-01-23 04:34:47 +0000503 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
504 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000505 ElementEntity.setElementIndex(Init);
506
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000507 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
508 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000509 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
510 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000511 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000512 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000513 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000514 hadError = true;
515 return;
516 }
517
John McCall60d7b3a2010-08-24 06:29:42 +0000518 ExprResult ElementInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000519 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000520 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000521 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000522 return;
523 }
524
525 if (hadError) {
526 // Do nothing
527 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000528 // For arrays, just set the expression used for value-initialization
529 // of the "holes" in the array.
530 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
531 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
532 else
533 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000534 } else {
535 // For arrays, just set the expression used for value-initialization
536 // of the rest of elements and exit.
537 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
538 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
539 return;
540 }
541
Sebastian Redl7491c492011-06-05 13:59:11 +0000542 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000543 // Value-initialization requires a constructor call, so
544 // extend the initializer list to include the constructor
545 // call and make a note that we'll need to take another pass
546 // through the initializer list.
547 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
548 RequiresSecondPass = true;
549 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000550 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000551 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000552 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000553 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000554 }
555}
556
Chris Lattner68355a52009-01-29 05:10:57 +0000557
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000558InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000559 InitListExpr *IL, QualType &T,
Richard Smith40cba902013-06-06 11:41:05 +0000560 bool VerifyOnly)
561 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000562 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000563
Eli Friedmanb85f7072008-05-19 19:16:24 +0000564 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000565 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000566 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000567 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000569 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000570 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000571
Sebastian Redl14b0c192011-09-24 17:48:00 +0000572 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000573 bool RequiresSecondPass = false;
574 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000575 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000576 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000577 RequiresSecondPass);
578 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000579}
580
581int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000582 // FIXME: use a proper constant
583 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000584 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000585 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000586 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
587 }
588 return maxElements;
589}
590
591int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000592 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000593 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000594 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000595 Field = structDecl->field_begin(),
596 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000597 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000598 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000599 ++InitializableMembers;
600 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000601 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000602 return std::min(InitializableMembers, 1);
603 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000604}
605
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000606void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000607 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000608 QualType T, unsigned &Index,
609 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000610 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000611 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Steve Naroff0cca7492008-05-01 22:18:59 +0000613 if (T->isArrayType())
614 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000615 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000616 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000617 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000618 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000619 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000620 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000621
Eli Friedman402256f2008-05-25 13:49:22 +0000622 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000623 if (!VerifyOnly)
624 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
625 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000626 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000627 hadError = true;
628 return;
629 }
630
Douglas Gregor4c678342009-01-28 21:54:33 +0000631 // Build a structured initializer list corresponding to this subobject.
632 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000633 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
634 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000635 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000636 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000637 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000638
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000640 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000641 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000642 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000643 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000644 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000645
Richard Smith40cba902013-06-06 11:41:05 +0000646 if (!VerifyOnly) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000647 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000648
Sebastian Redlc2235182011-10-16 18:19:28 +0000649 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000650 // Update the structured sub-object initializer so that it's ending
651 // range corresponds with the end of the last initializer it used.
652 if (EndIndex < ParentIList->getNumInits()) {
653 SourceLocation EndLoc
654 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
655 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
656 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000657
Sebastian Redlc2235182011-10-16 18:19:28 +0000658 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000659 if (T->isArrayType() || T->isRecordType()) {
660 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smith40cba902013-06-06 11:41:05 +0000661 diag::warn_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000662 << StructuredSubobjectInitList->getSourceRange()
663 << FixItHint::CreateInsertion(
664 StructuredSubobjectInitList->getLocStart(), "{")
665 << FixItHint::CreateInsertion(
666 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000667 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000668 "}");
669 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000670 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000671}
672
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000673void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000674 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000675 unsigned &Index,
676 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000677 unsigned &StructuredIndex,
678 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000679 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000680 if (!VerifyOnly) {
681 SyntacticToSemantic[IList] = StructuredList;
682 StructuredList->setSyntacticForm(IList);
683 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000685 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000686 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000687 QualType ExprTy = T;
688 if (!ExprTy->isArrayType())
689 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000690 IList->setType(ExprTy);
691 StructuredList->setType(ExprTy);
692 }
Eli Friedman638e1442008-05-25 13:22:35 +0000693 if (hadError)
694 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000695
Eli Friedman638e1442008-05-25 13:22:35 +0000696 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000697 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000698 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000699 if (SemaRef.getLangOpts().CPlusPlus ||
700 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000701 IList->getType()->isVectorType())) {
702 hadError = true;
703 }
704 return;
705 }
706
Eli Friedmane5408582009-05-29 20:20:05 +0000707 if (StructuredIndex == 1 &&
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000708 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
709 SIF_None) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000710 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000711 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000712 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000713 hadError = true;
714 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000715 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000716 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000717 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000718 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000719 // Don't complain for incomplete types, since we'll get an error
720 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000721 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000722 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000723 CurrentObjectType->isArrayType()? 0 :
724 CurrentObjectType->isVectorType()? 1 :
725 CurrentObjectType->isScalarType()? 2 :
726 CurrentObjectType->isUnionType()? 3 :
727 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000728
729 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000730 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000731 DK = diag::err_excess_initializers;
732 hadError = true;
733 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000734 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000735 DK = diag::err_excess_initializers;
736 hadError = true;
737 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000738
Chris Lattner08202542009-02-24 22:50:46 +0000739 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000740 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000741 }
742 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000743
Sebastian Redl14b0c192011-09-24 17:48:00 +0000744 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
745 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000746 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000747 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000748 << FixItHint::CreateRemoval(IList->getLocStart())
749 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000750}
751
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000752void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000753 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000754 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000755 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000756 unsigned &Index,
757 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000758 unsigned &StructuredIndex,
759 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000760 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
761 // Explicitly braced initializer for complex type can be real+imaginary
762 // parts.
763 CheckComplexType(Entity, IList, DeclType, Index,
764 StructuredList, StructuredIndex);
765 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000766 CheckScalarType(Entity, IList, DeclType, Index,
767 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000768 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000770 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000771 } else if (DeclType->isRecordType()) {
772 assert(DeclType->isAggregateType() &&
773 "non-aggregate records should be handed in CheckSubElementType");
774 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
775 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
776 SubobjectIsDesignatorContext, Index,
777 StructuredList, StructuredIndex,
778 TopLevelObject);
779 } else if (DeclType->isArrayType()) {
780 llvm::APSInt Zero(
781 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
782 false);
783 CheckArrayType(Entity, IList, DeclType, Zero,
784 SubobjectIsDesignatorContext, Index,
785 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000786 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
787 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000788 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000789 if (!VerifyOnly)
790 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
791 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000792 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000793 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000794 CheckReferenceType(Entity, IList, DeclType, Index,
795 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000796 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000797 if (!VerifyOnly)
798 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
799 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000800 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000801 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000802 if (!VerifyOnly)
803 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
804 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000805 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000806 }
807}
808
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000809void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000810 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000811 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000812 unsigned &Index,
813 InitListExpr *StructuredList,
814 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000815 Expr *expr = IList->getInit(Index);
Richard Smith6242a452013-05-31 02:56:17 +0000816
817 if (ElemType->isReferenceType())
818 return CheckReferenceType(Entity, IList, ElemType, Index,
819 StructuredList, StructuredIndex);
820
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000821 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000822 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
823 unsigned newIndex = 0;
824 unsigned newStructuredIndex = 0;
825 InitListExpr *newStructuredList
826 = getStructuredSubobjectInit(IList, Index, ElemType,
827 StructuredList, StructuredIndex,
828 SubInitList->getSourceRange());
829 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
830 newStructuredList, newStructuredIndex);
831 ++StructuredIndex;
832 ++Index;
833 return;
834 }
835 assert(SemaRef.getLangOpts().CPlusPlus &&
836 "non-aggregate records are only possible in C++");
837 // C++ initialization is handled later.
838 }
839
Richard Smith6242a452013-05-31 02:56:17 +0000840 if (ElemType->isScalarType())
John McCallfef8b342011-02-21 07:57:55 +0000841 return CheckScalarType(Entity, IList, ElemType, Index,
842 StructuredList, StructuredIndex);
Anders Carlssond28b4282009-08-27 17:18:13 +0000843
John McCallfef8b342011-02-21 07:57:55 +0000844 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
845 // arrayType can be incomplete if we're initializing a flexible
846 // array member. There's nothing we can do with the completed
847 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000848
Hans Wennborg0ff50742013-05-15 11:03:04 +0000849 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000850 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000851 CheckStringInit(expr, ElemType, arrayType, SemaRef);
852 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000853 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000854 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000855 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000856 }
John McCallfef8b342011-02-21 07:57:55 +0000857
858 // Fall through for subaggregate initialization.
859
David Blaikie4e4d0842012-03-11 07:00:24 +0000860 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000861 // C++ [dcl.init.aggr]p12:
862 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000863 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000864 // an initializer-list. If the initializer can initialize a
865 // member, the member is initialized. [...]
866
867 // FIXME: Better EqualLoc?
868 InitializationKind Kind =
869 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000870 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000871
872 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000873 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000874 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000875 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000876 if (Result.isInvalid())
877 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000878
Sebastian Redl14b0c192011-09-24 17:48:00 +0000879 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000880 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000881 }
John McCallfef8b342011-02-21 07:57:55 +0000882 ++Index;
883 return;
884 }
885
886 // Fall through for subaggregate initialization
887 } else {
888 // C99 6.7.8p13:
889 //
890 // The initializer for a structure or union object that has
891 // automatic storage duration shall be either an initializer
892 // list as described below, or a single expression that has
893 // compatible structure or union type. In the latter case, the
894 // initial value of the object, including unnamed members, is
895 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000896 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000897 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000898 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
899 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000900 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000901 if (ExprRes.isInvalid())
902 hadError = true;
903 else {
904 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000905 if (ExprRes.isInvalid())
906 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000907 }
908 UpdateStructuredListElement(StructuredList, StructuredIndex,
909 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000910 ++Index;
911 return;
912 }
John Wiegley429bb272011-04-08 18:41:53 +0000913 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000914 // Fall through for subaggregate initialization
915 }
916
917 // C++ [dcl.init.aggr]p12:
918 //
919 // [...] Otherwise, if the member is itself a non-empty
920 // subaggregate, brace elision is assumed and the initializer is
921 // considered for the initialization of the first member of
922 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000923 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000924 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000925 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
926 StructuredIndex);
927 ++StructuredIndex;
928 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000929 if (!VerifyOnly) {
930 // We cannot initialize this element, so let
931 // PerformCopyInitialization produce the appropriate diagnostic.
932 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
933 SemaRef.Owned(expr),
934 /*TopLevelOfInitList=*/true);
935 }
John McCallfef8b342011-02-21 07:57:55 +0000936 hadError = true;
937 ++Index;
938 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000939 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000940}
941
Eli Friedman0c706c22011-09-19 23:17:44 +0000942void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
943 InitListExpr *IList, QualType DeclType,
944 unsigned &Index,
945 InitListExpr *StructuredList,
946 unsigned &StructuredIndex) {
947 assert(Index == 0 && "Index in explicit init list must be zero");
948
949 // As an extension, clang supports complex initializers, which initialize
950 // a complex number component-wise. When an explicit initializer list for
951 // a complex number contains two two initializers, this extension kicks in:
952 // it exepcts the initializer list to contain two elements convertible to
953 // the element type of the complex type. The first element initializes
954 // the real part, and the second element intitializes the imaginary part.
955
956 if (IList->getNumInits() != 2)
957 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
958 StructuredIndex);
959
960 // This is an extension in C. (The builtin _Complex type does not exist
961 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000962 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000963 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
964 << IList->getSourceRange();
965
966 // Initialize the complex number.
967 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
968 InitializedEntity ElementEntity =
969 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
970
971 for (unsigned i = 0; i < 2; ++i) {
972 ElementEntity.setElementIndex(Index);
973 CheckSubElementType(ElementEntity, IList, elementType, Index,
974 StructuredList, StructuredIndex);
975 }
976}
977
978
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000979void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000980 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000981 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000982 InitListExpr *StructuredList,
983 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000984 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000985 if (!VerifyOnly)
986 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000987 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000988 diag::warn_cxx98_compat_empty_scalar_initializer :
989 diag::err_empty_scalar_initializer)
990 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000991 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000992 ++Index;
993 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000994 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000995 }
John McCallb934c2d2010-11-11 00:46:36 +0000996
997 Expr *expr = IList->getInit(Index);
998 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000999 if (!VerifyOnly)
1000 SemaRef.Diag(SubIList->getLocStart(),
1001 diag::warn_many_braces_around_scalar_init)
1002 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001003
1004 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1005 StructuredIndex);
1006 return;
1007 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001008 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001009 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001010 diag::err_designator_for_scalar_init)
1011 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001012 hadError = true;
1013 ++Index;
1014 ++StructuredIndex;
1015 return;
1016 }
1017
Sebastian Redl14b0c192011-09-24 17:48:00 +00001018 if (VerifyOnly) {
1019 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1020 hadError = true;
1021 ++Index;
1022 return;
1023 }
1024
John McCallb934c2d2010-11-11 00:46:36 +00001025 ExprResult Result =
1026 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001027 SemaRef.Owned(expr),
1028 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001029
1030 Expr *ResultExpr = 0;
1031
1032 if (Result.isInvalid())
1033 hadError = true; // types weren't compatible.
1034 else {
1035 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001036
John McCallb934c2d2010-11-11 00:46:36 +00001037 if (ResultExpr != expr) {
1038 // The type was promoted, update initializer list.
1039 IList->setInit(Index, ResultExpr);
1040 }
1041 }
1042 if (hadError)
1043 ++StructuredIndex;
1044 else
1045 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1046 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001047}
1048
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001049void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1050 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001051 unsigned &Index,
1052 InitListExpr *StructuredList,
1053 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001054 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001055 // FIXME: It would be wonderful if we could point at the actual member. In
1056 // general, it would be useful to pass location information down the stack,
1057 // so that we know the location (or decl) of the "current object" being
1058 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001059 if (!VerifyOnly)
1060 SemaRef.Diag(IList->getLocStart(),
1061 diag::err_init_reference_member_uninitialized)
1062 << DeclType
1063 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001064 hadError = true;
1065 ++Index;
1066 ++StructuredIndex;
1067 return;
1068 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001069
1070 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001071 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001072 if (!VerifyOnly)
1073 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1074 << DeclType << IList->getSourceRange();
1075 hadError = true;
1076 ++Index;
1077 ++StructuredIndex;
1078 return;
1079 }
1080
1081 if (VerifyOnly) {
1082 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1083 hadError = true;
1084 ++Index;
1085 return;
1086 }
1087
1088 ExprResult Result =
1089 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1090 SemaRef.Owned(expr),
1091 /*TopLevelOfInitList=*/true);
1092
1093 if (Result.isInvalid())
1094 hadError = true;
1095
1096 expr = Result.takeAs<Expr>();
1097 IList->setInit(Index, expr);
1098
1099 if (hadError)
1100 ++StructuredIndex;
1101 else
1102 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1103 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001104}
1105
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001106void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001107 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001108 unsigned &Index,
1109 InitListExpr *StructuredList,
1110 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001111 const VectorType *VT = DeclType->getAs<VectorType>();
1112 unsigned maxElements = VT->getNumElements();
1113 unsigned numEltsInit = 0;
1114 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001115
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001116 if (Index >= IList->getNumInits()) {
1117 // Make sure the element type can be value-initialized.
1118 if (VerifyOnly)
1119 CheckValueInitializable(
1120 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1121 return;
1122 }
1123
David Blaikie4e4d0842012-03-11 07:00:24 +00001124 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001125 // If the initializing element is a vector, try to copy-initialize
1126 // instead of breaking it apart (which is doomed to failure anyway).
1127 Expr *Init = IList->getInit(Index);
1128 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001129 if (VerifyOnly) {
1130 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1131 hadError = true;
1132 ++Index;
1133 return;
1134 }
1135
John McCall20e047a2010-10-30 00:11:39 +00001136 ExprResult Result =
1137 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001138 SemaRef.Owned(Init),
1139 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001140
1141 Expr *ResultExpr = 0;
1142 if (Result.isInvalid())
1143 hadError = true; // types weren't compatible.
1144 else {
1145 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001146
John McCall20e047a2010-10-30 00:11:39 +00001147 if (ResultExpr != Init) {
1148 // The type was promoted, update initializer list.
1149 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001150 }
1151 }
John McCall20e047a2010-10-30 00:11:39 +00001152 if (hadError)
1153 ++StructuredIndex;
1154 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001155 UpdateStructuredListElement(StructuredList, StructuredIndex,
1156 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001157 ++Index;
1158 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001159 }
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCall20e047a2010-10-30 00:11:39 +00001161 InitializedEntity ElementEntity =
1162 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001163
John McCall20e047a2010-10-30 00:11:39 +00001164 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1165 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001166 if (Index >= IList->getNumInits()) {
1167 if (VerifyOnly)
1168 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001169 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001170 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001171
John McCall20e047a2010-10-30 00:11:39 +00001172 ElementEntity.setElementIndex(Index);
1173 CheckSubElementType(ElementEntity, IList, elementType, Index,
1174 StructuredList, StructuredIndex);
1175 }
1176 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001177 }
John McCall20e047a2010-10-30 00:11:39 +00001178
1179 InitializedEntity ElementEntity =
1180 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001181
John McCall20e047a2010-10-30 00:11:39 +00001182 // OpenCL initializers allows vectors to be constructed from vectors.
1183 for (unsigned i = 0; i < maxElements; ++i) {
1184 // Don't attempt to go past the end of the init list
1185 if (Index >= IList->getNumInits())
1186 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001187
John McCall20e047a2010-10-30 00:11:39 +00001188 ElementEntity.setElementIndex(Index);
1189
1190 QualType IType = IList->getInit(Index)->getType();
1191 if (!IType->isVectorType()) {
1192 CheckSubElementType(ElementEntity, IList, elementType, Index,
1193 StructuredList, StructuredIndex);
1194 ++numEltsInit;
1195 } else {
1196 QualType VecType;
1197 const VectorType *IVT = IType->getAs<VectorType>();
1198 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001199
John McCall20e047a2010-10-30 00:11:39 +00001200 if (IType->isExtVectorType())
1201 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1202 else
1203 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001204 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001205 CheckSubElementType(ElementEntity, IList, VecType, Index,
1206 StructuredList, StructuredIndex);
1207 numEltsInit += numIElts;
1208 }
1209 }
1210
1211 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001212 if (numEltsInit != maxElements) {
1213 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001214 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001215 diag::err_vector_incorrect_num_initializers)
1216 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1217 hadError = true;
1218 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001219}
1220
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001221void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001222 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001223 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001224 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001225 unsigned &Index,
1226 InitListExpr *StructuredList,
1227 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001228 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1229
Steve Naroff0cca7492008-05-01 22:18:59 +00001230 // Check for the special-case of initializing an array with a string.
1231 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001232 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1233 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001234 // We place the string literal directly into the resulting
1235 // initializer list. This is the only place where the structure
1236 // of the structured initializer list doesn't match exactly,
1237 // because doing so would involve allocating one character
1238 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001239 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001240 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1241 UpdateStructuredListElement(StructuredList, StructuredIndex,
1242 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001243 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1244 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001245 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001246 return;
1247 }
1248 }
John McCallce6c9b72011-02-21 07:22:22 +00001249 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001250 // Check for VLAs; in standard C it would be possible to check this
1251 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1252 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001253 if (!VerifyOnly)
1254 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1255 diag::err_variable_object_no_init)
1256 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001257 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001258 ++Index;
1259 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001260 return;
1261 }
1262
Douglas Gregor05c13a32009-01-22 00:58:24 +00001263 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001264 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1265 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001266 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001267 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001268 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001269 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001270 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271 maxElementsKnown = true;
1272 }
1273
John McCallce6c9b72011-02-21 07:22:22 +00001274 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001275 while (Index < IList->getNumInits()) {
1276 Expr *Init = IList->getInit(Index);
1277 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001278 // If we're not the subobject that matches up with the '{' for
1279 // the designator, we shouldn't be handling the
1280 // designator. Return immediately.
1281 if (!SubobjectIsDesignatorContext)
1282 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001283
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001284 // Handle this designated initializer. elementIndex will be
1285 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001286 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001287 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001288 StructuredList, StructuredIndex, true,
1289 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001290 hadError = true;
1291 continue;
1292 }
1293
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001294 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001295 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001296 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001297 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001298 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001299
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001300 // If the array is of incomplete type, keep track of the number of
1301 // elements in the initializer.
1302 if (!maxElementsKnown && elementIndex > maxElements)
1303 maxElements = elementIndex;
1304
Douglas Gregor05c13a32009-01-22 00:58:24 +00001305 continue;
1306 }
1307
1308 // If we know the maximum number of elements, and we've already
1309 // hit it, stop consuming elements in the initializer list.
1310 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001311 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001312
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001313 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001314 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001315 Entity);
1316 // Check this element.
1317 CheckSubElementType(ElementEntity, IList, elementType, Index,
1318 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001319 ++elementIndex;
1320
1321 // If the array is of incomplete type, keep track of the number of
1322 // elements in the initializer.
1323 if (!maxElementsKnown && elementIndex > maxElements)
1324 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001325 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001326 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001327 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001328 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001329 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001330 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001331 // Sizing an array implicitly to zero is not allowed by ISO C,
1332 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001333 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001334 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001335 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001336
Mike Stump1eb44332009-09-09 15:08:12 +00001337 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001338 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001339 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001340 if (!hadError && VerifyOnly) {
1341 // Check if there are any members of the array that get value-initialized.
1342 // If so, check if doing that is possible.
1343 // FIXME: This needs to detect holes left by designated initializers too.
1344 if (maxElementsKnown && elementIndex < maxElements)
1345 CheckValueInitializable(InitializedEntity::InitializeElement(
1346 SemaRef.Context, 0, Entity));
1347 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001348}
1349
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001350bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1351 Expr *InitExpr,
1352 FieldDecl *Field,
1353 bool TopLevelObject) {
1354 // Handle GNU flexible array initializers.
1355 unsigned FlexArrayDiag;
1356 if (isa<InitListExpr>(InitExpr) &&
1357 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1358 // Empty flexible array init always allowed as an extension
1359 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001360 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001361 // Disallow flexible array init in C++; it is not required for gcc
1362 // compatibility, and it needs work to IRGen correctly in general.
1363 FlexArrayDiag = diag::err_flexible_array_init;
1364 } else if (!TopLevelObject) {
1365 // Disallow flexible array init on non-top-level object
1366 FlexArrayDiag = diag::err_flexible_array_init;
1367 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1368 // Disallow flexible array init on anything which is not a variable.
1369 FlexArrayDiag = diag::err_flexible_array_init;
1370 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1371 // Disallow flexible array init on local variables.
1372 FlexArrayDiag = diag::err_flexible_array_init;
1373 } else {
1374 // Allow other cases.
1375 FlexArrayDiag = diag::ext_flexible_array_init;
1376 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001377
1378 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001379 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001380 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001381 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001382 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1383 << Field;
1384 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001385
1386 return FlexArrayDiag != diag::ext_flexible_array_init;
1387}
1388
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001389void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001390 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001391 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001392 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001393 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001394 unsigned &Index,
1395 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001396 unsigned &StructuredIndex,
1397 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001398 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Eli Friedmanb85f7072008-05-19 19:16:24 +00001400 // If the record is invalid, some of it's members are invalid. To avoid
1401 // confusion, we forgo checking the intializer for the entire record.
1402 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001403 // Assume it was supposed to consume a single initializer.
1404 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001405 hadError = true;
1406 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001407 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001408
1409 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001410 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001411
1412 // If there's a default initializer, use it.
1413 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1414 if (VerifyOnly)
1415 return;
1416 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1417 Field != FieldEnd; ++Field) {
1418 if (Field->hasInClassInitializer()) {
1419 StructuredList->setInitializedFieldInUnion(*Field);
1420 // FIXME: Actually build a CXXDefaultInitExpr?
1421 return;
1422 }
1423 }
1424 }
1425
1426 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001427 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1428 Field != FieldEnd; ++Field) {
1429 if (Field->getDeclName()) {
1430 if (VerifyOnly)
1431 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001432 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001433 else
David Blaikie581deb32012-06-06 20:45:41 +00001434 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001435 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001436 }
1437 }
1438 return;
1439 }
1440
Douglas Gregor05c13a32009-01-22 00:58:24 +00001441 // If structDecl is a forward declaration, this loop won't do
1442 // anything except look at designated initializers; That's okay,
1443 // because an error should get printed out elsewhere. It might be
1444 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001445 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001446 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001447 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001448 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001449 while (Index < IList->getNumInits()) {
1450 Expr *Init = IList->getInit(Index);
1451
1452 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001453 // If we're not the subobject that matches up with the '{' for
1454 // the designator, we shouldn't be handling the
1455 // designator. Return immediately.
1456 if (!SubobjectIsDesignatorContext)
1457 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001458
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001459 // Handle this designated initializer. Field will be updated to
1460 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001461 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001462 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001463 StructuredList, StructuredIndex,
1464 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001465 hadError = true;
1466
Douglas Gregordfb5e592009-02-12 19:00:39 +00001467 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001468
1469 // Disable check for missing fields when designators are used.
1470 // This matches gcc behaviour.
1471 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001472 continue;
1473 }
1474
1475 if (Field == FieldEnd) {
1476 // We've run out of fields. We're done.
1477 break;
1478 }
1479
Douglas Gregordfb5e592009-02-12 19:00:39 +00001480 // We've already initialized a member of a union. We're done.
1481 if (InitializedSomething && DeclType->isUnionType())
1482 break;
1483
Douglas Gregor44b43212008-12-11 16:49:14 +00001484 // If we've hit the flexible array member at the end, we're done.
1485 if (Field->getType()->isIncompleteArrayType())
1486 break;
1487
Douglas Gregor0bb76892009-01-29 16:53:55 +00001488 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001489 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001490 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001491 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001492 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001493
Douglas Gregor54001c12011-06-29 21:51:31 +00001494 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001495 bool InvalidUse;
1496 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001497 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001498 else
David Blaikie581deb32012-06-06 20:45:41 +00001499 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001500 IList->getInit(Index)->getLocStart());
1501 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001502 ++Index;
1503 ++Field;
1504 hadError = true;
1505 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001506 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001507
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001508 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001509 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001510 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1511 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001512 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001513
Sebastian Redl14b0c192011-09-24 17:48:00 +00001514 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001515 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001516 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001517 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001518
1519 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001520 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001521
John McCall80639de2010-03-11 19:32:38 +00001522 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001523 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1524 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1525 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001526 // It is possible we have one or more unnamed bitfields remaining.
1527 // Find first (if any) named field and emit warning.
1528 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1529 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001530 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001531 SemaRef.Diag(IList->getSourceRange().getEnd(),
1532 diag::warn_missing_field_initializers) << it->getName();
1533 break;
1534 }
1535 }
1536 }
1537
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001538 // Check that any remaining fields can be value-initialized.
1539 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1540 !Field->getType()->isIncompleteArrayType()) {
1541 // FIXME: Should check for holes left by designated initializers too.
1542 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001543 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001544 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001545 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001546 }
1547 }
1548
Mike Stump1eb44332009-09-09 15:08:12 +00001549 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001550 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001551 return;
1552
David Blaikie581deb32012-06-06 20:45:41 +00001553 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001554 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001555 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001556 ++Index;
1557 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001558 }
1559
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001560 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001561 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001562
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001563 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001564 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001565 StructuredList, StructuredIndex);
1566 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001567 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001568 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001569}
Steve Naroff0cca7492008-05-01 22:18:59 +00001570
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001571/// \brief Expand a field designator that refers to a member of an
1572/// anonymous struct or union into a series of field designators that
1573/// refers to the field within the appropriate subobject.
1574///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001575static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001576 DesignatedInitExpr *DIE,
1577 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001578 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001579 typedef DesignatedInitExpr::Designator Designator;
1580
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001581 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001582 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001583 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1584 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1585 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001586 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001587 DIE->getDesignator(DesigIdx)->getDotLoc(),
1588 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1589 else
1590 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1591 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001592 assert(isa<FieldDecl>(*PI));
1593 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001594 }
1595
1596 // Expand the current designator into the set of replacement
1597 // designators, so we have a full subobject path down to where the
1598 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001599 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001600 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001601}
Mike Stump1eb44332009-09-09 15:08:12 +00001602
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001603/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001604/// corresponds to FieldName.
1605static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1606 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001607 if (!FieldName)
1608 return 0;
1609
Francois Picheta0e27f02010-12-22 03:46:10 +00001610 assert(AnonField->isAnonymousStructOrUnion());
1611 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001612 while (IndirectFieldDecl *IF =
1613 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001614 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001615 return IF;
1616 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001617 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001618 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001619}
1620
Sebastian Redl14b0c192011-09-24 17:48:00 +00001621static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1622 DesignatedInitExpr *DIE) {
1623 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1624 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1625 for (unsigned I = 0; I < NumIndexExprs; ++I)
1626 IndexExprs[I] = DIE->getSubExpr(I + 1);
1627 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001628 DIE->size(), IndexExprs,
1629 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001630 DIE->usesGNUSyntax(), DIE->getInit());
1631}
1632
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001633namespace {
1634
1635// Callback to only accept typo corrections that are for field members of
1636// the given struct or union.
1637class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1638 public:
1639 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1640 : Record(RD) {}
1641
1642 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1643 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1644 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1645 }
1646
1647 private:
1648 RecordDecl *Record;
1649};
1650
1651}
1652
Douglas Gregor05c13a32009-01-22 00:58:24 +00001653/// @brief Check the well-formedness of a C99 designated initializer.
1654///
1655/// Determines whether the designated initializer @p DIE, which
1656/// resides at the given @p Index within the initializer list @p
1657/// IList, is well-formed for a current object of type @p DeclType
1658/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001659/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001660/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001661///
1662/// @param IList The initializer list in which this designated
1663/// initializer occurs.
1664///
Douglas Gregor71199712009-04-15 04:56:10 +00001665/// @param DIE The designated initializer expression.
1666///
1667/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001668///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001669/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001670/// into which the designation in @p DIE should refer.
1671///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001672/// @param NextField If non-NULL and the first designator in @p DIE is
1673/// a field, this will be set to the field declaration corresponding
1674/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001675///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001676/// @param NextElementIndex If non-NULL and the first designator in @p
1677/// DIE is an array designator or GNU array-range designator, this
1678/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001679///
1680/// @param Index Index into @p IList where the designated initializer
1681/// @p DIE occurs.
1682///
Douglas Gregor4c678342009-01-28 21:54:33 +00001683/// @param StructuredList The initializer list expression that
1684/// describes all of the subobject initializers in the order they'll
1685/// actually be initialized.
1686///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001687/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001688bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001689InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001690 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001691 DesignatedInitExpr *DIE,
1692 unsigned DesigIdx,
1693 QualType &CurrentObjectType,
1694 RecordDecl::field_iterator *NextField,
1695 llvm::APSInt *NextElementIndex,
1696 unsigned &Index,
1697 InitListExpr *StructuredList,
1698 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001699 bool FinishSubobjectInit,
1700 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001701 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001702 // Check the actual initialization for the designated object type.
1703 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001704
1705 // Temporarily remove the designator expression from the
1706 // initializer list that the child calls see, so that we don't try
1707 // to re-process the designator.
1708 unsigned OldIndex = Index;
1709 IList->setInit(OldIndex, DIE->getInit());
1710
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001711 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001712 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001713
1714 // Restore the designated initializer expression in the syntactic
1715 // form of the initializer list.
1716 if (IList->getInit(OldIndex) != DIE->getInit())
1717 DIE->setInit(IList->getInit(OldIndex));
1718 IList->setInit(OldIndex, DIE);
1719
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001720 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001721 }
1722
Douglas Gregor71199712009-04-15 04:56:10 +00001723 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001724 bool IsFirstDesignator = (DesigIdx == 0);
1725 if (!VerifyOnly) {
1726 assert((IsFirstDesignator || StructuredList) &&
1727 "Need a non-designated initializer list to start from");
1728
1729 // Determine the structural initializer list that corresponds to the
1730 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001731 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001732 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1733 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001734 SourceRange(D->getLocStart(),
1735 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001736 assert(StructuredList && "Expected a structured initializer list");
1737 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001738
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001739 if (D->isFieldDesignator()) {
1740 // C99 6.7.8p7:
1741 //
1742 // If a designator has the form
1743 //
1744 // . identifier
1745 //
1746 // then the current object (defined below) shall have
1747 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001748 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001749 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001750 if (!RT) {
1751 SourceLocation Loc = D->getDotLoc();
1752 if (Loc.isInvalid())
1753 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001754 if (!VerifyOnly)
1755 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001756 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001757 ++Index;
1758 return true;
1759 }
1760
Douglas Gregor4c678342009-01-28 21:54:33 +00001761 // Note: we perform a linear search of the fields here, despite
1762 // the fact that we have a faster lookup method, because we always
1763 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001764 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001765 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001766 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001767 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001768 Field = RT->getDecl()->field_begin(),
1769 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001770 for (; Field != FieldEnd; ++Field) {
1771 if (Field->isUnnamedBitfield())
1772 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001773
Francois Picheta0e27f02010-12-22 03:46:10 +00001774 // If we find a field representing an anonymous field, look in the
1775 // IndirectFieldDecl that follow for the designated initializer.
1776 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1777 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001778 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001779 // In verify mode, don't modify the original.
1780 if (VerifyOnly)
1781 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001782 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1783 D = DIE->getDesignator(DesigIdx);
1784 break;
1785 }
1786 }
David Blaikie581deb32012-06-06 20:45:41 +00001787 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001788 break;
1789 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001790 break;
1791
1792 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001793 }
1794
Douglas Gregor4c678342009-01-28 21:54:33 +00001795 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001796 if (VerifyOnly) {
1797 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001798 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001799 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001800
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001801 // There was no normal field in the struct with the designated
1802 // name. Perform another lookup for this name, which may find
1803 // something that we can't designate (e.g., a member function),
1804 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001805 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001806 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001807 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001808 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001809 // Name lookup didn't find anything. Determine whether this
1810 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001811 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001812 TypoCorrection Corrected = SemaRef.CorrectTypo(
1813 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001814 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001815 RT->getDecl());
1816 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001817 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001818 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001819 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001820 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001821 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001822 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001823 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001824 << FieldName << CurrentObjectType << CorrectedQuotedStr
1825 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001826 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001827 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001828 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001829 } else {
1830 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1831 << FieldName << CurrentObjectType;
1832 ++Index;
1833 return true;
1834 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001835 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001836
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001837 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001838 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001839 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001840 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001841 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001842 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001843 ++Index;
1844 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001845 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001846
Francois Picheta0e27f02010-12-22 03:46:10 +00001847 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001848 // The replacement field comes from typo correction; find it
1849 // in the list of fields.
1850 FieldIndex = 0;
1851 Field = RT->getDecl()->field_begin();
1852 for (; Field != FieldEnd; ++Field) {
1853 if (Field->isUnnamedBitfield())
1854 continue;
1855
David Blaikie581deb32012-06-06 20:45:41 +00001856 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001857 Field->getIdentifier() == ReplacementField->getIdentifier())
1858 break;
1859
1860 ++FieldIndex;
1861 }
1862 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001863 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001864
1865 // All of the fields of a union are located at the same place in
1866 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001867 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001868 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001869 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001870 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001871 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001872
Douglas Gregor54001c12011-06-29 21:51:31 +00001873 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001874 bool InvalidUse;
1875 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001876 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001877 else
David Blaikie581deb32012-06-06 20:45:41 +00001878 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001879 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001880 ++Index;
1881 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001882 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001883
Sebastian Redl14b0c192011-09-24 17:48:00 +00001884 if (!VerifyOnly) {
1885 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001886 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Sebastian Redl14b0c192011-09-24 17:48:00 +00001888 // Make sure that our non-designated initializer list has space
1889 // for a subobject corresponding to this field.
1890 if (FieldIndex >= StructuredList->getNumInits())
1891 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1892 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001893
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001894 // This designator names a flexible array member.
1895 if (Field->getType()->isIncompleteArrayType()) {
1896 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001897 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001898 // We can't designate an object within the flexible array
1899 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001900 if (!VerifyOnly) {
1901 DesignatedInitExpr::Designator *NextD
1902 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001903 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001904 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001905 << SourceRange(NextD->getLocStart(),
1906 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001907 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001908 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001909 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001910 Invalid = true;
1911 }
1912
Chris Lattner9046c222010-10-10 17:49:49 +00001913 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1914 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001915 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001916 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001917 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001918 diag::err_flexible_array_init_needs_braces)
1919 << DIE->getInit()->getSourceRange();
1920 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001921 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001922 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001923 Invalid = true;
1924 }
1925
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001926 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001927 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001928 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001929 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001930
1931 if (Invalid) {
1932 ++Index;
1933 return true;
1934 }
1935
1936 // Initialize the array.
1937 bool prevHadError = hadError;
1938 unsigned newStructuredIndex = FieldIndex;
1939 unsigned OldIndex = Index;
1940 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001941
1942 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001943 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001944 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001945 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001946
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001947 IList->setInit(OldIndex, DIE);
1948 if (hadError && !prevHadError) {
1949 ++Field;
1950 ++FieldIndex;
1951 if (NextField)
1952 *NextField = Field;
1953 StructuredIndex = FieldIndex;
1954 return true;
1955 }
1956 } else {
1957 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001958 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001959 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001960
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001961 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001962 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001963 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1964 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001965 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001966 true, false))
1967 return true;
1968 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001969
1970 // Find the position of the next field to be initialized in this
1971 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001972 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001973 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001974
1975 // If this the first designator, our caller will continue checking
1976 // the rest of this struct/class/union subobject.
1977 if (IsFirstDesignator) {
1978 if (NextField)
1979 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001980 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001981 return false;
1982 }
1983
Douglas Gregor34e79462009-01-28 23:36:17 +00001984 if (!FinishSubobjectInit)
1985 return false;
1986
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001987 // We've already initialized something in the union; we're done.
1988 if (RT->getDecl()->isUnion())
1989 return hadError;
1990
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001991 // Check the remaining fields within this class/struct/union subobject.
1992 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001993
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001994 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001995 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001996 return hadError && !prevHadError;
1997 }
1998
1999 // C99 6.7.8p6:
2000 //
2001 // If a designator has the form
2002 //
2003 // [ constant-expression ]
2004 //
2005 // then the current object (defined below) shall have array
2006 // type and the expression shall be an integer constant
2007 // expression. If the array is of unknown size, any
2008 // nonnegative value is valid.
2009 //
2010 // Additionally, cope with the GNU extension that permits
2011 // designators of the form
2012 //
2013 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002014 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002015 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002016 if (!VerifyOnly)
2017 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2018 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002019 ++Index;
2020 return true;
2021 }
2022
2023 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00002024 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2025 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002026 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002027 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002028 DesignatedEndIndex = DesignatedStartIndex;
2029 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002030 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002031
Mike Stump1eb44332009-09-09 15:08:12 +00002032 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002033 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002034 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002035 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002036 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002037
Chris Lattnere0fd8322011-02-19 22:28:58 +00002038 // Codegen can't handle evaluating array range designators that have side
2039 // effects, because we replicate the AST value for each initialized element.
2040 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2041 // elements with something that has a side effect, so codegen can emit an
2042 // "error unsupported" error instead of miscompiling the app.
2043 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002044 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002045 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002046 }
2047
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002048 if (isa<ConstantArrayType>(AT)) {
2049 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002050 DesignatedStartIndex
2051 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002052 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002053 DesignatedEndIndex
2054 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002055 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2056 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002057 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002058 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002059 diag::err_array_designator_too_large)
2060 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2061 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002062 ++Index;
2063 return true;
2064 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002065 } else {
2066 // Make sure the bit-widths and signedness match.
2067 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002068 DesignatedEndIndex
2069 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002070 else if (DesignatedStartIndex.getBitWidth() <
2071 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002072 DesignatedStartIndex
2073 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002074 DesignatedStartIndex.setIsUnsigned(true);
2075 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002076 }
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Douglas Gregor4c678342009-01-28 21:54:33 +00002078 // Make sure that our non-designated initializer list has space
2079 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002080 if (!VerifyOnly &&
2081 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002082 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002083 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002084
Douglas Gregor34e79462009-01-28 23:36:17 +00002085 // Repeatedly perform subobject initializations in the range
2086 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002087
Douglas Gregor34e79462009-01-28 23:36:17 +00002088 // Move to the next designator
2089 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2090 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002091
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002092 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002093 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002094
Douglas Gregor34e79462009-01-28 23:36:17 +00002095 while (DesignatedStartIndex <= DesignatedEndIndex) {
2096 // Recurse to check later designated subobjects.
2097 QualType ElementType = AT->getElementType();
2098 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002099
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002100 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002101 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2102 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002103 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002104 (DesignatedStartIndex == DesignatedEndIndex),
2105 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002106 return true;
2107
2108 // Move to the next index in the array that we'll be initializing.
2109 ++DesignatedStartIndex;
2110 ElementIndex = DesignatedStartIndex.getZExtValue();
2111 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002112
2113 // If this the first designator, our caller will continue checking
2114 // the rest of this array subobject.
2115 if (IsFirstDesignator) {
2116 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002117 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002118 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002119 return false;
2120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Douglas Gregor34e79462009-01-28 23:36:17 +00002122 if (!FinishSubobjectInit)
2123 return false;
2124
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002125 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002126 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002127 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002128 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002129 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002130 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002131}
2132
Douglas Gregor4c678342009-01-28 21:54:33 +00002133// Get the structured initializer list for a subobject of type
2134// @p CurrentObjectType.
2135InitListExpr *
2136InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2137 QualType CurrentObjectType,
2138 InitListExpr *StructuredList,
2139 unsigned StructuredIndex,
2140 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002141 if (VerifyOnly)
2142 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002143 Expr *ExistingInit = 0;
2144 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002145 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002146 else if (StructuredIndex < StructuredList->getNumInits())
2147 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Douglas Gregor4c678342009-01-28 21:54:33 +00002149 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2150 return Result;
2151
2152 if (ExistingInit) {
2153 // We are creating an initializer list that initializes the
2154 // subobjects of the current object, but there was already an
2155 // initialization that completely initialized the current
2156 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002157 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002158 // struct X { int a, b; };
2159 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002160 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002161 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2162 // designated initializer re-initializes the whole
2163 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002164 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002165 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002166 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002167 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002168 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002169 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002170 << ExistingInit->getSourceRange();
2171 }
2172
Mike Stump1eb44332009-09-09 15:08:12 +00002173 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002174 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002175 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002176 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002177
Eli Friedman5c89c392012-02-23 02:25:10 +00002178 QualType ResultType = CurrentObjectType;
2179 if (!ResultType->isArrayType())
2180 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2181 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002182
Douglas Gregorfa219202009-03-20 23:58:33 +00002183 // Pre-allocate storage for the structured initializer list.
2184 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002185 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002186 bool GotNumInits = false;
2187 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002188 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002189 GotNumInits = true;
2190 } else if (Index < IList->getNumInits()) {
2191 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002192 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002193 GotNumInits = true;
2194 }
Douglas Gregor08457732009-03-21 18:13:52 +00002195 }
2196
Mike Stump1eb44332009-09-09 15:08:12 +00002197 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002198 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2199 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2200 NumElements = CAType->getSize().getZExtValue();
2201 // Simple heuristic so that we don't allocate a very large
2202 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002203 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002204 NumElements = 0;
2205 }
John McCall183700f2009-09-21 23:43:11 +00002206 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002207 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002208 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002209 RecordDecl *RDecl = RType->getDecl();
2210 if (RDecl->isUnion())
2211 NumElements = 1;
2212 else
Mike Stump1eb44332009-09-09 15:08:12 +00002213 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002214 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002215 }
2216
Ted Kremenek709210f2010-04-13 23:39:13 +00002217 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002218
Douglas Gregor4c678342009-01-28 21:54:33 +00002219 // Link this new initializer list into the structured initializer
2220 // lists.
2221 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002222 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002223 else {
2224 Result->setSyntacticForm(IList);
2225 SyntacticToSemantic[IList] = Result;
2226 }
2227
2228 return Result;
2229}
2230
2231/// Update the initializer at index @p StructuredIndex within the
2232/// structured initializer list to the value @p expr.
2233void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2234 unsigned &StructuredIndex,
2235 Expr *expr) {
2236 // No structured initializer list to update
2237 if (!StructuredList)
2238 return;
2239
Ted Kremenek709210f2010-04-13 23:39:13 +00002240 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2241 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002242 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002243 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002244 diag::warn_initializer_overrides)
2245 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002246 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002247 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002248 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002249 << PrevInit->getSourceRange();
2250 }
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Douglas Gregor4c678342009-01-28 21:54:33 +00002252 ++StructuredIndex;
2253}
2254
Douglas Gregor05c13a32009-01-22 00:58:24 +00002255/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002256/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002257/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002258/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002259/// failure. Returns the index expression, possibly with an implicit cast
2260/// added, on success. If everything went okay, Value will receive the
2261/// value of the constant expression.
2262static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002263CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002264 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002265
2266 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002267 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2268 if (Result.isInvalid())
2269 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002270
Chris Lattner3bf68932009-04-25 21:59:05 +00002271 if (Value.isSigned() && Value.isNegative())
2272 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002273 << Value.toString(10) << Index->getSourceRange();
2274
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002275 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002276 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002277}
2278
John McCall60d7b3a2010-08-24 06:29:42 +00002279ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002280 SourceLocation Loc,
2281 bool GNUSyntax,
2282 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002283 typedef DesignatedInitExpr::Designator ASTDesignator;
2284
2285 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002286 SmallVector<ASTDesignator, 32> Designators;
2287 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002288
2289 // Build designators and check array designator expressions.
2290 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2291 const Designator &D = Desig.getDesignator(Idx);
2292 switch (D.getKind()) {
2293 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002294 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002295 D.getFieldLoc()));
2296 break;
2297
2298 case Designator::ArrayDesignator: {
2299 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2300 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002301 if (!Index->isTypeDependent() && !Index->isValueDependent())
2302 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2303 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002304 Invalid = true;
2305 else {
2306 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002307 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002308 D.getRBracketLoc()));
2309 InitExpressions.push_back(Index);
2310 }
2311 break;
2312 }
2313
2314 case Designator::ArrayRangeDesignator: {
2315 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2316 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2317 llvm::APSInt StartValue;
2318 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002319 bool StartDependent = StartIndex->isTypeDependent() ||
2320 StartIndex->isValueDependent();
2321 bool EndDependent = EndIndex->isTypeDependent() ||
2322 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002323 if (!StartDependent)
2324 StartIndex =
2325 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2326 if (!EndDependent)
2327 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2328
2329 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002330 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002331 else {
2332 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002333 if (StartDependent || EndDependent) {
2334 // Nothing to compute.
2335 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002336 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002337 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002338 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002339
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002340 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002341 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002342 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002343 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2344 Invalid = true;
2345 } else {
2346 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002347 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002348 D.getEllipsisLoc(),
2349 D.getRBracketLoc()));
2350 InitExpressions.push_back(StartIndex);
2351 InitExpressions.push_back(EndIndex);
2352 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002353 }
2354 break;
2355 }
2356 }
2357 }
2358
2359 if (Invalid || Init.isInvalid())
2360 return ExprError();
2361
2362 // Clear out the expressions within the designation.
2363 Desig.ClearExprs(*this);
2364
2365 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002366 = DesignatedInitExpr::Create(Context,
2367 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002368 InitExpressions, Loc, GNUSyntax,
2369 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002370
David Blaikie4e4d0842012-03-11 07:00:24 +00002371 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002372 Diag(DIE->getLocStart(), diag::ext_designated_init)
2373 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002374
Douglas Gregor05c13a32009-01-22 00:58:24 +00002375 return Owned(DIE);
2376}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002377
Douglas Gregor20093b42009-12-09 23:02:17 +00002378//===----------------------------------------------------------------------===//
2379// Initialization entity
2380//===----------------------------------------------------------------------===//
2381
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002382InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002383 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002384 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002385{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002386 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2387 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002388 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002389 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002390 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002391 Type = VT->getElementType();
2392 } else {
2393 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2394 assert(CT && "Unexpected type");
2395 Kind = EK_ComplexElement;
2396 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002397 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002398}
2399
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002400InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002401 CXXBaseSpecifier *Base,
2402 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002403{
2404 InitializedEntity Result;
2405 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002406 Result.Base = reinterpret_cast<uintptr_t>(Base);
2407 if (IsInheritedVirtualBase)
2408 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002409
Douglas Gregord6542d82009-12-22 15:35:07 +00002410 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002411 return Result;
2412}
2413
Douglas Gregor99a2e602009-12-16 01:38:02 +00002414DeclarationName InitializedEntity::getName() const {
2415 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002416 case EK_Parameter: {
2417 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2418 return (D ? D->getDeclName() : DeclarationName());
2419 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002420
2421 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002422 case EK_Member:
2423 return VariableOrMember->getDeclName();
2424
Douglas Gregor47736542012-02-15 16:57:26 +00002425 case EK_LambdaCapture:
2426 return Capture.Var->getDeclName();
2427
Douglas Gregor99a2e602009-12-16 01:38:02 +00002428 case EK_Result:
2429 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002430 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002431 case EK_Temporary:
2432 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002433 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002434 case EK_ArrayElement:
2435 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002436 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002437 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002438 case EK_CompoundLiteralInit:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002439 return DeclarationName();
2440 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002441
David Blaikie7530c032012-01-17 06:56:22 +00002442 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002443}
2444
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002445DeclaratorDecl *InitializedEntity::getDecl() const {
2446 switch (getKind()) {
2447 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002448 case EK_Member:
2449 return VariableOrMember;
2450
John McCallf85e1932011-06-15 23:02:42 +00002451 case EK_Parameter:
2452 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2453
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002454 case EK_Result:
2455 case EK_Exception:
2456 case EK_New:
2457 case EK_Temporary:
2458 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002459 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002460 case EK_ArrayElement:
2461 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002462 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002463 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002464 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002465 case EK_CompoundLiteralInit:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002466 return 0;
2467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002468
David Blaikie7530c032012-01-17 06:56:22 +00002469 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002470}
2471
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002472bool InitializedEntity::allowsNRVO() const {
2473 switch (getKind()) {
2474 case EK_Result:
2475 case EK_Exception:
2476 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002477
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002478 case EK_Variable:
2479 case EK_Parameter:
2480 case EK_Member:
2481 case EK_New:
2482 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002483 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002484 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002485 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002486 case EK_ArrayElement:
2487 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002488 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002489 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002490 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002491 break;
2492 }
2493
2494 return false;
2495}
2496
Richard Smith211c8dd2013-06-05 00:46:14 +00002497unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
2498 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2499 for (unsigned I = 0; I != Depth; ++I)
2500 OS << "`-";
2501
2502 switch (getKind()) {
2503 case EK_Variable: OS << "Variable"; break;
2504 case EK_Parameter: OS << "Parameter"; break;
2505 case EK_Result: OS << "Result"; break;
2506 case EK_Exception: OS << "Exception"; break;
2507 case EK_Member: OS << "Member"; break;
2508 case EK_New: OS << "New"; break;
2509 case EK_Temporary: OS << "Temporary"; break;
2510 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
2511 case EK_Base: OS << "Base"; break;
2512 case EK_Delegating: OS << "Delegating"; break;
2513 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2514 case EK_VectorElement: OS << "VectorElement " << Index; break;
2515 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2516 case EK_BlockElement: OS << "Block"; break;
2517 case EK_LambdaCapture:
2518 OS << "LambdaCapture ";
2519 getCapturedVar()->printName(OS);
2520 break;
2521 }
2522
2523 if (Decl *D = getDecl()) {
2524 OS << " ";
2525 cast<NamedDecl>(D)->printQualifiedName(OS);
2526 }
2527
2528 OS << " '" << getType().getAsString() << "'\n";
2529
2530 return Depth + 1;
2531}
2532
2533void InitializedEntity::dump() const {
2534 dumpImpl(llvm::errs());
2535}
2536
Douglas Gregor20093b42009-12-09 23:02:17 +00002537//===----------------------------------------------------------------------===//
2538// Initialization sequence
2539//===----------------------------------------------------------------------===//
2540
2541void InitializationSequence::Step::Destroy() {
2542 switch (Kind) {
2543 case SK_ResolveAddressOfOverloadedFunction:
2544 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002545 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002546 case SK_CastDerivedToBaseLValue:
2547 case SK_BindReference:
2548 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002549 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002550 case SK_UserConversion:
2551 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002552 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002553 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002554 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002555 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002556 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002557 case SK_UnwrapInitList:
2558 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002559 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002560 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002561 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002562 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002563 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002564 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002565 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002566 case SK_PassByIndirectCopyRestore:
2567 case SK_PassByIndirectRestore:
2568 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002569 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002570 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002571 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002572 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002573
Douglas Gregor20093b42009-12-09 23:02:17 +00002574 case SK_ConversionSequence:
2575 delete ICS;
2576 }
2577}
2578
Douglas Gregorb70cf442010-03-26 20:14:36 +00002579bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002580 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002581}
2582
2583bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002584 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002585 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002586
Douglas Gregorb70cf442010-03-26 20:14:36 +00002587 switch (getFailureKind()) {
2588 case FK_TooManyInitsForReference:
2589 case FK_ArrayNeedsInitList:
2590 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002591 case FK_ArrayNeedsInitListOrWideStringLiteral:
2592 case FK_NarrowStringIntoWideCharArray:
2593 case FK_WideStringIntoCharArray:
2594 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002595 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2596 case FK_NonConstLValueReferenceBindingToTemporary:
2597 case FK_NonConstLValueReferenceBindingToUnrelated:
2598 case FK_RValueReferenceBindingToLValue:
2599 case FK_ReferenceInitDropsQualifiers:
2600 case FK_ReferenceInitFailed:
2601 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002602 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002603 case FK_TooManyInitsForScalar:
2604 case FK_ReferenceBindingToInitList:
2605 case FK_InitListBadDestinationType:
2606 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002607 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002608 case FK_ArrayTypeMismatch:
2609 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002610 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002611 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002612 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002613 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002614 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002615 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002616
Douglas Gregorb70cf442010-03-26 20:14:36 +00002617 case FK_ReferenceInitOverloadFailed:
2618 case FK_UserConversionOverloadFailed:
2619 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002620 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002621 return FailedOverloadResult == OR_Ambiguous;
2622 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002623
David Blaikie7530c032012-01-17 06:56:22 +00002624 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002625}
2626
Douglas Gregord6e44a32010-04-16 22:09:46 +00002627bool InitializationSequence::isConstructorInitialization() const {
2628 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2629}
2630
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002631void
2632InitializationSequence
2633::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2634 DeclAccessPair Found,
2635 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002636 Step S;
2637 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2638 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002639 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002640 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002641 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002642 Steps.push_back(S);
2643}
2644
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002645void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002646 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002647 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002648 switch (VK) {
2649 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2650 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2651 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002652 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002653 S.Type = BaseType;
2654 Steps.push_back(S);
2655}
2656
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002657void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002658 bool BindingTemporary) {
2659 Step S;
2660 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2661 S.Type = T;
2662 Steps.push_back(S);
2663}
2664
Douglas Gregor523d46a2010-04-18 07:40:54 +00002665void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2666 Step S;
2667 S.Kind = SK_ExtraneousCopyToTemporary;
2668 S.Type = T;
2669 Steps.push_back(S);
2670}
2671
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002672void
2673InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2674 DeclAccessPair FoundDecl,
2675 QualType T,
2676 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002677 Step S;
2678 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002679 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002680 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002681 S.Function.Function = Function;
2682 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002683 Steps.push_back(S);
2684}
2685
2686void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002687 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002688 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002689 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002690 switch (VK) {
2691 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002692 S.Kind = SK_QualificationConversionRValue;
2693 break;
John McCall5baba9d2010-08-25 10:28:54 +00002694 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002695 S.Kind = SK_QualificationConversionXValue;
2696 break;
John McCall5baba9d2010-08-25 10:28:54 +00002697 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002698 S.Kind = SK_QualificationConversionLValue;
2699 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002700 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002701 S.Type = Ty;
2702 Steps.push_back(S);
2703}
2704
Jordan Rose1fd1e282013-04-11 00:58:58 +00002705void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2706 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2707
2708 Step S;
2709 S.Kind = SK_LValueToRValue;
2710 S.Type = Ty;
2711 Steps.push_back(S);
2712}
2713
Douglas Gregor20093b42009-12-09 23:02:17 +00002714void InitializationSequence::AddConversionSequenceStep(
2715 const ImplicitConversionSequence &ICS,
2716 QualType T) {
2717 Step S;
2718 S.Kind = SK_ConversionSequence;
2719 S.Type = T;
2720 S.ICS = new ImplicitConversionSequence(ICS);
2721 Steps.push_back(S);
2722}
2723
Douglas Gregord87b61f2009-12-10 17:56:55 +00002724void InitializationSequence::AddListInitializationStep(QualType T) {
2725 Step S;
2726 S.Kind = SK_ListInitialization;
2727 S.Type = T;
2728 Steps.push_back(S);
2729}
2730
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002731void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002732InitializationSequence
2733::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2734 AccessSpecifier Access,
2735 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002736 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002737 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002738 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002739 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2740 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002741 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002742 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002743 S.Function.Function = Constructor;
2744 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002745 Steps.push_back(S);
2746}
2747
Douglas Gregor71d17402009-12-15 00:01:57 +00002748void InitializationSequence::AddZeroInitializationStep(QualType T) {
2749 Step S;
2750 S.Kind = SK_ZeroInitialization;
2751 S.Type = T;
2752 Steps.push_back(S);
2753}
2754
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002755void InitializationSequence::AddCAssignmentStep(QualType T) {
2756 Step S;
2757 S.Kind = SK_CAssignment;
2758 S.Type = T;
2759 Steps.push_back(S);
2760}
2761
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002762void InitializationSequence::AddStringInitStep(QualType T) {
2763 Step S;
2764 S.Kind = SK_StringInit;
2765 S.Type = T;
2766 Steps.push_back(S);
2767}
2768
Douglas Gregor569c3162010-08-07 11:51:51 +00002769void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2770 Step S;
2771 S.Kind = SK_ObjCObjectConversion;
2772 S.Type = T;
2773 Steps.push_back(S);
2774}
2775
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002776void InitializationSequence::AddArrayInitStep(QualType T) {
2777 Step S;
2778 S.Kind = SK_ArrayInit;
2779 S.Type = T;
2780 Steps.push_back(S);
2781}
2782
Richard Smith0f163e92012-02-15 22:38:09 +00002783void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2784 Step S;
2785 S.Kind = SK_ParenthesizedArrayInit;
2786 S.Type = T;
2787 Steps.push_back(S);
2788}
2789
John McCallf85e1932011-06-15 23:02:42 +00002790void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2791 bool shouldCopy) {
2792 Step s;
2793 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2794 : SK_PassByIndirectRestore);
2795 s.Type = type;
2796 Steps.push_back(s);
2797}
2798
2799void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2800 Step S;
2801 S.Kind = SK_ProduceObjCObject;
2802 S.Type = T;
2803 Steps.push_back(S);
2804}
2805
Sebastian Redl2b916b82012-01-17 22:49:42 +00002806void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2807 Step S;
2808 S.Kind = SK_StdInitializerList;
2809 S.Type = T;
2810 Steps.push_back(S);
2811}
2812
Guy Benyei21f18c42013-02-07 10:55:47 +00002813void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2814 Step S;
2815 S.Kind = SK_OCLSamplerInit;
2816 S.Type = T;
2817 Steps.push_back(S);
2818}
2819
Guy Benyeie6b9d802013-01-20 12:31:11 +00002820void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2821 Step S;
2822 S.Kind = SK_OCLZeroEvent;
2823 S.Type = T;
2824 Steps.push_back(S);
2825}
2826
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002827void InitializationSequence::RewrapReferenceInitList(QualType T,
2828 InitListExpr *Syntactic) {
2829 assert(Syntactic->getNumInits() == 1 &&
2830 "Can only rewrap trivial init lists.");
2831 Step S;
2832 S.Kind = SK_UnwrapInitList;
2833 S.Type = Syntactic->getInit(0)->getType();
2834 Steps.insert(Steps.begin(), S);
2835
2836 S.Kind = SK_RewrapInitList;
2837 S.Type = T;
2838 S.WrappingSyntacticList = Syntactic;
2839 Steps.push_back(S);
2840}
2841
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002842void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002843 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002844 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002845 this->Failure = Failure;
2846 this->FailedOverloadResult = Result;
2847}
2848
2849//===----------------------------------------------------------------------===//
2850// Attempt initialization
2851//===----------------------------------------------------------------------===//
2852
John McCallf85e1932011-06-15 23:02:42 +00002853static void MaybeProduceObjCObject(Sema &S,
2854 InitializationSequence &Sequence,
2855 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002856 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002857
2858 /// When initializing a parameter, produce the value if it's marked
2859 /// __attribute__((ns_consumed)).
2860 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2861 if (!Entity.isParameterConsumed())
2862 return;
2863
2864 assert(Entity.getType()->isObjCRetainableType() &&
2865 "consuming an object of unretainable type?");
2866 Sequence.AddProduceObjCObjectStep(Entity.getType());
2867
2868 /// When initializing a return value, if the return type is a
2869 /// retainable type, then returns need to immediately retain the
2870 /// object. If an autorelease is required, it will be done at the
2871 /// last instant.
2872 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2873 if (!Entity.getType()->isObjCRetainableType())
2874 return;
2875
2876 Sequence.AddProduceObjCObjectStep(Entity.getType());
2877 }
2878}
2879
Richard Smithf4bb8d02012-07-05 08:39:21 +00002880/// \brief When initializing from init list via constructor, handle
2881/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002882///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002883/// \return true if we have handled initialization of an object of type
2884/// std::initializer_list<T>, false otherwise.
2885static bool TryInitializerListConstruction(Sema &S,
2886 InitListExpr *List,
2887 QualType DestType,
2888 InitializationSequence &Sequence) {
2889 QualType E;
2890 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002891 return false;
2892
Richard Smithf4bb8d02012-07-05 08:39:21 +00002893 // Check that each individual element can be copy-constructed. But since we
2894 // have no place to store further information, we'll recalculate everything
2895 // later.
2896 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2897 S.Context.getConstantArrayType(E,
2898 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2899 List->getNumInits()),
2900 ArrayType::Normal, 0));
2901 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2902 0, HiddenArray);
2903 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2904 Element.setElementIndex(i);
2905 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2906 Sequence.SetFailed(
2907 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002908 return true;
2909 }
2910 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002911 Sequence.AddStdInitializerListConstructionStep(DestType);
2912 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002913}
2914
Sebastian Redl96715b22012-02-04 21:27:39 +00002915static OverloadingResult
2916ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002917 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002918 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002919 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002920 OverloadCandidateSet::iterator &Best,
2921 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002922 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002923 CandidateSet.clear();
2924
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002925 for (ArrayRef<NamedDecl *>::iterator
2926 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002927 NamedDecl *D = *Con;
2928 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2929 bool SuppressUserConversions = false;
2930
2931 // Find the constructor (which may be a template).
2932 CXXConstructorDecl *Constructor = 0;
2933 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2934 if (ConstructorTmpl)
2935 Constructor = cast<CXXConstructorDecl>(
2936 ConstructorTmpl->getTemplatedDecl());
2937 else {
2938 Constructor = cast<CXXConstructorDecl>(D);
2939
2940 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002941 // suppress user-defined conversions on the arguments. We do the same for
2942 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002943 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002944 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002945 SuppressUserConversions = true;
2946 }
2947
2948 if (!Constructor->isInvalidDecl() &&
2949 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002950 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002951 if (ConstructorTmpl)
2952 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002953 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002954 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002955 else {
2956 // C++ [over.match.copy]p1:
2957 // - When initializing a temporary to be bound to the first parameter
2958 // of a constructor that takes a reference to possibly cv-qualified
2959 // T as its first argument, called with a single argument in the
2960 // context of direct-initialization, explicit conversion functions
2961 // are also considered.
2962 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002963 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00002964 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002965 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002966 SuppressUserConversions,
2967 /*PartialOverloading=*/false,
2968 /*AllowExplicit=*/AllowExplicitConv);
2969 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002970 }
2971 }
2972
2973 // Perform overload resolution and return the result.
2974 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2975}
2976
Sebastian Redl10f04a62011-12-22 14:44:04 +00002977/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2978/// enumerates the constructors of the initialized entity and performs overload
2979/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002980/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002981/// class type.
2982static void TryConstructorInitialization(Sema &S,
2983 const InitializedEntity &Entity,
2984 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002985 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002986 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002987 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002988 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00002989 "InitListSyntax must come with a single initializer list argument.");
2990
Sebastian Redl10f04a62011-12-22 14:44:04 +00002991 // The type we're constructing needs to be complete.
2992 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002993 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002994 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002995 }
2996
2997 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2998 assert(DestRecordType && "Constructor initialization requires record type");
2999 CXXRecordDecl *DestRecordDecl
3000 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3001
Sebastian Redl96715b22012-02-04 21:27:39 +00003002 // Build the candidate set directly in the initialization sequence
3003 // structure, so that it will persist if we fail.
3004 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3005
3006 // Determine whether we are allowed to call explicit constructors or
3007 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003008 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003009 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00003010
Sebastian Redl10f04a62011-12-22 14:44:04 +00003011 // - Otherwise, if T is a class type, constructors are considered. The
3012 // applicable constructors are enumerated, and the best one is chosen
3013 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00003014 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003015 // The container holding the constructors can under certain conditions
3016 // be changed while iterating (e.g. because of deserialization).
3017 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003018 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00003019
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003020 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003021 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003022 bool AsInitializerList = false;
3023
3024 // C++11 [over.match.list]p1:
3025 // When objects of non-aggregate type T are list-initialized, overload
3026 // resolution selects the constructor in two phases:
3027 // - Initially, the candidate functions are the initializer-list
3028 // constructors of the class T and the argument list consists of the
3029 // initializer list as a single argument.
3030 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003031 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003032 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003033
3034 // If the initializer list has no elements and T has a default constructor,
3035 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003036 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003037 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003038 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003039 CopyInitialization, AllowExplicit,
3040 /*OnlyListConstructor=*/true,
3041 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003042
3043 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003044 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003045 }
3046
3047 // C++11 [over.match.list]p1:
3048 // - If no viable initializer-list constructor is found, overload resolution
3049 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003050 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003051 // elements of the initializer list.
3052 if (Result == OR_No_Viable_Function) {
3053 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003054 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003055 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003056 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003057 /*OnlyListConstructors=*/false,
3058 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003059 }
3060 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003061 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003062 InitializationSequence::FK_ListConstructorOverloadFailed :
3063 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003064 Result);
3065 return;
3066 }
3067
Richard Smithf4bb8d02012-07-05 08:39:21 +00003068 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003069 // If a program calls for the default initialization of an object
3070 // of a const-qualified type T, T shall be a class type with a
3071 // user-provided default constructor.
3072 if (Kind.getKind() == InitializationKind::IK_Default &&
3073 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003074 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003075 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3076 return;
3077 }
3078
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003079 // C++11 [over.match.list]p1:
3080 // In copy-list-initialization, if an explicit constructor is chosen, the
3081 // initializer is ill-formed.
3082 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3083 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3084 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3085 return;
3086 }
3087
Sebastian Redl10f04a62011-12-22 14:44:04 +00003088 // Add the constructor initialization step. Any cv-qualification conversion is
3089 // subsumed by the initialization.
3090 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003091 Sequence.AddConstructorInitializationStep(CtorDecl,
3092 Best->FoundDecl.getAccess(),
3093 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003094 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003095}
3096
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003097static bool
3098ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3099 Expr *Initializer,
3100 QualType &SourceType,
3101 QualType &UnqualifiedSourceType,
3102 QualType UnqualifiedTargetType,
3103 InitializationSequence &Sequence) {
3104 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3105 S.Context.OverloadTy) {
3106 DeclAccessPair Found;
3107 bool HadMultipleCandidates = false;
3108 if (FunctionDecl *Fn
3109 = S.ResolveAddressOfOverloadedFunction(Initializer,
3110 UnqualifiedTargetType,
3111 false, Found,
3112 &HadMultipleCandidates)) {
3113 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3114 HadMultipleCandidates);
3115 SourceType = Fn->getType();
3116 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3117 } else if (!UnqualifiedTargetType->isRecordType()) {
3118 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3119 return true;
3120 }
3121 }
3122 return false;
3123}
3124
3125static void TryReferenceInitializationCore(Sema &S,
3126 const InitializedEntity &Entity,
3127 const InitializationKind &Kind,
3128 Expr *Initializer,
3129 QualType cv1T1, QualType T1,
3130 Qualifiers T1Quals,
3131 QualType cv2T2, QualType T2,
3132 Qualifiers T2Quals,
3133 InitializationSequence &Sequence);
3134
Richard Smithf4bb8d02012-07-05 08:39:21 +00003135static void TryValueInitialization(Sema &S,
3136 const InitializedEntity &Entity,
3137 const InitializationKind &Kind,
3138 InitializationSequence &Sequence,
3139 InitListExpr *InitList = 0);
3140
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003141static void TryListInitialization(Sema &S,
3142 const InitializedEntity &Entity,
3143 const InitializationKind &Kind,
3144 InitListExpr *InitList,
3145 InitializationSequence &Sequence);
3146
3147/// \brief Attempt list initialization of a reference.
3148static void TryReferenceListInitialization(Sema &S,
3149 const InitializedEntity &Entity,
3150 const InitializationKind &Kind,
3151 InitListExpr *InitList,
3152 InitializationSequence &Sequence)
3153{
3154 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003155 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003156 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3157 return;
3158 }
3159
3160 QualType DestType = Entity.getType();
3161 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3162 Qualifiers T1Quals;
3163 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3164
3165 // Reference initialization via an initializer list works thus:
3166 // If the initializer list consists of a single element that is
3167 // reference-related to the referenced type, bind directly to that element
3168 // (possibly creating temporaries).
3169 // Otherwise, initialize a temporary with the initializer list and
3170 // bind to that.
3171 if (InitList->getNumInits() == 1) {
3172 Expr *Initializer = InitList->getInit(0);
3173 QualType cv2T2 = Initializer->getType();
3174 Qualifiers T2Quals;
3175 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3176
3177 // If this fails, creating a temporary wouldn't work either.
3178 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3179 T1, Sequence))
3180 return;
3181
3182 SourceLocation DeclLoc = Initializer->getLocStart();
3183 bool dummy1, dummy2, dummy3;
3184 Sema::ReferenceCompareResult RefRelationship
3185 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3186 dummy2, dummy3);
3187 if (RefRelationship >= Sema::Ref_Related) {
3188 // Try to bind the reference here.
3189 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3190 T1Quals, cv2T2, T2, T2Quals, Sequence);
3191 if (Sequence)
3192 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3193 return;
3194 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003195
3196 // Update the initializer if we've resolved an overloaded function.
3197 if (Sequence.step_begin() != Sequence.step_end())
3198 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003199 }
3200
3201 // Not reference-related. Create a temporary and bind to that.
3202 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3203
3204 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3205 if (Sequence) {
3206 if (DestType->isRValueReferenceType() ||
3207 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3208 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3209 else
3210 Sequence.SetFailed(
3211 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3212 }
3213}
3214
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003215/// \brief Attempt list initialization (C++0x [dcl.init.list])
3216static void TryListInitialization(Sema &S,
3217 const InitializedEntity &Entity,
3218 const InitializationKind &Kind,
3219 InitListExpr *InitList,
3220 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003221 QualType DestType = Entity.getType();
3222
Sebastian Redl14b0c192011-09-24 17:48:00 +00003223 // C++ doesn't allow scalar initialization with more than one argument.
3224 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003225 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003226 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3227 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3228 return;
3229 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003230 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003231 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003232 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003233 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003234 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003235 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003236 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003237 return;
3238 }
3239
Richard Smithf4bb8d02012-07-05 08:39:21 +00003240 // C++11 [dcl.init.list]p3:
3241 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003242 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003243 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003244 // - Otherwise, if the initializer list has no elements and T is a
3245 // class type with a default constructor, the object is
3246 // value-initialized.
3247 if (InitList->getNumInits() == 0) {
3248 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003249 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003250 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3251 return;
3252 }
3253 }
3254
3255 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3256 // an initializer_list object constructed [...]
3257 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3258 return;
3259
3260 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003261 Expr *InitListAsExpr = InitList;
3262 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003263 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003264 } else
3265 Sequence.SetFailed(
3266 InitializationSequence::FK_InitListBadDestinationType);
3267 return;
3268 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003269 }
3270
Sebastian Redl14b0c192011-09-24 17:48:00 +00003271 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00003272 DestType, /*VerifyOnly=*/true);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003273 if (CheckInitList.HadError()) {
3274 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3275 return;
3276 }
3277
3278 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003279 Sequence.AddListInitializationStep(DestType);
3280}
Douglas Gregor20093b42009-12-09 23:02:17 +00003281
3282/// \brief Try a reference initialization that involves calling a conversion
3283/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003284static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3285 const InitializedEntity &Entity,
3286 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003287 Expr *Initializer,
3288 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003289 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003290 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003291 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3292 QualType T1 = cv1T1.getUnqualifiedType();
3293 QualType cv2T2 = Initializer->getType();
3294 QualType T2 = cv2T2.getUnqualifiedType();
3295
3296 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003297 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003298 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003299 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003300 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003301 ObjCConversion,
3302 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003303 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003304 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003305 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003306 (void)ObjCLifetimeConversion;
3307
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 // Build the candidate set directly in the initialization sequence
3309 // structure, so that it will persist if we fail.
3310 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3311 CandidateSet.clear();
3312
3313 // Determine whether we are allowed to call explicit constructors or
3314 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003315 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003316 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3317
Douglas Gregor20093b42009-12-09 23:02:17 +00003318 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003319 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3320 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003321 // The type we're converting to is a class type. Enumerate its constructors
3322 // to see if there is a suitable conversion.
3323 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003324
David Blaikie3bc93e32012-12-19 00:45:41 +00003325 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003326 // The container holding the constructors can under certain conditions
3327 // be changed while iterating (e.g. because of deserialization).
3328 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003329 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003330 for (SmallVector<NamedDecl*, 16>::iterator
3331 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3332 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003333 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3334
Douglas Gregor20093b42009-12-09 23:02:17 +00003335 // Find the constructor (which may be a template).
3336 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003337 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003338 if (ConstructorTmpl)
3339 Constructor = cast<CXXConstructorDecl>(
3340 ConstructorTmpl->getTemplatedDecl());
3341 else
John McCall9aa472c2010-03-19 07:35:19 +00003342 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003343
Douglas Gregor20093b42009-12-09 23:02:17 +00003344 if (!Constructor->isInvalidDecl() &&
3345 Constructor->isConvertingConstructor(AllowExplicit)) {
3346 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003347 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003348 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003349 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003350 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003351 else
John McCall9aa472c2010-03-19 07:35:19 +00003352 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003353 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003354 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003355 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003356 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003357 }
John McCall572fc622010-08-17 07:23:57 +00003358 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3359 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003361 const RecordType *T2RecordType = 0;
3362 if ((T2RecordType = T2->getAs<RecordType>()) &&
3363 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003364 // The type we're converting from is a class type, enumerate its conversion
3365 // functions.
3366 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3367
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003368 std::pair<CXXRecordDecl::conversion_iterator,
3369 CXXRecordDecl::conversion_iterator>
3370 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3371 for (CXXRecordDecl::conversion_iterator
3372 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003373 NamedDecl *D = *I;
3374 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3375 if (isa<UsingShadowDecl>(D))
3376 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377
Douglas Gregor20093b42009-12-09 23:02:17 +00003378 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3379 CXXConversionDecl *Conv;
3380 if (ConvTemplate)
3381 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3382 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003383 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003384
Douglas Gregor20093b42009-12-09 23:02:17 +00003385 // If the conversion function doesn't return a reference type,
3386 // it can't be considered for this conversion unless we're allowed to
3387 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388 // FIXME: Do we need to make sure that we only consider conversion
3389 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003390 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003391 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003392 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3393 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003394 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003395 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003396 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003397 else
John McCall9aa472c2010-03-19 07:35:19 +00003398 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003399 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003400 }
3401 }
3402 }
John McCall572fc622010-08-17 07:23:57 +00003403 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3404 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003405
Douglas Gregor20093b42009-12-09 23:02:17 +00003406 SourceLocation DeclLoc = Initializer->getLocStart();
3407
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003408 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003409 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003411 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003412 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003413
Douglas Gregor20093b42009-12-09 23:02:17 +00003414 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003415 // This is the overload that will be used for this initialization step if we
3416 // use this initialization. Mark it as referenced.
3417 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003418
Eli Friedman03981012009-12-11 02:42:07 +00003419 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003420 if (isa<CXXConversionDecl>(Function))
3421 T2 = Function->getResultType();
3422 else
3423 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003424
3425 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003426 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003427 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003428 T2.getNonLValueExprType(S.Context),
3429 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003430
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003431 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003432 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003433 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003434 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003435 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003436 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003437 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003438
Douglas Gregor20093b42009-12-09 23:02:17 +00003439 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003440 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003441 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003442 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003443 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003444 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003445 NewDerivedToBase, NewObjCConversion,
3446 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003447 if (NewRefRelationship == Sema::Ref_Incompatible) {
3448 // If the type we've converted to is not reference-related to the
3449 // type we're looking for, then there is another conversion step
3450 // we need to perform to produce a temporary of the right type
3451 // that we'll be binding to.
3452 ImplicitConversionSequence ICS;
3453 ICS.setStandard();
3454 ICS.Standard = Best->FinalConversion;
3455 T2 = ICS.Standard.getToType(2);
3456 Sequence.AddConversionSequenceStep(ICS, T2);
3457 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003458 Sequence.AddDerivedToBaseCastStep(
3459 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003460 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003461 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003462 else if (NewObjCConversion)
3463 Sequence.AddObjCObjectConversionStep(
3464 S.Context.getQualifiedType(T1,
3465 T2.getNonReferenceType().getQualifiers()));
3466
Douglas Gregor20093b42009-12-09 23:02:17 +00003467 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003468 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003469
Douglas Gregor20093b42009-12-09 23:02:17 +00003470 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3471 return OR_Success;
3472}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003473
Richard Smith83da2e72011-10-19 16:55:56 +00003474static void CheckCXX98CompatAccessibleCopy(Sema &S,
3475 const InitializedEntity &Entity,
3476 Expr *CurInitExpr);
3477
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3479static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003480 const InitializedEntity &Entity,
3481 const InitializationKind &Kind,
3482 Expr *Initializer,
3483 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003484 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003485 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003486 Qualifiers T1Quals;
3487 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003488 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003489 Qualifiers T2Quals;
3490 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003491
Douglas Gregor20093b42009-12-09 23:02:17 +00003492 // If the initializer is the address of an overloaded function, try
3493 // to resolve the overloaded function. If all goes well, T2 is the
3494 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003495 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3496 T1, Sequence))
3497 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003498
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003499 // Delegate everything else to a subfunction.
3500 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3501 T1Quals, cv2T2, T2, T2Quals, Sequence);
3502}
3503
Jordan Rose1fd1e282013-04-11 00:58:58 +00003504/// Converts the target of reference initialization so that it has the
3505/// appropriate qualifiers and value kind.
3506///
3507/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3508/// \code
3509/// int x;
3510/// const int &r = x;
3511/// \endcode
3512///
3513/// In this case the reference is binding to a bitfield lvalue, which isn't
3514/// valid. Perform a load to create a lifetime-extended temporary instead.
3515/// \code
3516/// const int &r = someStruct.bitfield;
3517/// \endcode
3518static ExprValueKind
3519convertQualifiersAndValueKindIfNecessary(Sema &S,
3520 InitializationSequence &Sequence,
3521 Expr *Initializer,
3522 QualType cv1T1,
3523 Qualifiers T1Quals,
3524 Qualifiers T2Quals,
3525 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003526 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003527 Initializer->refersToVectorElement();
3528
3529 if (IsNonAddressableType) {
3530 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3531 // lvalue reference to a non-volatile const type, or the reference shall be
3532 // an rvalue reference.
3533 //
3534 // If not, we can't make a temporary and bind to that. Give up and allow the
3535 // error to be diagnosed later.
3536 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3537 assert(Initializer->isGLValue());
3538 return Initializer->getValueKind();
3539 }
3540
3541 // Force a load so we can materialize a temporary.
3542 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3543 return VK_RValue;
3544 }
3545
3546 if (T1Quals != T2Quals) {
3547 Sequence.AddQualificationConversionStep(cv1T1,
3548 Initializer->getValueKind());
3549 }
3550
3551 return Initializer->getValueKind();
3552}
3553
3554
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003555/// \brief Reference initialization without resolving overloaded functions.
3556static void TryReferenceInitializationCore(Sema &S,
3557 const InitializedEntity &Entity,
3558 const InitializationKind &Kind,
3559 Expr *Initializer,
3560 QualType cv1T1, QualType T1,
3561 Qualifiers T1Quals,
3562 QualType cv2T2, QualType T2,
3563 Qualifiers T2Quals,
3564 InitializationSequence &Sequence) {
3565 QualType DestType = Entity.getType();
3566 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003567 // Compute some basic properties of the types and the initializer.
3568 bool isLValueRef = DestType->isLValueReferenceType();
3569 bool isRValueRef = !isLValueRef;
3570 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003571 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003572 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003573 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003574 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003575 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003576 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003577
Douglas Gregor20093b42009-12-09 23:02:17 +00003578 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003579 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003580 // "cv2 T2" as follows:
3581 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003582 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003583 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003584 // Note the analogous bullet points for rvlaue refs to functions. Because
3585 // there are no function rvalues in C++, rvalue refs to functions are treated
3586 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003587 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003588 bool T1Function = T1->isFunctionType();
3589 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003590 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003591 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003592 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003593 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003594 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003595 // reference-compatible with "cv2 T2," or
3596 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003597 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003598 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003599 // can occur. However, we do pay attention to whether it is a bit-field
3600 // to decide whether we're actually binding to a temporary created from
3601 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003602 if (DerivedToBase)
3603 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003604 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003605 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003606 else if (ObjCConversion)
3607 Sequence.AddObjCObjectConversionStep(
3608 S.Context.getQualifiedType(T1, T2Quals));
3609
Jordan Rose1fd1e282013-04-11 00:58:58 +00003610 ExprValueKind ValueKind =
3611 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3612 cv1T1, T1Quals, T2Quals,
3613 isLValueRef);
3614 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003615 return;
3616 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003617
3618 // - has a class type (i.e., T2 is a class type), where T1 is not
3619 // reference-related to T2, and can be implicitly converted to an
3620 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3621 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003622 // applicable conversion functions (13.3.1.6) and choosing the best
3623 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003624 // If we have an rvalue ref to function type here, the rhs must be
3625 // an rvalue.
3626 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3627 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003628 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003629 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003630 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003631 Sequence);
3632 if (ConvOvlResult == OR_Success)
3633 return;
John McCall1d318332010-01-12 00:44:57 +00003634 if (ConvOvlResult != OR_No_Viable_Function) {
3635 Sequence.SetOverloadFailure(
3636 InitializationSequence::FK_ReferenceInitOverloadFailed,
3637 ConvOvlResult);
3638 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003639 }
3640 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003641
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003642 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003643 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003644 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003645 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003646 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3647 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3648 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003649 Sequence.SetOverloadFailure(
3650 InitializationSequence::FK_ReferenceInitOverloadFailed,
3651 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003652 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003653 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003654 ? (RefRelationship == Sema::Ref_Related
3655 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3656 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3657 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003658
Douglas Gregor20093b42009-12-09 23:02:17 +00003659 return;
3660 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003661
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003662 // - If the initializer expression
3663 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3664 // "cv1 T1" is reference-compatible with "cv2 T2"
3665 // Note: functions are handled below.
3666 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003667 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003668 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003669 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003670 (InitCategory.isXValue() ||
3671 (InitCategory.isPRValue() && T2->isRecordType()) ||
3672 (InitCategory.isPRValue() && T2->isArrayType()))) {
3673 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3674 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003675 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3676 // compiler the freedom to perform a copy here or bind to the
3677 // object, while C++0x requires that we bind directly to the
3678 // object. Hence, we always bind to the object without making an
3679 // extra copy. However, in C++03 requires that we check for the
3680 // presence of a suitable copy constructor:
3681 //
3682 // The constructor that would be used to make the copy shall
3683 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003684 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003685 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003686 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003687 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003688 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003689
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003690 if (DerivedToBase)
3691 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3692 ValueKind);
3693 else if (ObjCConversion)
3694 Sequence.AddObjCObjectConversionStep(
3695 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003696
Jordan Rose1fd1e282013-04-11 00:58:58 +00003697 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3698 Initializer, cv1T1,
3699 T1Quals, T2Quals,
3700 isLValueRef);
3701
3702 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003703 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003704 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003705
3706 // - has a class type (i.e., T2 is a class type), where T1 is not
3707 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003708 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3709 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003710 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003711 if (RefRelationship == Sema::Ref_Incompatible) {
3712 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3713 Kind, Initializer,
3714 /*AllowRValues=*/true,
3715 Sequence);
3716 if (ConvOvlResult)
3717 Sequence.SetOverloadFailure(
3718 InitializationSequence::FK_ReferenceInitOverloadFailed,
3719 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003720
Douglas Gregor20093b42009-12-09 23:02:17 +00003721 return;
3722 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723
Douglas Gregordefa32e2013-03-26 23:59:23 +00003724 if ((RefRelationship == Sema::Ref_Compatible ||
3725 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3726 isRValueRef && InitCategory.isLValue()) {
3727 Sequence.SetFailed(
3728 InitializationSequence::FK_RValueReferenceBindingToLValue);
3729 return;
3730 }
3731
Douglas Gregor20093b42009-12-09 23:02:17 +00003732 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3733 return;
3734 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003735
3736 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003737 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003738 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003739 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003740
Douglas Gregor20093b42009-12-09 23:02:17 +00003741 // Determine whether we are allowed to call explicit constructors or
3742 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003743 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003744
3745 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3746
John McCallf85e1932011-06-15 23:02:42 +00003747 ImplicitConversionSequence ICS
3748 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003749 /*SuppressUserConversions*/ false,
3750 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003751 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003752 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3753 /*AllowObjCWritebackConversion=*/false);
3754
3755 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003756 // FIXME: Use the conversion function set stored in ICS to turn
3757 // this into an overloading ambiguity diagnostic. However, we need
3758 // to keep that set as an OverloadCandidateSet rather than as some
3759 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003760 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3761 Sequence.SetOverloadFailure(
3762 InitializationSequence::FK_ReferenceInitOverloadFailed,
3763 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003764 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3765 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003766 else
3767 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003768 return;
John McCallf85e1932011-06-15 23:02:42 +00003769 } else {
3770 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003771 }
3772
3773 // [...] If T1 is reference-related to T2, cv1 must be the
3774 // same cv-qualification as, or greater cv-qualification
3775 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003776 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3777 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003779 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003780 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3781 return;
3782 }
3783
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003784 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003785 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003786 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003787 InitCategory.isLValue()) {
3788 Sequence.SetFailed(
3789 InitializationSequence::FK_RValueReferenceBindingToLValue);
3790 return;
3791 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
Douglas Gregor20093b42009-12-09 23:02:17 +00003793 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3794 return;
3795}
3796
3797/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798/// (C++ [dcl.init.string], C99 6.7.8).
3799static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003800 const InitializedEntity &Entity,
3801 const InitializationKind &Kind,
3802 Expr *Initializer,
3803 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003804 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003805}
3806
Douglas Gregor71d17402009-12-15 00:01:57 +00003807/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003808static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003809 const InitializedEntity &Entity,
3810 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003811 InitializationSequence &Sequence,
3812 InitListExpr *InitList) {
3813 assert((!InitList || InitList->getNumInits() == 0) &&
3814 "Shouldn't use value-init for non-empty init lists");
3815
Richard Smith1d0c9a82012-02-14 21:14:13 +00003816 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003817 //
3818 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003819 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003820
Douglas Gregor71d17402009-12-15 00:01:57 +00003821 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003822 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
Douglas Gregor71d17402009-12-15 00:01:57 +00003824 if (const RecordType *RT = T->getAs<RecordType>()) {
3825 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003826 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003827 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003828 // C++98:
3829 // -- if T is a class type (clause 9) with a user-declared constructor
3830 // (12.1), then the default constructor for T is called (and the
3831 // initialization is ill-formed if T has no accessible default
3832 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003833 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003834 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003835 } else {
3836 // C++11:
3837 // -- if T is a class type (clause 9) with either no default constructor
3838 // (12.1 [class.ctor]) or a default constructor that is user-provided
3839 // or deleted, then the object is default-initialized;
3840 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3841 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003842 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003843 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844
Richard Smith1d0c9a82012-02-14 21:14:13 +00003845 // -- if T is a (possibly cv-qualified) non-union class type without a
3846 // user-provided or deleted default constructor, then the object is
3847 // zero-initialized and, if T has a non-trivial default constructor,
3848 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003849 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3850 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003851 if (NeedZeroInitialization)
3852 Sequence.AddZeroInitializationStep(Entity.getType());
3853
Richard Smithd5bc8672012-12-08 02:01:17 +00003854 // C++03:
3855 // -- if T is a non-union class type without a user-declared constructor,
3856 // then every non-static data member and base class component of T is
3857 // value-initialized;
3858 // [...] A program that calls for [...] value-initialization of an
3859 // entity of reference type is ill-formed.
3860 //
3861 // C++11 doesn't need this handling, because value-initialization does not
3862 // occur recursively there, and the implicit default constructor is
3863 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003864 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003865 ClassDecl->hasUninitializedReferenceMember()) {
3866 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3867 return;
3868 }
3869
Richard Smithf4bb8d02012-07-05 08:39:21 +00003870 // If this is list-value-initialization, pass the empty init list on when
3871 // building the constructor call. This affects the semantics of a few
3872 // things (such as whether an explicit default constructor can be called).
3873 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003874 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003875 bool InitListSyntax = InitList;
3876
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003877 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3878 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003879 }
3880 }
3881
Douglas Gregord6542d82009-12-22 15:35:07 +00003882 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003883}
3884
Douglas Gregor99a2e602009-12-16 01:38:02 +00003885/// \brief Attempt default initialization (C++ [dcl.init]p6).
3886static void TryDefaultInitialization(Sema &S,
3887 const InitializedEntity &Entity,
3888 const InitializationKind &Kind,
3889 InitializationSequence &Sequence) {
3890 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003891
Douglas Gregor99a2e602009-12-16 01:38:02 +00003892 // C++ [dcl.init]p6:
3893 // To default-initialize an object of type T means:
3894 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003895 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3896
Douglas Gregor99a2e602009-12-16 01:38:02 +00003897 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3898 // constructor for T is called (and the initialization is ill-formed if
3899 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003900 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003901 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003902 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003903 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003904
Douglas Gregor99a2e602009-12-16 01:38:02 +00003905 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003906
Douglas Gregor99a2e602009-12-16 01:38:02 +00003907 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003908 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003909 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003910 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003911 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003912 return;
3913 }
3914
3915 // If the destination type has a lifetime property, zero-initialize it.
3916 if (DestType.getQualifiers().hasObjCLifetime()) {
3917 Sequence.AddZeroInitializationStep(Entity.getType());
3918 return;
3919 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003920}
3921
Douglas Gregor20093b42009-12-09 23:02:17 +00003922/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3923/// which enumerates all conversion functions and performs overload resolution
3924/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003926 const InitializedEntity &Entity,
3927 const InitializationKind &Kind,
3928 Expr *Initializer,
3929 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003930 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003931 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3932 QualType SourceType = Initializer->getType();
3933 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3934 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003935
Douglas Gregor4a520a22009-12-14 17:27:33 +00003936 // Build the candidate set directly in the initialization sequence
3937 // structure, so that it will persist if we fail.
3938 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3939 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003940
Douglas Gregor4a520a22009-12-14 17:27:33 +00003941 // Determine whether we are allowed to call explicit constructors or
3942 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003943 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944
Douglas Gregor4a520a22009-12-14 17:27:33 +00003945 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3946 // The type we're converting to is a class type. Enumerate its constructors
3947 // to see if there is a suitable conversion.
3948 CXXRecordDecl *DestRecordDecl
3949 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003950
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003951 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003952 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003953 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003954 // The container holding the constructors can under certain conditions
3955 // be changed while iterating. To be safe we copy the lookup results
3956 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003957 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003958 for (SmallVector<NamedDecl*, 8>::iterator
3959 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003960 Con != ConEnd; ++Con) {
3961 NamedDecl *D = *Con;
3962 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003963
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003964 // Find the constructor (which may be a template).
3965 CXXConstructorDecl *Constructor = 0;
3966 FunctionTemplateDecl *ConstructorTmpl
3967 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003968 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003969 Constructor = cast<CXXConstructorDecl>(
3970 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003971 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003972 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003973
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003974 if (!Constructor->isInvalidDecl() &&
3975 Constructor->isConvertingConstructor(AllowExplicit)) {
3976 if (ConstructorTmpl)
3977 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3978 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003979 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003980 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003981 else
3982 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003983 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003984 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003985 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003986 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003987 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003988 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003989
3990 SourceLocation DeclLoc = Initializer->getLocStart();
3991
Douglas Gregor4a520a22009-12-14 17:27:33 +00003992 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3993 // The type we're converting from is a class type, enumerate its conversion
3994 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003995
Eli Friedman33c2da92009-12-20 22:12:03 +00003996 // We can only enumerate the conversion functions for a complete type; if
3997 // the type isn't complete, simply skip this step.
3998 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3999 CXXRecordDecl *SourceRecordDecl
4000 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004002 std::pair<CXXRecordDecl::conversion_iterator,
4003 CXXRecordDecl::conversion_iterator>
4004 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4005 for (CXXRecordDecl::conversion_iterator
4006 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00004007 NamedDecl *D = *I;
4008 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4009 if (isa<UsingShadowDecl>(D))
4010 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004011
Eli Friedman33c2da92009-12-20 22:12:03 +00004012 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4013 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00004014 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00004015 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00004016 else
John McCall32daa422010-03-31 01:36:47 +00004017 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004018
Eli Friedman33c2da92009-12-20 22:12:03 +00004019 if (AllowExplicit || !Conv->isExplicit()) {
4020 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00004021 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00004022 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00004023 CandidateSet);
4024 else
John McCall9aa472c2010-03-19 07:35:19 +00004025 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00004026 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00004027 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004028 }
4029 }
4030 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004031
4032 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004033 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004034 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004035 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004036 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004037 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004038 Result);
4039 return;
4040 }
John McCall1d318332010-01-12 00:44:57 +00004041
Douglas Gregor4a520a22009-12-14 17:27:33 +00004042 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004043 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004044 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004045
Douglas Gregor4a520a22009-12-14 17:27:33 +00004046 if (isa<CXXConstructorDecl>(Function)) {
4047 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004048 // subsumed by the initialization. Per DR5, the created temporary is of the
4049 // cv-unqualified type of the destination.
4050 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4051 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004052 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004053 return;
4054 }
4055
4056 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004057 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004058 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004059 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004060 // the resulting temporary object (possible to create an object of
4061 // a base class type). That copy is not a separate conversion, so
4062 // we just make a note of the actual destination type (possibly a
4063 // base class of the type returned by the conversion function) and
4064 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004065 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4066 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004067 return;
4068 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004069
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004070 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4071 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004072
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004073 // If the conversion following the call to the conversion function
4074 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004075 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4076 Best->FinalConversion.Third) {
4077 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004078 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004079 ICS.Standard = Best->FinalConversion;
4080 Sequence.AddConversionSequenceStep(ICS, DestType);
4081 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004082}
4083
John McCallf85e1932011-06-15 23:02:42 +00004084/// The non-zero enum values here are indexes into diagnostic alternatives.
4085enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4086
4087/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004088static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004089 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004090 // Skip parens.
4091 e = e->IgnoreParens();
4092
4093 // Skip address-of nodes.
4094 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4095 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004096 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4097 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004098
4099 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004100 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4101 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004102 case CK_Dependent:
4103 case CK_BitCast:
4104 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004105 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004106 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004107
4108 case CK_ArrayToPointerDecay:
4109 return IIK_nonscalar;
4110
4111 case CK_NullToPointer:
4112 return IIK_okay;
4113
4114 default:
4115 break;
4116 }
4117
4118 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004119 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004120 // set isWeakAccess to true, to mean that there will be an implicit
4121 // load which requires a cleanup.
4122 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4123 isWeakAccess = true;
4124
John McCallc03fa492011-06-27 23:59:58 +00004125 if (!isAddressOf) return IIK_nonlocal;
4126
John McCallf4b88a42012-03-10 09:33:50 +00004127 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4128 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004129
4130 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004131
4132 // If we have a conditional operator, check both sides.
4133 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004134 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4135 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004136 return iik;
4137
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004138 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004139
4140 // These are never scalar.
4141 } else if (isa<ArraySubscriptExpr>(e)) {
4142 return IIK_nonscalar;
4143
4144 // Otherwise, it needs to be a null pointer constant.
4145 } else {
4146 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4147 ? IIK_okay : IIK_nonlocal);
4148 }
4149
4150 return IIK_nonlocal;
4151}
4152
4153/// Check whether the given expression is a valid operand for an
4154/// indirect copy/restore.
4155static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4156 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004157 bool isWeakAccess = false;
4158 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4159 // If isWeakAccess to true, there will be an implicit
4160 // load which requires a cleanup.
4161 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4162 S.ExprNeedsCleanups = true;
4163
John McCallf85e1932011-06-15 23:02:42 +00004164 if (iik == IIK_okay) return;
4165
4166 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4167 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4168 << src->getSourceRange();
4169}
4170
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004171/// \brief Determine whether we have compatible array types for the
4172/// purposes of GNU by-copy array initialization.
4173static bool hasCompatibleArrayTypes(ASTContext &Context,
4174 const ArrayType *Dest,
4175 const ArrayType *Source) {
4176 // If the source and destination array types are equivalent, we're
4177 // done.
4178 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4179 return true;
4180
4181 // Make sure that the element types are the same.
4182 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4183 return false;
4184
4185 // The only mismatch we allow is when the destination is an
4186 // incomplete array type and the source is a constant array type.
4187 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4188}
4189
John McCallf85e1932011-06-15 23:02:42 +00004190static bool tryObjCWritebackConversion(Sema &S,
4191 InitializationSequence &Sequence,
4192 const InitializedEntity &Entity,
4193 Expr *Initializer) {
4194 bool ArrayDecay = false;
4195 QualType ArgType = Initializer->getType();
4196 QualType ArgPointee;
4197 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4198 ArrayDecay = true;
4199 ArgPointee = ArgArrayType->getElementType();
4200 ArgType = S.Context.getPointerType(ArgPointee);
4201 }
4202
4203 // Handle write-back conversion.
4204 QualType ConvertedArgType;
4205 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4206 ConvertedArgType))
4207 return false;
4208
4209 // We should copy unless we're passing to an argument explicitly
4210 // marked 'out'.
4211 bool ShouldCopy = true;
4212 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4213 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4214
4215 // Do we need an lvalue conversion?
4216 if (ArrayDecay || Initializer->isGLValue()) {
4217 ImplicitConversionSequence ICS;
4218 ICS.setStandard();
4219 ICS.Standard.setAsIdentityConversion();
4220
4221 QualType ResultType;
4222 if (ArrayDecay) {
4223 ICS.Standard.First = ICK_Array_To_Pointer;
4224 ResultType = S.Context.getPointerType(ArgPointee);
4225 } else {
4226 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4227 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4228 }
4229
4230 Sequence.AddConversionSequenceStep(ICS, ResultType);
4231 }
4232
4233 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4234 return true;
4235}
4236
Guy Benyei21f18c42013-02-07 10:55:47 +00004237static bool TryOCLSamplerInitialization(Sema &S,
4238 InitializationSequence &Sequence,
4239 QualType DestType,
4240 Expr *Initializer) {
4241 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4242 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4243 return false;
4244
4245 Sequence.AddOCLSamplerInitStep(DestType);
4246 return true;
4247}
4248
Guy Benyeie6b9d802013-01-20 12:31:11 +00004249//
4250// OpenCL 1.2 spec, s6.12.10
4251//
4252// The event argument can also be used to associate the
4253// async_work_group_copy with a previous async copy allowing
4254// an event to be shared by multiple async copies; otherwise
4255// event should be zero.
4256//
4257static bool TryOCLZeroEventInitialization(Sema &S,
4258 InitializationSequence &Sequence,
4259 QualType DestType,
4260 Expr *Initializer) {
4261 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4262 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4263 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4264 return false;
4265
4266 Sequence.AddOCLZeroEventStep(DestType);
4267 return true;
4268}
4269
Douglas Gregor20093b42009-12-09 23:02:17 +00004270InitializationSequence::InitializationSequence(Sema &S,
4271 const InitializedEntity &Entity,
4272 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004273 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004274 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004275 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004276
John McCall76da55d2013-04-16 07:28:30 +00004277 // Eliminate non-overload placeholder types in the arguments. We
4278 // need to do this before checking whether types are dependent
4279 // because lowering a pseudo-object expression might well give us
4280 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004281 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004282 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4283 // FIXME: should we be doing this here?
4284 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4285 if (result.isInvalid()) {
4286 SetFailed(FK_PlaceholderType);
4287 return;
4288 }
4289 Args[I] = result.take();
4290 }
4291
Douglas Gregor20093b42009-12-09 23:02:17 +00004292 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004293 // The semantics of initializers are as follows. The destination type is
4294 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004295 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004296 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004297 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004298 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004299
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004300 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004301 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004302 SequenceKind = DependentSequence;
4303 return;
4304 }
4305
Sebastian Redl7491c492011-06-05 13:59:11 +00004306 // Almost everything is a normal sequence.
4307 setSequenceKind(NormalSequence);
4308
Douglas Gregor20093b42009-12-09 23:02:17 +00004309 QualType SourceType;
4310 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004311 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004312 Initializer = Args[0];
4313 if (!isa<InitListExpr>(Initializer))
4314 SourceType = Initializer->getType();
4315 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004317 // - If the initializer is a (non-parenthesized) braced-init-list, the
4318 // object is list-initialized (8.5.4).
4319 if (Kind.getKind() != InitializationKind::IK_Direct) {
4320 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4321 TryListInitialization(S, Entity, Kind, InitList, *this);
4322 return;
4323 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004324 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004325
Douglas Gregor20093b42009-12-09 23:02:17 +00004326 // - If the destination type is a reference type, see 8.5.3.
4327 if (DestType->isReferenceType()) {
4328 // C++0x [dcl.init.ref]p1:
4329 // A variable declared to be a T& or T&&, that is, "reference to type T"
4330 // (8.3.2), shall be initialized by an object, or function, of type T or
4331 // by an object that can be converted into a T.
4332 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004333 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004334 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004335 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004336 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004337 return;
4338 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004339
Douglas Gregor20093b42009-12-09 23:02:17 +00004340 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004341 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004342 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004343 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004344 return;
4345 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004346
Douglas Gregor99a2e602009-12-16 01:38:02 +00004347 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004348 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004349 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004350 return;
4351 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004352
John McCallce6c9b72011-02-21 07:22:22 +00004353 // - If the destination type is an array of characters, an array of
4354 // char16_t, an array of char32_t, or an array of wchar_t, and the
4355 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004356 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004357 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004358 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004359 if (Initializer && isa<VariableArrayType>(DestAT)) {
4360 SetFailed(FK_VariableLengthArrayHasInitializer);
4361 return;
4362 }
4363
Hans Wennborg0ff50742013-05-15 11:03:04 +00004364 if (Initializer) {
4365 switch (IsStringInit(Initializer, DestAT, Context)) {
4366 case SIF_None:
4367 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4368 return;
4369 case SIF_NarrowStringIntoWideChar:
4370 SetFailed(FK_NarrowStringIntoWideCharArray);
4371 return;
4372 case SIF_WideStringIntoChar:
4373 SetFailed(FK_WideStringIntoCharArray);
4374 return;
4375 case SIF_IncompatWideStringIntoWideChar:
4376 SetFailed(FK_IncompatWideStringIntoWideChar);
4377 return;
4378 case SIF_Other:
4379 break;
4380 }
John McCallce6c9b72011-02-21 07:22:22 +00004381 }
4382
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004383 // Note: as an GNU C extension, we allow initialization of an
4384 // array from a compound literal that creates an array of the same
4385 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004386 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004387 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4388 Initializer->getType()->isArrayType()) {
4389 const ArrayType *SourceAT
4390 = Context.getAsArrayType(Initializer->getType());
4391 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004392 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004393 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004394 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004395 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004396 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004397 }
Richard Smith0f163e92012-02-15 22:38:09 +00004398 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004399 // Note: as a GNU C++ extension, we allow list-initialization of a
4400 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004401 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004402 Entity.getKind() == InitializedEntity::EK_Member &&
4403 Initializer && isa<InitListExpr>(Initializer)) {
4404 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4405 *this);
4406 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004407 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004408 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004409 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4410 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004411 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004412 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004413
Douglas Gregor20093b42009-12-09 23:02:17 +00004414 return;
4415 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004416
John McCallf85e1932011-06-15 23:02:42 +00004417 // Determine whether we should consider writeback conversions for
4418 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004419 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004420 Entity.getKind() == InitializedEntity::EK_Parameter;
4421
4422 // We're at the end of the line for C: it's either a write-back conversion
4423 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004424 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004425 // If allowed, check whether this is an Objective-C writeback conversion.
4426 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004427 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004428 return;
4429 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004430
4431 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4432 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004433
4434 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4435 return;
4436
John McCallf85e1932011-06-15 23:02:42 +00004437 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004438 AddCAssignmentStep(DestType);
4439 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004440 return;
4441 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004442
David Blaikie4e4d0842012-03-11 07:00:24 +00004443 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004444
Douglas Gregor20093b42009-12-09 23:02:17 +00004445 // - If the destination type is a (possibly cv-qualified) class type:
4446 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004447 // - If the initialization is direct-initialization, or if it is
4448 // copy-initialization where the cv-unqualified version of the
4449 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004450 // class of the destination, constructors are considered. [...]
4451 if (Kind.getKind() == InitializationKind::IK_Direct ||
4452 (Kind.getKind() == InitializationKind::IK_Copy &&
4453 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4454 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004455 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004456 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004458 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004459 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004460 // used) to a derived class thereof are enumerated as described in
4461 // 13.3.1.4, and the best one is chosen through overload resolution
4462 // (13.3).
4463 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004464 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004465 return;
4466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004468 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004469 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004470 return;
4471 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004472 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004473
4474 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004475 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004476 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004477 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4478 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004479 return;
4480 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004481
Douglas Gregor20093b42009-12-09 23:02:17 +00004482 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004483 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004484 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004485 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004486 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004487
4488 ImplicitConversionSequence ICS
4489 = S.TryImplicitConversion(Initializer, Entity.getType(),
4490 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004491 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004492 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004493 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4494 allowObjCWritebackConversion);
4495
4496 if (ICS.isStandard() &&
4497 ICS.Standard.Second == ICK_Writeback_Conversion) {
4498 // Objective-C ARC writeback conversion.
4499
4500 // We should copy unless we're passing to an argument explicitly
4501 // marked 'out'.
4502 bool ShouldCopy = true;
4503 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4504 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4505
4506 // If there was an lvalue adjustment, add it as a separate conversion.
4507 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4508 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4509 ImplicitConversionSequence LvalueICS;
4510 LvalueICS.setStandard();
4511 LvalueICS.Standard.setAsIdentityConversion();
4512 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4513 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004514 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004515 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004516
4517 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004518 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004519 DeclAccessPair dap;
4520 if (Initializer->getType() == Context.OverloadTy &&
4521 !S.ResolveAddressOfOverloadedFunction(Initializer
4522 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004523 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004524 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004525 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004526 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004527 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004528
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004529 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004530 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004531}
4532
4533InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004534 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004535 StepEnd = Steps.end();
4536 Step != StepEnd; ++Step)
4537 Step->Destroy();
4538}
4539
4540//===----------------------------------------------------------------------===//
4541// Perform initialization
4542//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004543static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004544getAssignmentAction(const InitializedEntity &Entity) {
4545 switch(Entity.getKind()) {
4546 case InitializedEntity::EK_Variable:
4547 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004548 case InitializedEntity::EK_Exception:
4549 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004550 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004551 return Sema::AA_Initializing;
4552
4553 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004554 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004555 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4556 return Sema::AA_Sending;
4557
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004558 return Sema::AA_Passing;
4559
4560 case InitializedEntity::EK_Result:
4561 return Sema::AA_Returning;
4562
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004563 case InitializedEntity::EK_Temporary:
4564 // FIXME: Can we tell apart casting vs. converting?
4565 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004566
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004567 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004568 case InitializedEntity::EK_ArrayElement:
4569 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004570 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004571 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004572 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004573 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004574 return Sema::AA_Initializing;
4575 }
4576
David Blaikie7530c032012-01-17 06:56:22 +00004577 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004578}
4579
Richard Smith774d8b42013-01-08 00:08:23 +00004580/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004581/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004582static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004583 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004584 case InitializedEntity::EK_ArrayElement:
4585 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004586 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004587 case InitializedEntity::EK_New:
4588 case InitializedEntity::EK_Variable:
4589 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004590 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004591 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004592 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004593 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004594 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004595 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004596 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004597 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004598
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004599 case InitializedEntity::EK_Parameter:
4600 case InitializedEntity::EK_Temporary:
4601 return true;
4602 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004603
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004604 llvm_unreachable("missed an InitializedEntity kind?");
4605}
4606
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004607/// \brief Whether the given entity, when initialized with an object
4608/// created for that initialization, requires destruction.
4609static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4610 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004611 case InitializedEntity::EK_Result:
4612 case InitializedEntity::EK_New:
4613 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004614 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004615 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004616 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004617 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004618 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004619 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004620
Richard Smith774d8b42013-01-08 00:08:23 +00004621 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004622 case InitializedEntity::EK_Variable:
4623 case InitializedEntity::EK_Parameter:
4624 case InitializedEntity::EK_Temporary:
4625 case InitializedEntity::EK_ArrayElement:
4626 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004627 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004628 return true;
4629 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004630
4631 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004632}
4633
Richard Smith83da2e72011-10-19 16:55:56 +00004634/// \brief Look for copy and move constructors and constructor templates, for
4635/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4636static void LookupCopyAndMoveConstructors(Sema &S,
4637 OverloadCandidateSet &CandidateSet,
4638 CXXRecordDecl *Class,
4639 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004640 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004641 // The container holding the constructors can under certain conditions
4642 // be changed while iterating (e.g. because of deserialization).
4643 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004644 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004645 for (SmallVector<NamedDecl*, 16>::iterator
4646 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4647 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004648 CXXConstructorDecl *Constructor = 0;
4649
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004650 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004651 // Handle copy/moveconstructors, only.
4652 if (!Constructor || Constructor->isInvalidDecl() ||
4653 !Constructor->isCopyOrMoveConstructor() ||
4654 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4655 continue;
4656
4657 DeclAccessPair FoundDecl
4658 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4659 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004660 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004661 continue;
4662 }
4663
4664 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004665 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004666 if (ConstructorTmpl->isInvalidDecl())
4667 continue;
4668
4669 Constructor = cast<CXXConstructorDecl>(
4670 ConstructorTmpl->getTemplatedDecl());
4671 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4672 continue;
4673
4674 // FIXME: Do we need to limit this to copy-constructor-like
4675 // candidates?
4676 DeclAccessPair FoundDecl
4677 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4678 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004679 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004680 }
4681}
4682
4683/// \brief Get the location at which initialization diagnostics should appear.
4684static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4685 Expr *Initializer) {
4686 switch (Entity.getKind()) {
4687 case InitializedEntity::EK_Result:
4688 return Entity.getReturnLoc();
4689
4690 case InitializedEntity::EK_Exception:
4691 return Entity.getThrowLoc();
4692
4693 case InitializedEntity::EK_Variable:
4694 return Entity.getDecl()->getLocation();
4695
Douglas Gregor47736542012-02-15 16:57:26 +00004696 case InitializedEntity::EK_LambdaCapture:
4697 return Entity.getCaptureLoc();
4698
Richard Smith83da2e72011-10-19 16:55:56 +00004699 case InitializedEntity::EK_ArrayElement:
4700 case InitializedEntity::EK_Member:
4701 case InitializedEntity::EK_Parameter:
4702 case InitializedEntity::EK_Temporary:
4703 case InitializedEntity::EK_New:
4704 case InitializedEntity::EK_Base:
4705 case InitializedEntity::EK_Delegating:
4706 case InitializedEntity::EK_VectorElement:
4707 case InitializedEntity::EK_ComplexElement:
4708 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004709 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith83da2e72011-10-19 16:55:56 +00004710 return Initializer->getLocStart();
4711 }
4712 llvm_unreachable("missed an InitializedEntity kind?");
4713}
4714
Douglas Gregor523d46a2010-04-18 07:40:54 +00004715/// \brief Make a (potentially elidable) temporary copy of the object
4716/// provided by the given initializer by calling the appropriate copy
4717/// constructor.
4718///
4719/// \param S The Sema object used for type-checking.
4720///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004721/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004722/// the type of the initializer expression or a superclass thereof.
4723///
James Dennett1dfbd922012-06-14 21:40:34 +00004724/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004725///
4726/// \param CurInit The initializer expression.
4727///
4728/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4729/// is permitted in C++03 (but not C++0x) when binding a reference to
4730/// an rvalue.
4731///
4732/// \returns An expression that copies the initializer expression into
4733/// a temporary object, or an error expression if a copy could not be
4734/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004735static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004736 QualType T,
4737 const InitializedEntity &Entity,
4738 ExprResult CurInit,
4739 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004740 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004741 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004742 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004743 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004744 Class = cast<CXXRecordDecl>(Record->getDecl());
4745 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004746 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004747
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004748 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004749 // When certain criteria are met, an implementation is allowed to
4750 // omit the copy/move construction of a class object, even if the
4751 // copy/move constructor and/or destructor for the object have
4752 // side effects. [...]
4753 // - when a temporary class object that has not been bound to a
4754 // reference (12.2) would be copied/moved to a class object
4755 // with the same cv-unqualified type, the copy/move operation
4756 // can be omitted by constructing the temporary object
4757 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004758 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004759 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004760 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004761 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004762 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004763 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004764 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004765
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004766 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004767 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004768 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004769
Douglas Gregorcc15f012011-01-21 19:38:21 +00004770 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004771 // Only consider constructors and constructor templates. Per
4772 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4773 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004774 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004775 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004776
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004777 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4778
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004779 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004780 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004781 case OR_Success:
4782 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004783
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004784 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004785 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4786 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4787 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004788 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004789 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004790 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004791 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004792 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004793 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004794
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004795 case OR_Ambiguous:
4796 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004797 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004798 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004799 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004800 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004801
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004802 case OR_Deleted:
4803 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004804 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004805 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004806 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004807 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004808 }
4809
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004810 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004811 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004812 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004813
Anders Carlsson9a68a672010-04-21 18:47:17 +00004814 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004815 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004816
4817 if (IsExtraneousCopy) {
4818 // If this is a totally extraneous copy for C++03 reference
4819 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004820 // expression. We don't generate an (elided) copy operation here
4821 // because doing so would require us to pass down a flag to avoid
4822 // infinite recursion, where each step adds another extraneous,
4823 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004824
Douglas Gregor2559a702010-04-18 07:57:34 +00004825 // Instantiate the default arguments of any extra parameters in
4826 // the selected copy constructor, as if we were going to create a
4827 // proper call to the copy constructor.
4828 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4829 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4830 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004831 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004832 break;
4833
4834 // Build the default argument expression; we don't actually care
4835 // if this succeeds or not, because this routine will complain
4836 // if there was a problem.
4837 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4838 }
4839
Douglas Gregor523d46a2010-04-18 07:40:54 +00004840 return S.Owned(CurInitExpr);
4841 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004842
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004843 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004844 // constructor call (we might have derived-to-base conversions, or
4845 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004846 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004847 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004848
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004849 // Actually perform the constructor call.
4850 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004851 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004852 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004853 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004854 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004855 CXXConstructExpr::CK_Complete,
4856 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004857
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004858 // If we're supposed to bind temporaries, do so.
4859 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4860 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004861 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004862}
Douglas Gregor20093b42009-12-09 23:02:17 +00004863
Richard Smith83da2e72011-10-19 16:55:56 +00004864/// \brief Check whether elidable copy construction for binding a reference to
4865/// a temporary would have succeeded if we were building in C++98 mode, for
4866/// -Wc++98-compat.
4867static void CheckCXX98CompatAccessibleCopy(Sema &S,
4868 const InitializedEntity &Entity,
4869 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004870 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004871
4872 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4873 if (!Record)
4874 return;
4875
4876 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4877 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4878 == DiagnosticsEngine::Ignored)
4879 return;
4880
4881 // Find constructors which would have been considered.
4882 OverloadCandidateSet CandidateSet(Loc);
4883 LookupCopyAndMoveConstructors(
4884 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4885
4886 // Perform overload resolution.
4887 OverloadCandidateSet::iterator Best;
4888 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4889
4890 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4891 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4892 << CurInitExpr->getSourceRange();
4893
4894 switch (OR) {
4895 case OR_Success:
4896 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004897 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004898 // FIXME: Check default arguments as far as that's possible.
4899 break;
4900
4901 case OR_No_Viable_Function:
4902 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004903 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004904 break;
4905
4906 case OR_Ambiguous:
4907 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004908 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004909 break;
4910
4911 case OR_Deleted:
4912 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004913 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004914 break;
4915 }
4916}
4917
Douglas Gregora41a8c52010-04-22 00:20:18 +00004918void InitializationSequence::PrintInitLocationNote(Sema &S,
4919 const InitializedEntity &Entity) {
4920 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4921 if (Entity.getDecl()->getLocation().isInvalid())
4922 return;
4923
4924 if (Entity.getDecl()->getDeclName())
4925 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4926 << Entity.getDecl()->getDeclName();
4927 else
4928 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4929 }
4930}
4931
Sebastian Redl3b802322011-07-14 19:07:55 +00004932static bool isReferenceBinding(const InitializationSequence::Step &s) {
4933 return s.Kind == InitializationSequence::SK_BindReference ||
4934 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4935}
4936
Jordan Rose2624b812013-05-06 16:48:12 +00004937/// Returns true if the parameters describe a constructor initialization of
4938/// an explicit temporary object, e.g. "Point(x, y)".
4939static bool isExplicitTemporary(const InitializedEntity &Entity,
4940 const InitializationKind &Kind,
4941 unsigned NumArgs) {
4942 switch (Entity.getKind()) {
4943 case InitializedEntity::EK_Temporary:
4944 case InitializedEntity::EK_CompoundLiteralInit:
4945 break;
4946 default:
4947 return false;
4948 }
4949
4950 switch (Kind.getKind()) {
4951 case InitializationKind::IK_DirectList:
4952 return true;
4953 // FIXME: Hack to work around cast weirdness.
4954 case InitializationKind::IK_Direct:
4955 case InitializationKind::IK_Value:
4956 return NumArgs != 1;
4957 default:
4958 return false;
4959 }
4960}
4961
Sebastian Redl10f04a62011-12-22 14:44:04 +00004962static ExprResult
4963PerformConstructorInitialization(Sema &S,
4964 const InitializedEntity &Entity,
4965 const InitializationKind &Kind,
4966 MultiExprArg Args,
4967 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004968 bool &ConstructorInitRequiresZeroInit,
4969 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004970 unsigned NumArgs = Args.size();
4971 CXXConstructorDecl *Constructor
4972 = cast<CXXConstructorDecl>(Step.Function.Function);
4973 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4974
4975 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004976 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004977 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4978 ? Kind.getEqualLoc()
4979 : Kind.getLocation();
4980
4981 if (Kind.getKind() == InitializationKind::IK_Default) {
4982 // Force even a trivial, implicit default constructor to be
4983 // semantically checked. We do this explicitly because we don't build
4984 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004985 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004986 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004987 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004988 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4989 }
4990
4991 ExprResult CurInit = S.Owned((Expr *)0);
4992
Douglas Gregored878af2012-02-24 23:56:31 +00004993 // C++ [over.match.copy]p1:
4994 // - When initializing a temporary to be bound to the first parameter
4995 // of a constructor that takes a reference to possibly cv-qualified
4996 // T as its first argument, called with a single argument in the
4997 // context of direct-initialization, explicit conversion functions
4998 // are also considered.
4999 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5000 Args.size() == 1 &&
5001 Constructor->isCopyOrMoveConstructor();
5002
Sebastian Redl10f04a62011-12-22 14:44:04 +00005003 // Determine the arguments required to actually perform the constructor
5004 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005005 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00005006 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00005007 AllowExplicitConv,
5008 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005009 return ExprError();
5010
5011
Jordan Rose2624b812013-05-06 16:48:12 +00005012 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005013 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00005014 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005015 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5016 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005017
5018 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5019 if (!TSInfo)
5020 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00005021 SourceRange ParenRange;
5022 if (Kind.getKind() != InitializationKind::IK_DirectList)
5023 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005024
Richard Smithc83c2302012-12-19 01:39:02 +00005025 CurInit = S.Owned(
5026 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5027 TSInfo, ConstructorArgs,
5028 ParenRange, IsListInitialization,
5029 HadMultipleCandidates,
5030 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00005031 } else {
5032 CXXConstructExpr::ConstructionKind ConstructKind =
5033 CXXConstructExpr::CK_Complete;
5034
5035 if (Entity.getKind() == InitializedEntity::EK_Base) {
5036 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5037 CXXConstructExpr::CK_VirtualBase :
5038 CXXConstructExpr::CK_NonVirtualBase;
5039 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5040 ConstructKind = CXXConstructExpr::CK_Delegating;
5041 }
5042
5043 // Only get the parenthesis range if it is a direct construction.
5044 SourceRange parenRange =
5045 Kind.getKind() == InitializationKind::IK_Direct ?
5046 Kind.getParenRange() : SourceRange();
5047
5048 // If the entity allows NRVO, mark the construction as elidable
5049 // unconditionally.
5050 if (Entity.allowsNRVO())
5051 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5052 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005053 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005054 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005055 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005056 ConstructorInitRequiresZeroInit,
5057 ConstructKind,
5058 parenRange);
5059 else
5060 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5061 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005062 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005063 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005064 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005065 ConstructorInitRequiresZeroInit,
5066 ConstructKind,
5067 parenRange);
5068 }
5069 if (CurInit.isInvalid())
5070 return ExprError();
5071
5072 // Only check access if all of that succeeded.
5073 S.CheckConstructorAccess(Loc, Constructor, Entity,
5074 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005075 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5076 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005077
5078 if (shouldBindAsTemporary(Entity))
5079 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5080
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005081 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005082}
5083
Richard Smith36d02af2012-06-04 22:27:30 +00005084/// Determine whether the specified InitializedEntity definitely has a lifetime
5085/// longer than the current full-expression. Conservatively returns false if
5086/// it's unclear.
5087static bool
5088InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5089 const InitializedEntity *Top = &Entity;
5090 while (Top->getParent())
5091 Top = Top->getParent();
5092
5093 switch (Top->getKind()) {
5094 case InitializedEntity::EK_Variable:
5095 case InitializedEntity::EK_Result:
5096 case InitializedEntity::EK_Exception:
5097 case InitializedEntity::EK_Member:
5098 case InitializedEntity::EK_New:
5099 case InitializedEntity::EK_Base:
5100 case InitializedEntity::EK_Delegating:
5101 return true;
5102
5103 case InitializedEntity::EK_ArrayElement:
5104 case InitializedEntity::EK_VectorElement:
5105 case InitializedEntity::EK_BlockElement:
5106 case InitializedEntity::EK_ComplexElement:
5107 // Could not determine what the full initialization is. Assume it might not
5108 // outlive the full-expression.
5109 return false;
5110
5111 case InitializedEntity::EK_Parameter:
5112 case InitializedEntity::EK_Temporary:
5113 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005114 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith36d02af2012-06-04 22:27:30 +00005115 // The entity being initialized might not outlive the full-expression.
5116 return false;
5117 }
5118
5119 llvm_unreachable("unknown entity kind");
5120}
5121
Richard Smith211c8dd2013-06-05 00:46:14 +00005122/// Determine the declaration which an initialized entity ultimately refers to,
5123/// for the purpose of lifetime-extending a temporary bound to a reference in
5124/// the initialization of \p Entity.
5125static const ValueDecl *
5126getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5127 const ValueDecl *FallbackDecl = 0) {
5128 // C++11 [class.temporary]p5:
5129 switch (Entity.getKind()) {
5130 case InitializedEntity::EK_Variable:
5131 // The temporary [...] persists for the lifetime of the reference
5132 return Entity.getDecl();
5133
5134 case InitializedEntity::EK_Member:
5135 // For subobjects, we look at the complete object.
5136 if (Entity.getParent())
5137 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5138 Entity.getDecl());
5139
5140 // except:
5141 // -- A temporary bound to a reference member in a constructor's
5142 // ctor-initializer persists until the constructor exits.
5143 return Entity.getDecl();
5144
5145 case InitializedEntity::EK_Parameter:
5146 // -- A temporary bound to a reference parameter in a function call
5147 // persists until the completion of the full-expression containing
5148 // the call.
5149 case InitializedEntity::EK_Result:
5150 // -- The lifetime of a temporary bound to the returned value in a
5151 // function return statement is not extended; the temporary is
5152 // destroyed at the end of the full-expression in the return statement.
5153 case InitializedEntity::EK_New:
5154 // -- A temporary bound to a reference in a new-initializer persists
5155 // until the completion of the full-expression containing the
5156 // new-initializer.
5157 return 0;
5158
5159 case InitializedEntity::EK_Temporary:
5160 case InitializedEntity::EK_CompoundLiteralInit:
5161 // We don't yet know the storage duration of the surrounding temporary.
5162 // Assume it's got full-expression duration for now, it will patch up our
5163 // storage duration if that's not correct.
5164 return 0;
5165
5166 case InitializedEntity::EK_ArrayElement:
5167 // For subobjects, we look at the complete object.
5168 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5169 FallbackDecl);
5170
5171 case InitializedEntity::EK_Base:
5172 case InitializedEntity::EK_Delegating:
5173 // We can reach this case for aggregate initialization in a constructor:
5174 // struct A { int &&r; };
5175 // struct B : A { B() : A{0} {} };
5176 // In this case, use the innermost field decl as the context.
5177 return FallbackDecl;
5178
5179 case InitializedEntity::EK_BlockElement:
5180 case InitializedEntity::EK_LambdaCapture:
5181 case InitializedEntity::EK_Exception:
5182 case InitializedEntity::EK_VectorElement:
5183 case InitializedEntity::EK_ComplexElement:
5184 llvm_unreachable("should not materialize a temporary to initialize this");
5185 }
Benjamin Kramer6f773e82013-06-05 15:37:50 +00005186 llvm_unreachable("unknown entity kind");
Richard Smith211c8dd2013-06-05 00:46:14 +00005187}
5188
5189static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5190
5191/// Update a glvalue expression that is used as the initializer of a reference
5192/// to note that its lifetime is extended.
5193static void performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
5194 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5195 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5196 // This is just redundant braces around an initializer. Step over it.
5197 Init = ILE->getInit(0);
5198 }
5199 }
5200
5201 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5202 // Update the storage duration of the materialized temporary.
5203 // FIXME: Rebuild the expression instead of mutating it.
5204 ME->setExtendingDecl(ExtendingD);
5205 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
5206 }
5207}
5208
5209/// Update a prvalue expression that is going to be materialized as a
5210/// lifetime-extended temporary.
5211static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5212 // Dig out the expression which constructs the extended temporary.
5213 SmallVector<const Expr *, 2> CommaLHSs;
5214 SmallVector<SubobjectAdjustment, 2> Adjustments;
5215 Init = const_cast<Expr *>(
5216 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5217
5218 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5219 if (ILE->initializesStdInitializerList()) {
5220 // FIXME: If this is an InitListExpr which creates a std::initializer_list
5221 // object, we also need to lifetime-extend the underlying array
5222 // itself. Fix the representation to explicitly materialize an
5223 // array temporary so we can model this properly.
5224 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5225 performLifetimeExtension(ILE->getInit(I), ExtendingD);
5226 return;
5227 }
5228
5229 CXXRecordDecl *RD = Init->getType()->getAsCXXRecordDecl();
5230 if (RD) {
5231 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5232
5233 // If we lifetime-extend a braced initializer which is initializing an
5234 // aggregate, and that aggregate contains reference members which are
5235 // bound to temporaries, those temporaries are also lifetime-extended.
5236 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5237 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5238 performReferenceExtension(ILE->getInit(0), ExtendingD);
5239 else {
5240 unsigned Index = 0;
5241 for (RecordDecl::field_iterator I = RD->field_begin(),
5242 E = RD->field_end();
5243 I != E; ++I) {
5244 if (I->isUnnamedBitfield())
5245 continue;
5246 if (I->getType()->isReferenceType())
5247 performReferenceExtension(ILE->getInit(Index), ExtendingD);
5248 else if (isa<InitListExpr>(ILE->getInit(Index)))
5249 // This may be either aggregate-initialization of a member or
5250 // initialization of a std::initializer_list object. Either way,
5251 // we should recursively lifetime-extend that initializer.
5252 performLifetimeExtension(ILE->getInit(Index), ExtendingD);
5253 ++Index;
5254 }
5255 }
5256 }
5257 }
5258}
5259
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005260ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005261InitializationSequence::Perform(Sema &S,
5262 const InitializedEntity &Entity,
5263 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005264 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005265 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005266 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005267 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005268 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005270
Sebastian Redl7491c492011-06-05 13:59:11 +00005271 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005272 // If the declaration is a non-dependent, incomplete array type
5273 // that has an initializer, then its type will be completed once
5274 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005275 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005276 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005277 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005278 if (const IncompleteArrayType *ArrayT
5279 = S.Context.getAsIncompleteArrayType(DeclType)) {
5280 // FIXME: We don't currently have the ability to accurately
5281 // compute the length of an initializer list without
5282 // performing full type-checking of the initializer list
5283 // (since we have to determine where braces are implicitly
5284 // introduced and such). So, we fall back to making the array
5285 // type a dependently-sized array type with no specified
5286 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005287 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005288 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005289
Douglas Gregord87b61f2009-12-10 17:56:55 +00005290 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005291 if (DeclaratorDecl *DD = Entity.getDecl()) {
5292 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5293 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005294 if (IncompleteArrayTypeLoc ArrayLoc =
5295 TL.getAs<IncompleteArrayTypeLoc>())
5296 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005297 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005298 }
5299
5300 *ResultType
5301 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5302 /*NumElts=*/0,
5303 ArrayT->getSizeModifier(),
5304 ArrayT->getIndexTypeCVRQualifiers(),
5305 Brackets);
5306 }
5307
5308 }
5309 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005310 if (Kind.getKind() == InitializationKind::IK_Direct &&
5311 !Kind.isExplicitCast()) {
5312 // Rebuild the ParenListExpr.
5313 SourceRange ParenRange = Kind.getParenRange();
5314 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005315 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005316 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005317 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005318 Kind.isExplicitCast() ||
5319 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005320 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005321 }
5322
Sebastian Redl7491c492011-06-05 13:59:11 +00005323 // No steps means no initialization.
5324 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005325 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005326
Richard Smith80ad52f2013-01-02 11:42:31 +00005327 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005328 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005329 Entity.getKind() != InitializedEntity::EK_Parameter) {
5330 // Produce a C++98 compatibility warning if we are initializing a reference
5331 // from an initializer list. For parameters, we produce a better warning
5332 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005333 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005334 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5335 << Init->getSourceRange();
5336 }
5337
Richard Smith36d02af2012-06-04 22:27:30 +00005338 // Diagnose cases where we initialize a pointer to an array temporary, and the
5339 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005340 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005341 Entity.getType()->isPointerType() &&
5342 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005343 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005344 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5345 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5346 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5347 << Init->getSourceRange();
5348 }
5349
Douglas Gregord6542d82009-12-22 15:35:07 +00005350 QualType DestType = Entity.getType().getNonReferenceType();
5351 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005352 // the same as Entity.getDecl()->getType() in cases involving type merging,
5353 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005354 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005355 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005356 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005357
John McCall60d7b3a2010-08-24 06:29:42 +00005358 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005359
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005360 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005361 // grab the only argument out the Args and place it into the "current"
5362 // initializer.
5363 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005364 case SK_ResolveAddressOfOverloadedFunction:
5365 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005366 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005367 case SK_CastDerivedToBaseLValue:
5368 case SK_BindReference:
5369 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005370 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005371 case SK_UserConversion:
5372 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005373 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005374 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005375 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005376 case SK_ConversionSequence:
5377 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005378 case SK_UnwrapInitList:
5379 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005380 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005381 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005382 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005383 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005384 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005385 case SK_PassByIndirectCopyRestore:
5386 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005387 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005388 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005389 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005390 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005391 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005392 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005393 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005394 break;
John McCallf6a16482010-12-04 03:47:34 +00005395 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005396
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005397 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005398 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005399 case SK_ZeroInitialization:
5400 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005401 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005402
5403 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005404 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005405 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005406 for (step_iterator Step = step_begin(), StepEnd = step_end();
5407 Step != StepEnd; ++Step) {
5408 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005409 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005410
John Wiegley429bb272011-04-08 18:41:53 +00005411 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005412
Douglas Gregor20093b42009-12-09 23:02:17 +00005413 switch (Step->Kind) {
5414 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005415 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005416 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005417 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005418 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5419 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005420 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005421 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005422 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005423 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424
Douglas Gregor20093b42009-12-09 23:02:17 +00005425 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005426 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005427 case SK_CastDerivedToBaseLValue: {
5428 // We have a derived-to-base cast that produces either an rvalue or an
5429 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005430
John McCallf871d0c2010-08-07 06:22:56 +00005431 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005432
Douglas Gregor20093b42009-12-09 23:02:17 +00005433 // Casts to inaccessible base classes are allowed with C-style casts.
5434 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5435 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005436 CurInit.get()->getLocStart(),
5437 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005438 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005439 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005440
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005441 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5442 QualType T = SourceType;
5443 if (const PointerType *Pointer = T->getAs<PointerType>())
5444 T = Pointer->getPointeeType();
5445 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005446 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005447 cast<CXXRecordDecl>(RecordTy->getDecl()));
5448 }
5449
John McCall5baba9d2010-08-25 10:28:54 +00005450 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005451 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005452 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005453 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005454 VK_XValue :
5455 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005456 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5457 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005458 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005459 CurInit.get(),
5460 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005461 break;
5462 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005463
Douglas Gregor20093b42009-12-09 23:02:17 +00005464 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005465 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5466 if (CurInit.get()->refersToBitField()) {
5467 // We don't necessarily have an unambiguous source bit-field.
5468 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005469 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005470 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005471 << (BitField ? BitField->getDeclName() : DeclarationName())
5472 << (BitField != NULL)
John Wiegley429bb272011-04-08 18:41:53 +00005473 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005474 if (BitField)
5475 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5476
John McCallf312b1e2010-08-26 23:41:50 +00005477 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005478 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005479
John Wiegley429bb272011-04-08 18:41:53 +00005480 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005481 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005482 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5483 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005484 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005485 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005486 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005487 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005488
Douglas Gregor20093b42009-12-09 23:02:17 +00005489 // Reference binding does not have any corresponding ASTs.
5490
5491 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005492 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005493 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005494
Douglas Gregor20093b42009-12-09 23:02:17 +00005495 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005496
Richard Smith211c8dd2013-06-05 00:46:14 +00005497 case SK_BindReferenceToTemporary: {
Jordan Rose1fd1e282013-04-11 00:58:58 +00005498 // Make sure the "temporary" is actually an rvalue.
5499 assert(CurInit.get()->isRValue() && "not a temporary");
5500
Douglas Gregor20093b42009-12-09 23:02:17 +00005501 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005502 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005503 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005504
Richard Smith211c8dd2013-06-05 00:46:14 +00005505 // Maybe lifetime-extend the temporary's subobjects to match the
5506 // entity's lifetime.
5507 const ValueDecl *ExtendingDecl =
5508 getDeclForTemporaryLifetimeExtension(Entity);
5509 if (ExtendingDecl)
5510 performLifetimeExtension(CurInit.get(), ExtendingDecl);
5511
Douglas Gregor03e80032011-06-21 17:03:29 +00005512 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005513 CurInit = new (S.Context) MaterializeTemporaryExpr(
Richard Smith211c8dd2013-06-05 00:46:14 +00005514 Entity.getType().getNonReferenceType(), CurInit.get(),
5515 Entity.getType()->isLValueReferenceType(), ExtendingDecl);
Douglas Gregord7b23162011-06-22 16:12:01 +00005516
5517 // If we're binding to an Objective-C object that has lifetime, we
5518 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005519 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005520 CurInit.get()->getType()->isObjCLifetimeType())
5521 S.ExprNeedsCleanups = true;
5522
Douglas Gregor20093b42009-12-09 23:02:17 +00005523 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005525
Douglas Gregor523d46a2010-04-18 07:40:54 +00005526 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005527 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005528 /*IsExtraneousCopy=*/true);
5529 break;
5530
Douglas Gregor20093b42009-12-09 23:02:17 +00005531 case SK_UserConversion: {
5532 // We have a user-defined conversion that invokes either a constructor
5533 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005534 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005535 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005536 FunctionDecl *Fn = Step->Function.Function;
5537 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005538 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005539 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005540 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005541 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005542 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005543 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005544 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005545
Douglas Gregor20093b42009-12-09 23:02:17 +00005546 // Determine the arguments required to actually perform the constructor
5547 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005548 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005549 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005550 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005551 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005552 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005553
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005554 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005555 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005556 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005557 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005558 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005559 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005560 CXXConstructExpr::CK_Complete,
5561 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005562 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005563 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005564
Anders Carlsson9a68a672010-04-21 18:47:17 +00005565 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005566 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005567 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5568 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005569
John McCall2de56d12010-08-25 11:45:40 +00005570 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005571 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5572 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5573 S.IsDerivedFrom(SourceType, Class))
5574 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005575
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005576 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005577 } else {
5578 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005579 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005580 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005581 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005582 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5583 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005584
5585 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005586 // derived-to-base conversion? I believe the answer is "no", because
5587 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005588 ExprResult CurInitExprRes =
5589 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5590 FoundFn, Conversion);
5591 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005592 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005593 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005594
Douglas Gregor20093b42009-12-09 23:02:17 +00005595 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005596 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5597 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005598 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005599 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005600
John McCall2de56d12010-08-25 11:45:40 +00005601 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005602
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005603 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005604 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005605
Sebastian Redl3b802322011-07-14 19:07:55 +00005606 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005607 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5608
5609 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005610 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005611 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005612 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005613 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005614 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005615 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005616 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005617 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5618 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005619 }
5620 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005621
John McCallf871d0c2010-08-07 06:22:56 +00005622 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005623 CurInit.get()->getType(),
5624 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005625 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005626 if (MaybeBindToTemp)
5627 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005628 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005629 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005630 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005631 break;
5632 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005633
Douglas Gregor20093b42009-12-09 23:02:17 +00005634 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005635 case SK_QualificationConversionXValue:
5636 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005637 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005638 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005639 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005640 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005641 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005642 VK_XValue :
5643 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005644 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005645 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005646 }
5647
Jordan Rose1fd1e282013-04-11 00:58:58 +00005648 case SK_LValueToRValue: {
5649 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5650 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5651 CK_LValueToRValue,
5652 CurInit.take(),
5653 /*BasePath=*/0,
5654 VK_RValue));
5655 break;
5656 }
5657
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005658 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005659 Sema::CheckedConversionKind CCK
5660 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5661 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005662 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005663 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005664 ExprResult CurInitExprRes =
5665 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005666 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005667 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005668 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005669 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005670 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005671 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005672
Douglas Gregord87b61f2009-12-10 17:56:55 +00005673 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005674 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005675 // Hack: We must pass *ResultType if available in order to set the type
5676 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5677 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5678 // temporary, not a reference, so we should pass Ty.
5679 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5680 // Since this step is never used for a reference directly, we explicitly
5681 // unwrap references here and rewrap them afterwards.
5682 // We also need to create a InitializeTemporary entity for this.
5683 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005684 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005685 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005686 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5687 InitListChecker PerformInitList(S, InitEntity,
Richard Smith40cba902013-06-06 11:41:05 +00005688 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005689 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005690 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005691
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005692 if (ResultType) {
5693 if ((*ResultType)->isRValueReferenceType())
5694 Ty = S.Context.getRValueReferenceType(Ty);
5695 else if ((*ResultType)->isLValueReferenceType())
5696 Ty = S.Context.getLValueReferenceType(Ty,
5697 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5698 *ResultType = Ty;
5699 }
5700
5701 InitListExpr *StructuredInitList =
5702 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005703 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005704 CurInit = shouldBindAsTemporary(InitEntity)
5705 ? S.MaybeBindToTemporary(StructuredInitList)
5706 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005707 break;
5708 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005709
Sebastian Redl10f04a62011-12-22 14:44:04 +00005710 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005711 // When an initializer list is passed for a parameter of type "reference
5712 // to object", we don't get an EK_Temporary entity, but instead an
5713 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005714 // FIXME: This is a hack. What we really should do is create a user
5715 // conversion step for this case, but this makes it considerably more
5716 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005717 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5718 Entity.getType().getNonReferenceType());
5719 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005720 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005721 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005722 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5723 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005724 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005725 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5726 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005727 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005728 ConstructorInitRequiresZeroInit,
5729 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005730 break;
5731 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005732
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005733 case SK_UnwrapInitList:
5734 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5735 break;
5736
5737 case SK_RewrapInitList: {
5738 Expr *E = CurInit.take();
5739 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5740 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005741 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005742 ILE->setSyntacticForm(Syntactic);
5743 ILE->setType(E->getType());
5744 ILE->setValueKind(E->getValueKind());
5745 CurInit = S.Owned(ILE);
5746 break;
5747 }
5748
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005749 case SK_ConstructorInitialization: {
5750 // When an initializer list is passed for a parameter of type "reference
5751 // to object", we don't get an EK_Temporary entity, but instead an
5752 // EK_Parameter entity with reference type.
5753 // FIXME: This is a hack. What we really should do is create a user
5754 // conversion step for this case, but this makes it considerably more
5755 // complicated. For now, this will do.
5756 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5757 Entity.getType().getNonReferenceType());
5758 bool UseTemporary = Entity.getType()->isReferenceType();
5759 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5760 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005761 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005762 ConstructorInitRequiresZeroInit,
5763 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005764 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005765 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005766
Douglas Gregor71d17402009-12-15 00:01:57 +00005767 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005768 step_iterator NextStep = Step;
5769 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005770 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005771 (NextStep->Kind == SK_ConstructorInitialization ||
5772 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005773 // The need for zero-initialization is recorded directly into
5774 // the call to the object's constructor within the next step.
5775 ConstructorInitRequiresZeroInit = true;
5776 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005777 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005778 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005779 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5780 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005781 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005782 Kind.getRange().getBegin());
5783
5784 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5785 TSInfo->getType().getNonLValueExprType(S.Context),
5786 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005787 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005788 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005789 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005790 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005791 break;
5792 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005793
5794 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005795 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005796 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005797 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005798 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5799 if (Result.isInvalid())
5800 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005801 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005802
5803 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005804 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005805 if (ConvTy != Sema::Compatible &&
5806 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005807 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005808 == Sema::Compatible)
5809 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005810 if (CurInitExprRes.isInvalid())
5811 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005812 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005813
Douglas Gregora41a8c52010-04-22 00:20:18 +00005814 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005815 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5816 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005817 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005818 getAssignmentAction(Entity),
5819 &Complained)) {
5820 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005821 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005822 } else if (Complained)
5823 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005824 break;
5825 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005826
5827 case SK_StringInit: {
5828 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005829 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005830 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005831 break;
5832 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005833
5834 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005835 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005836 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005837 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005838 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005839
5840 case SK_ArrayInit:
5841 // Okay: we checked everything before creating this step. Note that
5842 // this is a GNU extension.
5843 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005844 << Step->Type << CurInit.get()->getType()
5845 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005846
5847 // If the destination type is an incomplete array type, update the
5848 // type accordingly.
5849 if (ResultType) {
5850 if (const IncompleteArrayType *IncompleteDest
5851 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5852 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005853 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005854 *ResultType = S.Context.getConstantArrayType(
5855 IncompleteDest->getElementType(),
5856 ConstantSource->getSize(),
5857 ArrayType::Normal, 0);
5858 }
5859 }
5860 }
John McCallf85e1932011-06-15 23:02:42 +00005861 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005862
Richard Smith0f163e92012-02-15 22:38:09 +00005863 case SK_ParenthesizedArrayInit:
5864 // Okay: we checked everything before creating this step. Note that
5865 // this is a GNU extension.
5866 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5867 << CurInit.get()->getSourceRange();
5868 break;
5869
John McCallf85e1932011-06-15 23:02:42 +00005870 case SK_PassByIndirectCopyRestore:
5871 case SK_PassByIndirectRestore:
5872 checkIndirectCopyRestoreSource(S, CurInit.get());
5873 CurInit = S.Owned(new (S.Context)
5874 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5875 Step->Kind == SK_PassByIndirectCopyRestore));
5876 break;
5877
5878 case SK_ProduceObjCObject:
5879 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005880 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005881 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005882 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005883
5884 case SK_StdInitializerList: {
5885 QualType Dest = Step->Type;
5886 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005887 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005888 (void)Success;
5889 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005890
5891 // If the element type has a destructor, check it.
5892 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5893 if (!RD->hasIrrelevantDestructor()) {
5894 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5895 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5896 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5897 S.PDiag(diag::err_access_dtor_temp) << E);
Richard Smith82f145d2013-05-04 06:44:46 +00005898 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5899 return ExprError();
Sebastian Redl28357452012-03-05 19:35:43 +00005900 }
5901 }
5902 }
5903
Sebastian Redl2b916b82012-01-17 22:49:42 +00005904 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005905 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5906 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005907 unsigned NumInits = ILE->getNumInits();
5908 SmallVector<Expr*, 16> Converted(NumInits);
5909 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5910 S.Context.getConstantArrayType(E,
5911 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5912 NumInits),
5913 ArrayType::Normal, 0));
5914 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5915 0, HiddenArray);
5916 for (unsigned i = 0; i < NumInits; ++i) {
5917 Element.setElementIndex(i);
5918 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005919 ExprResult Res = S.PerformCopyInitialization(
5920 Element, Init.get()->getExprLoc(), Init,
5921 /*TopLevelOfInitList=*/ true);
Richard Smith2c2f09e2013-05-23 23:20:04 +00005922 if (Res.isInvalid())
5923 return ExprError();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005924 Converted[i] = Res.take();
5925 }
5926 InitListExpr *Semantic = new (S.Context)
5927 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005928 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005929 Semantic->setSyntacticForm(ILE);
5930 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005931 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005932 CurInit = S.Owned(Semantic);
5933 break;
5934 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005935 case SK_OCLSamplerInit: {
5936 assert(Step->Type->isSamplerT() &&
5937 "Sampler initialization on non sampler type.");
5938
5939 QualType SourceType = CurInit.get()->getType();
5940 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5941
5942 if (EntityKind == InitializedEntity::EK_Parameter) {
5943 if (!SourceType->isSamplerT())
5944 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5945 << SourceType;
5946 } else if (EntityKind != InitializedEntity::EK_Variable) {
5947 llvm_unreachable("Invalid EntityKind!");
5948 }
5949
5950 break;
5951 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005952 case SK_OCLZeroEvent: {
5953 assert(Step->Type->isEventT() &&
5954 "Event initialization on non event type.");
5955
5956 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5957 CK_ZeroToOCLEvent,
5958 CurInit.get()->getValueKind());
5959 break;
5960 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005961 }
5962 }
John McCall15d7d122010-11-11 03:21:53 +00005963
5964 // Diagnose non-fatal problems with the completed initialization.
5965 if (Entity.getKind() == InitializedEntity::EK_Member &&
5966 cast<FieldDecl>(Entity.getDecl())->isBitField())
5967 S.CheckBitFieldInitialization(Kind.getLocation(),
5968 cast<FieldDecl>(Entity.getDecl()),
5969 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005970
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005971 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005972}
5973
Richard Smithd5bc8672012-12-08 02:01:17 +00005974/// Somewhere within T there is an uninitialized reference subobject.
5975/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005976static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5977 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005978 if (T->isReferenceType()) {
5979 S.Diag(Loc, diag::err_reference_without_init)
5980 << T.getNonReferenceType();
5981 return true;
5982 }
5983
5984 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5985 if (!RD || !RD->hasUninitializedReferenceMember())
5986 return false;
5987
5988 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5989 FE = RD->field_end(); FI != FE; ++FI) {
5990 if (FI->isUnnamedBitfield())
5991 continue;
5992
5993 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5994 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5995 return true;
5996 }
5997 }
5998
5999 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6000 BE = RD->bases_end();
6001 BI != BE; ++BI) {
6002 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6003 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6004 return true;
6005 }
6006 }
6007
6008 return false;
6009}
6010
6011
Douglas Gregor20093b42009-12-09 23:02:17 +00006012//===----------------------------------------------------------------------===//
6013// Diagnose initialization failures
6014//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00006015
6016/// Emit notes associated with an initialization that failed due to a
6017/// "simple" conversion failure.
6018static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6019 Expr *op) {
6020 QualType destType = entity.getType();
6021 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6022 op->getType()->isObjCObjectPointerType()) {
6023
6024 // Emit a possible note about the conversion failing because the
6025 // operand is a message send with a related result type.
6026 S.EmitRelatedResultTypeNote(op);
6027
6028 // Emit a possible note about a return failing because we're
6029 // expecting a related result type.
6030 if (entity.getKind() == InitializedEntity::EK_Result)
6031 S.EmitRelatedResultTypeNoteForReturn(destType);
6032 }
6033}
6034
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006035bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00006036 const InitializedEntity &Entity,
6037 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006038 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00006039 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00006040 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006041
Douglas Gregord6542d82009-12-22 15:35:07 +00006042 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00006043 switch (Failure) {
6044 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006045 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006046 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006047 // Dig out the reference subobject which is uninitialized and diagnose it.
6048 // If this is value-initialization, this could be nested some way within
6049 // the target type.
6050 assert(Kind.getKind() == InitializationKind::IK_Value ||
6051 DestType->isReferenceType());
6052 bool Diagnosed =
6053 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6054 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6055 (void)Diagnosed;
6056 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006057 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006058 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00006059 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006060
Douglas Gregor20093b42009-12-09 23:02:17 +00006061 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00006062 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00006063 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00006064 case FK_ArrayNeedsInitListOrStringLiteral:
6065 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6066 break;
6067 case FK_ArrayNeedsInitListOrWideStringLiteral:
6068 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6069 break;
6070 case FK_NarrowStringIntoWideCharArray:
6071 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6072 break;
6073 case FK_WideStringIntoCharArray:
6074 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6075 break;
6076 case FK_IncompatWideStringIntoWideChar:
6077 S.Diag(Kind.getLocation(),
6078 diag::err_array_init_incompat_wide_string_into_wchar);
6079 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006080 case FK_ArrayTypeMismatch:
6081 case FK_NonConstantArrayInit:
6082 S.Diag(Kind.getLocation(),
6083 (Failure == FK_ArrayTypeMismatch
6084 ? diag::err_array_init_different_type
6085 : diag::err_array_init_non_constant_array))
6086 << DestType.getNonReferenceType()
6087 << Args[0]->getType()
6088 << Args[0]->getSourceRange();
6089 break;
6090
John McCall73076432012-01-05 00:13:19 +00006091 case FK_VariableLengthArrayHasInitializer:
6092 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6093 << Args[0]->getSourceRange();
6094 break;
6095
John McCall6bb80172010-03-30 21:47:33 +00006096 case FK_AddressOfOverloadFailed: {
6097 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006098 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00006099 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00006100 true,
6101 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00006102 break;
John McCall6bb80172010-03-30 21:47:33 +00006103 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006104
Douglas Gregor20093b42009-12-09 23:02:17 +00006105 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00006106 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00006107 switch (FailedOverloadResult) {
6108 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006109 if (Failure == FK_UserConversionOverloadFailed)
6110 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6111 << Args[0]->getType() << DestType
6112 << Args[0]->getSourceRange();
6113 else
6114 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6115 << DestType << Args[0]->getType()
6116 << Args[0]->getSourceRange();
6117
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006118 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006119 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006120
Douglas Gregor20093b42009-12-09 23:02:17 +00006121 case OR_No_Viable_Function:
6122 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6123 << Args[0]->getType() << DestType.getNonReferenceType()
6124 << Args[0]->getSourceRange();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006125 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006126 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006127
Douglas Gregor20093b42009-12-09 23:02:17 +00006128 case OR_Deleted: {
6129 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6130 << Args[0]->getType() << DestType.getNonReferenceType()
6131 << Args[0]->getSourceRange();
6132 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006133 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006134 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6135 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00006136 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00006137 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00006138 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006139 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00006140 }
6141 break;
6142 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006143
Douglas Gregor20093b42009-12-09 23:02:17 +00006144 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006145 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00006146 }
6147 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006148
Douglas Gregor20093b42009-12-09 23:02:17 +00006149 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006150 if (isa<InitListExpr>(Args[0])) {
6151 S.Diag(Kind.getLocation(),
6152 diag::err_lvalue_reference_bind_to_initlist)
6153 << DestType.getNonReferenceType().isVolatileQualified()
6154 << DestType.getNonReferenceType()
6155 << Args[0]->getSourceRange();
6156 break;
6157 }
6158 // Intentional fallthrough
6159
Douglas Gregor20093b42009-12-09 23:02:17 +00006160 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006161 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00006162 Failure == FK_NonConstLValueReferenceBindingToTemporary
6163 ? diag::err_lvalue_reference_bind_to_temporary
6164 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00006165 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00006166 << DestType.getNonReferenceType()
6167 << Args[0]->getType()
6168 << Args[0]->getSourceRange();
6169 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006170
Douglas Gregor20093b42009-12-09 23:02:17 +00006171 case FK_RValueReferenceBindingToLValue:
6172 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00006173 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00006174 << Args[0]->getSourceRange();
6175 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006176
Douglas Gregor20093b42009-12-09 23:02:17 +00006177 case FK_ReferenceInitDropsQualifiers:
6178 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6179 << DestType.getNonReferenceType()
6180 << Args[0]->getType()
6181 << Args[0]->getSourceRange();
6182 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006183
Douglas Gregor20093b42009-12-09 23:02:17 +00006184 case FK_ReferenceInitFailed:
6185 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6186 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006187 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006188 << Args[0]->getType()
6189 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006190 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006191 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006192
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006193 case FK_ConversionFailed: {
6194 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006195 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006196 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006197 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006198 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006199 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006200 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006201 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6202 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006203 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006204 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006205 }
John Wiegley429bb272011-04-08 18:41:53 +00006206
6207 case FK_ConversionFromPropertyFailed:
6208 // No-op. This error has already been reported.
6209 break;
6210
Douglas Gregord87b61f2009-12-10 17:56:55 +00006211 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006212 SourceRange R;
6213
6214 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006215 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006216 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006217 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006218 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006219
Douglas Gregor19311e72010-09-08 21:40:08 +00006220 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6221 if (Kind.isCStyleOrFunctionalCast())
6222 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6223 << R;
6224 else
6225 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6226 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006227 break;
6228 }
6229
6230 case FK_ReferenceBindingToInitList:
6231 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6232 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6233 break;
6234
6235 case FK_InitListBadDestinationType:
6236 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6237 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6238 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006239
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006240 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006241 case FK_ConstructorOverloadFailed: {
6242 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006243 if (Args.size())
6244 ArgsRange = SourceRange(Args.front()->getLocStart(),
6245 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006246
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006247 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006248 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006249 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006250 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006251 }
6252
Douglas Gregor51c56d62009-12-14 20:49:26 +00006253 // FIXME: Using "DestType" for the entity we're printing is probably
6254 // bad.
6255 switch (FailedOverloadResult) {
6256 case OR_Ambiguous:
6257 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6258 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006259 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006260 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006261
Douglas Gregor51c56d62009-12-14 20:49:26 +00006262 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006263 if (Kind.getKind() == InitializationKind::IK_Default &&
6264 (Entity.getKind() == InitializedEntity::EK_Base ||
6265 Entity.getKind() == InitializedEntity::EK_Member) &&
6266 isa<CXXConstructorDecl>(S.CurContext)) {
6267 // This is implicit default initialization of a member or
6268 // base within a constructor. If no viable function was
6269 // found, notify the user that she needs to explicitly
6270 // initialize this base/member.
6271 CXXConstructorDecl *Constructor
6272 = cast<CXXConstructorDecl>(S.CurContext);
6273 if (Entity.getKind() == InitializedEntity::EK_Base) {
6274 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006275 << (Constructor->getInheritedConstructor() ? 2 :
6276 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006277 << S.Context.getTypeDeclType(Constructor->getParent())
6278 << /*base=*/0
6279 << Entity.getType();
6280
6281 RecordDecl *BaseDecl
6282 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6283 ->getDecl();
6284 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6285 << S.Context.getTagDeclType(BaseDecl);
6286 } else {
6287 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006288 << (Constructor->getInheritedConstructor() ? 2 :
6289 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006290 << S.Context.getTypeDeclType(Constructor->getParent())
6291 << /*member=*/1
6292 << Entity.getName();
6293 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6294
6295 if (const RecordType *Record
6296 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006297 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006298 diag::note_previous_decl)
6299 << S.Context.getTagDeclType(Record->getDecl());
6300 }
6301 break;
6302 }
6303
Douglas Gregor51c56d62009-12-14 20:49:26 +00006304 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6305 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006306 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006307 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006308
Douglas Gregor51c56d62009-12-14 20:49:26 +00006309 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006310 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006311 OverloadingResult Ovl
6312 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006313 if (Ovl != OR_Deleted) {
6314 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6315 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006316 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006317 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006318 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006319
6320 // If this is a defaulted or implicitly-declared function, then
6321 // it was implicitly deleted. Make it clear that the deletion was
6322 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006323 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006324 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006325 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006326 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006327 else
6328 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6329 << true << DestType << ArgsRange;
6330
6331 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006332 break;
6333 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006334
Douglas Gregor51c56d62009-12-14 20:49:26 +00006335 case OR_Success:
6336 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006337 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006338 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006339 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006340
Douglas Gregor99a2e602009-12-16 01:38:02 +00006341 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006342 if (Entity.getKind() == InitializedEntity::EK_Member &&
6343 isa<CXXConstructorDecl>(S.CurContext)) {
6344 // This is implicit default-initialization of a const member in
6345 // a constructor. Complain that it needs to be explicitly
6346 // initialized.
6347 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6348 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006349 << (Constructor->getInheritedConstructor() ? 2 :
6350 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006351 << S.Context.getTypeDeclType(Constructor->getParent())
6352 << /*const=*/1
6353 << Entity.getName();
6354 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6355 << Entity.getName();
6356 } else {
6357 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6358 << DestType << (bool)DestType->getAs<RecordType>();
6359 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006360 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006361
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006362 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006363 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006364 diag::err_init_incomplete_type);
6365 break;
6366
Sebastian Redl14b0c192011-09-24 17:48:00 +00006367 case FK_ListInitializationFailed: {
6368 // Run the init list checker again to emit diagnostics.
6369 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6370 QualType DestType = Entity.getType();
6371 InitListChecker DiagnoseInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00006372 DestType, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006373 assert(DiagnoseInitList.HadError() &&
6374 "Inconsistent init list check result.");
6375 break;
6376 }
John McCall5acb0c92011-10-17 18:40:02 +00006377
6378 case FK_PlaceholderType: {
6379 // FIXME: Already diagnosed!
6380 break;
6381 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006382
6383 case FK_InitListElementCopyFailure: {
6384 // Try to perform all copies again.
6385 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6386 unsigned NumInits = InitList->getNumInits();
6387 QualType DestType = Entity.getType();
6388 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006389 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006390 (void)Success;
6391 assert(Success && "Where did the std::initializer_list go?");
6392 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6393 S.Context.getConstantArrayType(E,
6394 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6395 NumInits),
6396 ArrayType::Normal, 0));
6397 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6398 0, HiddenArray);
6399 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6400 // where the init list type is wrong, e.g.
6401 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6402 // FIXME: Emit a note if we hit the limit?
6403 int ErrorCount = 0;
6404 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6405 Element.setElementIndex(i);
6406 ExprResult Init = S.Owned(InitList->getInit(i));
6407 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6408 .isInvalid())
6409 ++ErrorCount;
6410 }
6411 break;
6412 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006413
6414 case FK_ExplicitConstructor: {
6415 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6416 << Args[0]->getSourceRange();
6417 OverloadCandidateSet::iterator Best;
6418 OverloadingResult Ovl
6419 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006420 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006421 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6422 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6423 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6424 break;
6425 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006426 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006427
Douglas Gregora41a8c52010-04-22 00:20:18 +00006428 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006429 return true;
6430}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006431
Chris Lattner5f9e2722011-07-23 10:55:15 +00006432void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006433 switch (SequenceKind) {
6434 case FailedSequence: {
6435 OS << "Failed sequence: ";
6436 switch (Failure) {
6437 case FK_TooManyInitsForReference:
6438 OS << "too many initializers for reference";
6439 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006440
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006441 case FK_ArrayNeedsInitList:
6442 OS << "array requires initializer list";
6443 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006444
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006445 case FK_ArrayNeedsInitListOrStringLiteral:
6446 OS << "array requires initializer list or string literal";
6447 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006448
Hans Wennborg0ff50742013-05-15 11:03:04 +00006449 case FK_ArrayNeedsInitListOrWideStringLiteral:
6450 OS << "array requires initializer list or wide string literal";
6451 break;
6452
6453 case FK_NarrowStringIntoWideCharArray:
6454 OS << "narrow string into wide char array";
6455 break;
6456
6457 case FK_WideStringIntoCharArray:
6458 OS << "wide string into char array";
6459 break;
6460
6461 case FK_IncompatWideStringIntoWideChar:
6462 OS << "incompatible wide string into wide char array";
6463 break;
6464
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006465 case FK_ArrayTypeMismatch:
6466 OS << "array type mismatch";
6467 break;
6468
6469 case FK_NonConstantArrayInit:
6470 OS << "non-constant array initializer";
6471 break;
6472
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006473 case FK_AddressOfOverloadFailed:
6474 OS << "address of overloaded function failed";
6475 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006476
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006477 case FK_ReferenceInitOverloadFailed:
6478 OS << "overload resolution for reference initialization failed";
6479 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006480
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006481 case FK_NonConstLValueReferenceBindingToTemporary:
6482 OS << "non-const lvalue reference bound to temporary";
6483 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006484
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006485 case FK_NonConstLValueReferenceBindingToUnrelated:
6486 OS << "non-const lvalue reference bound to unrelated type";
6487 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006488
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006489 case FK_RValueReferenceBindingToLValue:
6490 OS << "rvalue reference bound to an lvalue";
6491 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006492
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006493 case FK_ReferenceInitDropsQualifiers:
6494 OS << "reference initialization drops qualifiers";
6495 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006496
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006497 case FK_ReferenceInitFailed:
6498 OS << "reference initialization failed";
6499 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006500
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006501 case FK_ConversionFailed:
6502 OS << "conversion failed";
6503 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006504
John Wiegley429bb272011-04-08 18:41:53 +00006505 case FK_ConversionFromPropertyFailed:
6506 OS << "conversion from property failed";
6507 break;
6508
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006509 case FK_TooManyInitsForScalar:
6510 OS << "too many initializers for scalar";
6511 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006512
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006513 case FK_ReferenceBindingToInitList:
6514 OS << "referencing binding to initializer list";
6515 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006516
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006517 case FK_InitListBadDestinationType:
6518 OS << "initializer list for non-aggregate, non-scalar type";
6519 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006520
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006521 case FK_UserConversionOverloadFailed:
6522 OS << "overloading failed for user-defined conversion";
6523 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006524
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006525 case FK_ConstructorOverloadFailed:
6526 OS << "constructor overloading failed";
6527 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006528
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006529 case FK_DefaultInitOfConst:
6530 OS << "default initialization of a const variable";
6531 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006532
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006533 case FK_Incomplete:
6534 OS << "initialization of incomplete type";
6535 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006536
6537 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006538 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006539 break;
6540
John McCall73076432012-01-05 00:13:19 +00006541 case FK_VariableLengthArrayHasInitializer:
6542 OS << "variable length array has an initializer";
6543 break;
6544
John McCall5acb0c92011-10-17 18:40:02 +00006545 case FK_PlaceholderType:
6546 OS << "initializer expression isn't contextually valid";
6547 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006548
6549 case FK_ListConstructorOverloadFailed:
6550 OS << "list constructor overloading failed";
6551 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006552
6553 case FK_InitListElementCopyFailure:
6554 OS << "copy construction of initializer list element failed";
6555 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006556
6557 case FK_ExplicitConstructor:
6558 OS << "list copy initialization chose explicit constructor";
6559 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006560 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006561 OS << '\n';
6562 return;
6563 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006564
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006565 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006566 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006567 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006568
Sebastian Redl7491c492011-06-05 13:59:11 +00006569 case NormalSequence:
6570 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006571 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006572 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006573
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006574 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6575 if (S != step_begin()) {
6576 OS << " -> ";
6577 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006578
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006579 switch (S->Kind) {
6580 case SK_ResolveAddressOfOverloadedFunction:
6581 OS << "resolve address of overloaded function";
6582 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006583
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006584 case SK_CastDerivedToBaseRValue:
6585 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6586 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006587
Sebastian Redl906082e2010-07-20 04:20:21 +00006588 case SK_CastDerivedToBaseXValue:
6589 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6590 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006591
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006592 case SK_CastDerivedToBaseLValue:
6593 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6594 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006595
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006596 case SK_BindReference:
6597 OS << "bind reference to lvalue";
6598 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006599
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006600 case SK_BindReferenceToTemporary:
6601 OS << "bind reference to a temporary";
6602 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006603
Douglas Gregor523d46a2010-04-18 07:40:54 +00006604 case SK_ExtraneousCopyToTemporary:
6605 OS << "extraneous C++03 copy to temporary";
6606 break;
6607
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006608 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006609 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006610 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006611
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006612 case SK_QualificationConversionRValue:
6613 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006614 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006615
Sebastian Redl906082e2010-07-20 04:20:21 +00006616 case SK_QualificationConversionXValue:
6617 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006618 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006619
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006620 case SK_QualificationConversionLValue:
6621 OS << "qualification conversion (lvalue)";
6622 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006623
Jordan Rose1fd1e282013-04-11 00:58:58 +00006624 case SK_LValueToRValue:
6625 OS << "load (lvalue to rvalue)";
6626 break;
6627
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006628 case SK_ConversionSequence:
6629 OS << "implicit conversion sequence (";
6630 S->ICS->DebugPrint(); // FIXME: use OS
6631 OS << ")";
6632 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006633
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006634 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006635 OS << "list aggregate initialization";
6636 break;
6637
6638 case SK_ListConstructorCall:
6639 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006640 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006641
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006642 case SK_UnwrapInitList:
6643 OS << "unwrap reference initializer list";
6644 break;
6645
6646 case SK_RewrapInitList:
6647 OS << "rewrap reference initializer list";
6648 break;
6649
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006650 case SK_ConstructorInitialization:
6651 OS << "constructor initialization";
6652 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006653
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006654 case SK_ZeroInitialization:
6655 OS << "zero initialization";
6656 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006657
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006658 case SK_CAssignment:
6659 OS << "C assignment";
6660 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006661
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006662 case SK_StringInit:
6663 OS << "string initialization";
6664 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006665
6666 case SK_ObjCObjectConversion:
6667 OS << "Objective-C object conversion";
6668 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006669
6670 case SK_ArrayInit:
6671 OS << "array initialization";
6672 break;
John McCallf85e1932011-06-15 23:02:42 +00006673
Richard Smith0f163e92012-02-15 22:38:09 +00006674 case SK_ParenthesizedArrayInit:
6675 OS << "parenthesized array initialization";
6676 break;
6677
John McCallf85e1932011-06-15 23:02:42 +00006678 case SK_PassByIndirectCopyRestore:
6679 OS << "pass by indirect copy and restore";
6680 break;
6681
6682 case SK_PassByIndirectRestore:
6683 OS << "pass by indirect restore";
6684 break;
6685
6686 case SK_ProduceObjCObject:
6687 OS << "Objective-C object retension";
6688 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006689
6690 case SK_StdInitializerList:
6691 OS << "std::initializer_list from initializer list";
6692 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006693
Guy Benyei21f18c42013-02-07 10:55:47 +00006694 case SK_OCLSamplerInit:
6695 OS << "OpenCL sampler_t from integer constant";
6696 break;
6697
Guy Benyeie6b9d802013-01-20 12:31:11 +00006698 case SK_OCLZeroEvent:
6699 OS << "OpenCL event_t from zero";
6700 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006701 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006702
6703 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006704 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006705
6706 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006707}
6708
6709void InitializationSequence::dump() const {
6710 dump(llvm::errs());
6711}
6712
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006713static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6714 QualType EntityType,
6715 const Expr *PreInit,
6716 const Expr *PostInit) {
6717 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6718 return;
6719
6720 // A narrowing conversion can only appear as the final implicit conversion in
6721 // an initialization sequence.
6722 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6723 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6724 return;
6725
6726 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6727 const StandardConversionSequence *SCS = 0;
6728 switch (ICS.getKind()) {
6729 case ImplicitConversionSequence::StandardConversion:
6730 SCS = &ICS.Standard;
6731 break;
6732 case ImplicitConversionSequence::UserDefinedConversion:
6733 SCS = &ICS.UserDefined.After;
6734 break;
6735 case ImplicitConversionSequence::AmbiguousConversion:
6736 case ImplicitConversionSequence::EllipsisConversion:
6737 case ImplicitConversionSequence::BadConversion:
6738 return;
6739 }
6740
6741 // Determine the type prior to the narrowing conversion. If a conversion
6742 // operator was used, this may be different from both the type of the entity
6743 // and of the pre-initialization expression.
6744 QualType PreNarrowingType = PreInit->getType();
6745 if (Seq.step_begin() + 1 != Seq.step_end())
6746 PreNarrowingType = Seq.step_end()[-2].Type;
6747
6748 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6749 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006750 QualType ConstantType;
6751 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6752 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006753 case NK_Not_Narrowing:
6754 // No narrowing occurred.
6755 return;
6756
6757 case NK_Type_Narrowing:
6758 // This was a floating-to-integer conversion, which is always considered a
6759 // narrowing conversion even if the value is a constant and can be
6760 // represented exactly as an integer.
6761 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006762 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006763 diag::warn_init_list_type_narrowing
6764 : S.isSFINAEContext()?
6765 diag::err_init_list_type_narrowing_sfinae
6766 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006767 << PostInit->getSourceRange()
6768 << PreNarrowingType.getLocalUnqualifiedType()
6769 << EntityType.getLocalUnqualifiedType();
6770 break;
6771
6772 case NK_Constant_Narrowing:
6773 // A constant value was narrowed.
6774 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006775 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006776 diag::warn_init_list_constant_narrowing
6777 : S.isSFINAEContext()?
6778 diag::err_init_list_constant_narrowing_sfinae
6779 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006780 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006781 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006782 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006783 break;
6784
6785 case NK_Variable_Narrowing:
6786 // A variable's value may have been narrowed.
6787 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006788 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006789 diag::warn_init_list_variable_narrowing
6790 : S.isSFINAEContext()?
6791 diag::err_init_list_variable_narrowing_sfinae
6792 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006793 << PostInit->getSourceRange()
6794 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006795 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006796 break;
6797 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006798
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006799 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006800 llvm::raw_svector_ostream OS(StaticCast);
6801 OS << "static_cast<";
6802 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6803 // It's important to use the typedef's name if there is one so that the
6804 // fixit doesn't break code using types like int64_t.
6805 //
6806 // FIXME: This will break if the typedef requires qualification. But
6807 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006808 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006809 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006810 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006811 else {
6812 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6813 // with a broken cast.
6814 return;
6815 }
6816 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006817 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6818 << PostInit->getSourceRange()
6819 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006820 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006821 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006822}
6823
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006824//===----------------------------------------------------------------------===//
6825// Initialization helper functions
6826//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006827bool
6828Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6829 ExprResult Init) {
6830 if (Init.isInvalid())
6831 return false;
6832
6833 Expr *InitE = Init.get();
6834 assert(InitE && "No initialization expression");
6835
Douglas Gregor3c394c52012-07-31 22:15:04 +00006836 InitializationKind Kind
6837 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006838 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006839 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006840}
6841
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006842ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006843Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6844 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006845 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006846 bool TopLevelOfInitList,
6847 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006848 if (Init.isInvalid())
6849 return ExprError();
6850
John McCall15d7d122010-11-11 03:21:53 +00006851 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006852 assert(InitE && "No initialization expression?");
6853
6854 if (EqualLoc.isInvalid())
6855 EqualLoc = InitE->getLocStart();
6856
6857 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006858 EqualLoc,
6859 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006860 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006861 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006862
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006863 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006864
6865 if (!Result.isInvalid() && TopLevelOfInitList)
6866 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6867 InitE, Result.get());
6868
6869 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006870}