blob: 7b41ee1af3666aaa64322d7a5bc1c1c9cfade181 [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
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000840 // FIXME: Need to handle atomic aggregate types with implicit init lists.
841 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCallfef8b342011-02-21 07:57:55 +0000842 return CheckScalarType(Entity, IList, ElemType, Index,
843 StructuredList, StructuredIndex);
Anders Carlssond28b4282009-08-27 17:18:13 +0000844
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000845 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
846 ElemType->isArrayType()) && "Unexpected type");
847
John McCallfef8b342011-02-21 07:57:55 +0000848 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
849 // arrayType can be incomplete if we're initializing a flexible
850 // array member. There's nothing we can do with the completed
851 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000852
Hans Wennborg0ff50742013-05-15 11:03:04 +0000853 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000854 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000855 CheckStringInit(expr, ElemType, arrayType, SemaRef);
856 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000857 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000858 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000859 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000860 }
John McCallfef8b342011-02-21 07:57:55 +0000861
862 // Fall through for subaggregate initialization.
863
David Blaikie4e4d0842012-03-11 07:00:24 +0000864 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000865 // C++ [dcl.init.aggr]p12:
866 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000867 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000868 // an initializer-list. If the initializer can initialize a
869 // member, the member is initialized. [...]
870
871 // FIXME: Better EqualLoc?
872 InitializationKind Kind =
873 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000874 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000875
876 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000877 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000878 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000879 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000880 if (Result.isInvalid())
881 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000882
Sebastian Redl14b0c192011-09-24 17:48:00 +0000883 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000884 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000885 }
John McCallfef8b342011-02-21 07:57:55 +0000886 ++Index;
887 return;
888 }
889
890 // Fall through for subaggregate initialization
891 } else {
892 // C99 6.7.8p13:
893 //
894 // The initializer for a structure or union object that has
895 // automatic storage duration shall be either an initializer
896 // list as described below, or a single expression that has
897 // compatible structure or union type. In the latter case, the
898 // initial value of the object, including unnamed members, is
899 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000900 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000901 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000902 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
903 !VerifyOnly)
Eli Friedman08f0bbc2013-09-17 04:07:04 +0000904 != Sema::Incompatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000905 if (ExprRes.isInvalid())
906 hadError = true;
907 else {
908 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000909 if (ExprRes.isInvalid())
910 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000911 }
912 UpdateStructuredListElement(StructuredList, StructuredIndex,
913 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000914 ++Index;
915 return;
916 }
John Wiegley429bb272011-04-08 18:41:53 +0000917 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000918 // Fall through for subaggregate initialization
919 }
920
921 // C++ [dcl.init.aggr]p12:
922 //
923 // [...] Otherwise, if the member is itself a non-empty
924 // subaggregate, brace elision is assumed and the initializer is
925 // considered for the initialization of the first member of
926 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000927 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000928 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000929 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
930 StructuredIndex);
931 ++StructuredIndex;
932 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000933 if (!VerifyOnly) {
934 // We cannot initialize this element, so let
935 // PerformCopyInitialization produce the appropriate diagnostic.
936 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
937 SemaRef.Owned(expr),
938 /*TopLevelOfInitList=*/true);
939 }
John McCallfef8b342011-02-21 07:57:55 +0000940 hadError = true;
941 ++Index;
942 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000943 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000944}
945
Eli Friedman0c706c22011-09-19 23:17:44 +0000946void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
947 InitListExpr *IList, QualType DeclType,
948 unsigned &Index,
949 InitListExpr *StructuredList,
950 unsigned &StructuredIndex) {
951 assert(Index == 0 && "Index in explicit init list must be zero");
952
953 // As an extension, clang supports complex initializers, which initialize
954 // a complex number component-wise. When an explicit initializer list for
955 // a complex number contains two two initializers, this extension kicks in:
956 // it exepcts the initializer list to contain two elements convertible to
957 // the element type of the complex type. The first element initializes
958 // the real part, and the second element intitializes the imaginary part.
959
960 if (IList->getNumInits() != 2)
961 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
962 StructuredIndex);
963
964 // This is an extension in C. (The builtin _Complex type does not exist
965 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000966 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000967 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
968 << IList->getSourceRange();
969
970 // Initialize the complex number.
971 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
972 InitializedEntity ElementEntity =
973 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
974
975 for (unsigned i = 0; i < 2; ++i) {
976 ElementEntity.setElementIndex(Index);
977 CheckSubElementType(ElementEntity, IList, elementType, Index,
978 StructuredList, StructuredIndex);
979 }
980}
981
982
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000983void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000984 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000985 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000986 InitListExpr *StructuredList,
987 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000988 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000989 if (!VerifyOnly)
990 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000991 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000992 diag::warn_cxx98_compat_empty_scalar_initializer :
993 diag::err_empty_scalar_initializer)
994 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000995 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000996 ++Index;
997 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000998 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000999 }
John McCallb934c2d2010-11-11 00:46:36 +00001000
1001 Expr *expr = IList->getInit(Index);
1002 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001003 if (!VerifyOnly)
1004 SemaRef.Diag(SubIList->getLocStart(),
1005 diag::warn_many_braces_around_scalar_init)
1006 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001007
1008 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1009 StructuredIndex);
1010 return;
1011 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001012 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001013 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001014 diag::err_designator_for_scalar_init)
1015 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001016 hadError = true;
1017 ++Index;
1018 ++StructuredIndex;
1019 return;
1020 }
1021
Sebastian Redl14b0c192011-09-24 17:48:00 +00001022 if (VerifyOnly) {
1023 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1024 hadError = true;
1025 ++Index;
1026 return;
1027 }
1028
John McCallb934c2d2010-11-11 00:46:36 +00001029 ExprResult Result =
1030 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001031 SemaRef.Owned(expr),
1032 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001033
1034 Expr *ResultExpr = 0;
1035
1036 if (Result.isInvalid())
1037 hadError = true; // types weren't compatible.
1038 else {
1039 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040
John McCallb934c2d2010-11-11 00:46:36 +00001041 if (ResultExpr != expr) {
1042 // The type was promoted, update initializer list.
1043 IList->setInit(Index, ResultExpr);
1044 }
1045 }
1046 if (hadError)
1047 ++StructuredIndex;
1048 else
1049 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1050 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001051}
1052
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001053void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1054 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001055 unsigned &Index,
1056 InitListExpr *StructuredList,
1057 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001058 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001059 // FIXME: It would be wonderful if we could point at the actual member. In
1060 // general, it would be useful to pass location information down the stack,
1061 // so that we know the location (or decl) of the "current object" being
1062 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001063 if (!VerifyOnly)
1064 SemaRef.Diag(IList->getLocStart(),
1065 diag::err_init_reference_member_uninitialized)
1066 << DeclType
1067 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001068 hadError = true;
1069 ++Index;
1070 ++StructuredIndex;
1071 return;
1072 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001073
1074 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001075 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001076 if (!VerifyOnly)
1077 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1078 << DeclType << IList->getSourceRange();
1079 hadError = true;
1080 ++Index;
1081 ++StructuredIndex;
1082 return;
1083 }
1084
1085 if (VerifyOnly) {
1086 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1087 hadError = true;
1088 ++Index;
1089 return;
1090 }
1091
1092 ExprResult Result =
1093 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1094 SemaRef.Owned(expr),
1095 /*TopLevelOfInitList=*/true);
1096
1097 if (Result.isInvalid())
1098 hadError = true;
1099
1100 expr = Result.takeAs<Expr>();
1101 IList->setInit(Index, expr);
1102
1103 if (hadError)
1104 ++StructuredIndex;
1105 else
1106 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1107 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001108}
1109
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001110void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001111 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001112 unsigned &Index,
1113 InitListExpr *StructuredList,
1114 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001115 const VectorType *VT = DeclType->getAs<VectorType>();
1116 unsigned maxElements = VT->getNumElements();
1117 unsigned numEltsInit = 0;
1118 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001119
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001120 if (Index >= IList->getNumInits()) {
1121 // Make sure the element type can be value-initialized.
1122 if (VerifyOnly)
1123 CheckValueInitializable(
1124 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1125 return;
1126 }
1127
David Blaikie4e4d0842012-03-11 07:00:24 +00001128 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001129 // If the initializing element is a vector, try to copy-initialize
1130 // instead of breaking it apart (which is doomed to failure anyway).
1131 Expr *Init = IList->getInit(Index);
1132 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001133 if (VerifyOnly) {
1134 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1135 hadError = true;
1136 ++Index;
1137 return;
1138 }
1139
John McCall20e047a2010-10-30 00:11:39 +00001140 ExprResult Result =
1141 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001142 SemaRef.Owned(Init),
1143 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001144
1145 Expr *ResultExpr = 0;
1146 if (Result.isInvalid())
1147 hadError = true; // types weren't compatible.
1148 else {
1149 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001150
John McCall20e047a2010-10-30 00:11:39 +00001151 if (ResultExpr != Init) {
1152 // The type was promoted, update initializer list.
1153 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001154 }
1155 }
John McCall20e047a2010-10-30 00:11:39 +00001156 if (hadError)
1157 ++StructuredIndex;
1158 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001159 UpdateStructuredListElement(StructuredList, StructuredIndex,
1160 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001161 ++Index;
1162 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001163 }
Mike Stump1eb44332009-09-09 15:08:12 +00001164
John McCall20e047a2010-10-30 00:11:39 +00001165 InitializedEntity ElementEntity =
1166 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001167
John McCall20e047a2010-10-30 00:11:39 +00001168 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1169 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001170 if (Index >= IList->getNumInits()) {
1171 if (VerifyOnly)
1172 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001173 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001175
John McCall20e047a2010-10-30 00:11:39 +00001176 ElementEntity.setElementIndex(Index);
1177 CheckSubElementType(ElementEntity, IList, elementType, Index,
1178 StructuredList, StructuredIndex);
1179 }
1180 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001181 }
John McCall20e047a2010-10-30 00:11:39 +00001182
1183 InitializedEntity ElementEntity =
1184 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001185
John McCall20e047a2010-10-30 00:11:39 +00001186 // OpenCL initializers allows vectors to be constructed from vectors.
1187 for (unsigned i = 0; i < maxElements; ++i) {
1188 // Don't attempt to go past the end of the init list
1189 if (Index >= IList->getNumInits())
1190 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001191
John McCall20e047a2010-10-30 00:11:39 +00001192 ElementEntity.setElementIndex(Index);
1193
1194 QualType IType = IList->getInit(Index)->getType();
1195 if (!IType->isVectorType()) {
1196 CheckSubElementType(ElementEntity, IList, elementType, Index,
1197 StructuredList, StructuredIndex);
1198 ++numEltsInit;
1199 } else {
1200 QualType VecType;
1201 const VectorType *IVT = IType->getAs<VectorType>();
1202 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001203
John McCall20e047a2010-10-30 00:11:39 +00001204 if (IType->isExtVectorType())
1205 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1206 else
1207 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001208 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001209 CheckSubElementType(ElementEntity, IList, VecType, Index,
1210 StructuredList, StructuredIndex);
1211 numEltsInit += numIElts;
1212 }
1213 }
1214
1215 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001216 if (numEltsInit != maxElements) {
1217 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001218 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001219 diag::err_vector_incorrect_num_initializers)
1220 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1221 hadError = true;
1222 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001223}
1224
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001225void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001226 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001227 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001228 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001229 unsigned &Index,
1230 InitListExpr *StructuredList,
1231 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001232 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1233
Steve Naroff0cca7492008-05-01 22:18:59 +00001234 // Check for the special-case of initializing an array with a string.
1235 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001236 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1237 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001238 // We place the string literal directly into the resulting
1239 // initializer list. This is the only place where the structure
1240 // of the structured initializer list doesn't match exactly,
1241 // because doing so would involve allocating one character
1242 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001243 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001244 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1245 UpdateStructuredListElement(StructuredList, StructuredIndex,
1246 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001247 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1248 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001249 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001250 return;
1251 }
1252 }
John McCallce6c9b72011-02-21 07:22:22 +00001253 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001254 // Check for VLAs; in standard C it would be possible to check this
1255 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1256 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001257 if (!VerifyOnly)
1258 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1259 diag::err_variable_object_no_init)
1260 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001261 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001262 ++Index;
1263 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001264 return;
1265 }
1266
Douglas Gregor05c13a32009-01-22 00:58:24 +00001267 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001268 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1269 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001270 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001271 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001272 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001273 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001274 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001275 maxElementsKnown = true;
1276 }
1277
John McCallce6c9b72011-02-21 07:22:22 +00001278 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001279 while (Index < IList->getNumInits()) {
1280 Expr *Init = IList->getInit(Index);
1281 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001282 // If we're not the subobject that matches up with the '{' for
1283 // the designator, we shouldn't be handling the
1284 // designator. Return immediately.
1285 if (!SubobjectIsDesignatorContext)
1286 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001287
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001288 // Handle this designated initializer. elementIndex will be
1289 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001290 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001291 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001292 StructuredList, StructuredIndex, true,
1293 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001294 hadError = true;
1295 continue;
1296 }
1297
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001298 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001299 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001300 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001301 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001302 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001303
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001304 // If the array is of incomplete type, keep track of the number of
1305 // elements in the initializer.
1306 if (!maxElementsKnown && elementIndex > maxElements)
1307 maxElements = elementIndex;
1308
Douglas Gregor05c13a32009-01-22 00:58:24 +00001309 continue;
1310 }
1311
1312 // If we know the maximum number of elements, and we've already
1313 // hit it, stop consuming elements in the initializer list.
1314 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001315 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001316
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001317 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001318 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001319 Entity);
1320 // Check this element.
1321 CheckSubElementType(ElementEntity, IList, elementType, Index,
1322 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001323 ++elementIndex;
1324
1325 // If the array is of incomplete type, keep track of the number of
1326 // elements in the initializer.
1327 if (!maxElementsKnown && elementIndex > maxElements)
1328 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001329 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001330 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001331 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001332 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001333 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001334 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001335 // Sizing an array implicitly to zero is not allowed by ISO C,
1336 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001337 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001338 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001339 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001340
Mike Stump1eb44332009-09-09 15:08:12 +00001341 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001342 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001343 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001344 if (!hadError && VerifyOnly) {
1345 // Check if there are any members of the array that get value-initialized.
1346 // If so, check if doing that is possible.
1347 // FIXME: This needs to detect holes left by designated initializers too.
1348 if (maxElementsKnown && elementIndex < maxElements)
1349 CheckValueInitializable(InitializedEntity::InitializeElement(
1350 SemaRef.Context, 0, Entity));
1351 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001352}
1353
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001354bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1355 Expr *InitExpr,
1356 FieldDecl *Field,
1357 bool TopLevelObject) {
1358 // Handle GNU flexible array initializers.
1359 unsigned FlexArrayDiag;
1360 if (isa<InitListExpr>(InitExpr) &&
1361 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1362 // Empty flexible array init always allowed as an extension
1363 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001364 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001365 // Disallow flexible array init in C++; it is not required for gcc
1366 // compatibility, and it needs work to IRGen correctly in general.
1367 FlexArrayDiag = diag::err_flexible_array_init;
1368 } else if (!TopLevelObject) {
1369 // Disallow flexible array init on non-top-level object
1370 FlexArrayDiag = diag::err_flexible_array_init;
1371 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1372 // Disallow flexible array init on anything which is not a variable.
1373 FlexArrayDiag = diag::err_flexible_array_init;
1374 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1375 // Disallow flexible array init on local variables.
1376 FlexArrayDiag = diag::err_flexible_array_init;
1377 } else {
1378 // Allow other cases.
1379 FlexArrayDiag = diag::ext_flexible_array_init;
1380 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001381
1382 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001383 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001384 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001385 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001386 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1387 << Field;
1388 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001389
1390 return FlexArrayDiag != diag::ext_flexible_array_init;
1391}
1392
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001393void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001394 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001395 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001396 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001397 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001398 unsigned &Index,
1399 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001400 unsigned &StructuredIndex,
1401 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001402 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Eli Friedmanb85f7072008-05-19 19:16:24 +00001404 // If the record is invalid, some of it's members are invalid. To avoid
1405 // confusion, we forgo checking the intializer for the entire record.
1406 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001407 // Assume it was supposed to consume a single initializer.
1408 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001409 hadError = true;
1410 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001411 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001412
1413 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001414 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001415
1416 // If there's a default initializer, use it.
1417 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1418 if (VerifyOnly)
1419 return;
1420 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1421 Field != FieldEnd; ++Field) {
1422 if (Field->hasInClassInitializer()) {
1423 StructuredList->setInitializedFieldInUnion(*Field);
1424 // FIXME: Actually build a CXXDefaultInitExpr?
1425 return;
1426 }
1427 }
1428 }
1429
1430 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001431 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1432 Field != FieldEnd; ++Field) {
1433 if (Field->getDeclName()) {
1434 if (VerifyOnly)
1435 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001436 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001437 else
David Blaikie581deb32012-06-06 20:45:41 +00001438 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001439 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001440 }
1441 }
1442 return;
1443 }
1444
Douglas Gregor05c13a32009-01-22 00:58:24 +00001445 // If structDecl is a forward declaration, this loop won't do
1446 // anything except look at designated initializers; That's okay,
1447 // because an error should get printed out elsewhere. It might be
1448 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001449 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001450 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001451 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001452 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001453 while (Index < IList->getNumInits()) {
1454 Expr *Init = IList->getInit(Index);
1455
1456 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001457 // If we're not the subobject that matches up with the '{' for
1458 // the designator, we shouldn't be handling the
1459 // designator. Return immediately.
1460 if (!SubobjectIsDesignatorContext)
1461 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001462
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001463 // Handle this designated initializer. Field will be updated to
1464 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001465 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001466 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001467 StructuredList, StructuredIndex,
1468 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001469 hadError = true;
1470
Douglas Gregordfb5e592009-02-12 19:00:39 +00001471 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001472
1473 // Disable check for missing fields when designators are used.
1474 // This matches gcc behaviour.
1475 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001476 continue;
1477 }
1478
1479 if (Field == FieldEnd) {
1480 // We've run out of fields. We're done.
1481 break;
1482 }
1483
Douglas Gregordfb5e592009-02-12 19:00:39 +00001484 // We've already initialized a member of a union. We're done.
1485 if (InitializedSomething && DeclType->isUnionType())
1486 break;
1487
Douglas Gregor44b43212008-12-11 16:49:14 +00001488 // If we've hit the flexible array member at the end, we're done.
1489 if (Field->getType()->isIncompleteArrayType())
1490 break;
1491
Douglas Gregor0bb76892009-01-29 16:53:55 +00001492 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001493 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001494 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001495 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001496 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001497
Douglas Gregor54001c12011-06-29 21:51:31 +00001498 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001499 bool InvalidUse;
1500 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001501 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001502 else
David Blaikie581deb32012-06-06 20:45:41 +00001503 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001504 IList->getInit(Index)->getLocStart());
1505 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001506 ++Index;
1507 ++Field;
1508 hadError = true;
1509 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001510 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001511
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001512 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001513 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001514 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1515 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001516 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001517
Sebastian Redl14b0c192011-09-24 17:48:00 +00001518 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001519 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001520 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001521 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001522
1523 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001524 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001525
John McCall80639de2010-03-11 19:32:38 +00001526 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001527 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1528 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1529 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001530 // It is possible we have one or more unnamed bitfields remaining.
1531 // Find first (if any) named field and emit warning.
1532 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1533 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001534 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001535 SemaRef.Diag(IList->getSourceRange().getEnd(),
1536 diag::warn_missing_field_initializers) << it->getName();
1537 break;
1538 }
1539 }
1540 }
1541
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001542 // Check that any remaining fields can be value-initialized.
1543 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1544 !Field->getType()->isIncompleteArrayType()) {
1545 // FIXME: Should check for holes left by designated initializers too.
1546 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001547 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001548 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001549 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001550 }
1551 }
1552
Mike Stump1eb44332009-09-09 15:08:12 +00001553 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001554 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001555 return;
1556
David Blaikie581deb32012-06-06 20:45:41 +00001557 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001558 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001559 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001560 ++Index;
1561 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001562 }
1563
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001564 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001565 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001566
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001567 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001568 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001569 StructuredList, StructuredIndex);
1570 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001571 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001572 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001573}
Steve Naroff0cca7492008-05-01 22:18:59 +00001574
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001575/// \brief Expand a field designator that refers to a member of an
1576/// anonymous struct or union into a series of field designators that
1577/// refers to the field within the appropriate subobject.
1578///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001579static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001580 DesignatedInitExpr *DIE,
1581 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001582 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001583 typedef DesignatedInitExpr::Designator Designator;
1584
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001585 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001586 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001587 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1588 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1589 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001590 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001591 DIE->getDesignator(DesigIdx)->getDotLoc(),
1592 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1593 else
1594 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1595 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001596 assert(isa<FieldDecl>(*PI));
1597 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001598 }
1599
1600 // Expand the current designator into the set of replacement
1601 // designators, so we have a full subobject path down to where the
1602 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001603 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001604 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001605}
Mike Stump1eb44332009-09-09 15:08:12 +00001606
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001607/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001608/// corresponds to FieldName.
1609static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1610 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001611 if (!FieldName)
1612 return 0;
1613
Francois Picheta0e27f02010-12-22 03:46:10 +00001614 assert(AnonField->isAnonymousStructOrUnion());
1615 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001616 while (IndirectFieldDecl *IF =
1617 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001618 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001619 return IF;
1620 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001621 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001622 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001623}
1624
Sebastian Redl14b0c192011-09-24 17:48:00 +00001625static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1626 DesignatedInitExpr *DIE) {
1627 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1628 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1629 for (unsigned I = 0; I < NumIndexExprs; ++I)
1630 IndexExprs[I] = DIE->getSubExpr(I + 1);
1631 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001632 DIE->size(), IndexExprs,
1633 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001634 DIE->usesGNUSyntax(), DIE->getInit());
1635}
1636
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001637namespace {
1638
1639// Callback to only accept typo corrections that are for field members of
1640// the given struct or union.
1641class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1642 public:
1643 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1644 : Record(RD) {}
1645
1646 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1647 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1648 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1649 }
1650
1651 private:
1652 RecordDecl *Record;
1653};
1654
1655}
1656
Douglas Gregor05c13a32009-01-22 00:58:24 +00001657/// @brief Check the well-formedness of a C99 designated initializer.
1658///
1659/// Determines whether the designated initializer @p DIE, which
1660/// resides at the given @p Index within the initializer list @p
1661/// IList, is well-formed for a current object of type @p DeclType
1662/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001663/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001664/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001665///
1666/// @param IList The initializer list in which this designated
1667/// initializer occurs.
1668///
Douglas Gregor71199712009-04-15 04:56:10 +00001669/// @param DIE The designated initializer expression.
1670///
1671/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001672///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001673/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001674/// into which the designation in @p DIE should refer.
1675///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001676/// @param NextField If non-NULL and the first designator in @p DIE is
1677/// a field, this will be set to the field declaration corresponding
1678/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001679///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001680/// @param NextElementIndex If non-NULL and the first designator in @p
1681/// DIE is an array designator or GNU array-range designator, this
1682/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001683///
1684/// @param Index Index into @p IList where the designated initializer
1685/// @p DIE occurs.
1686///
Douglas Gregor4c678342009-01-28 21:54:33 +00001687/// @param StructuredList The initializer list expression that
1688/// describes all of the subobject initializers in the order they'll
1689/// actually be initialized.
1690///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001691/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001692bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001693InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001694 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001695 DesignatedInitExpr *DIE,
1696 unsigned DesigIdx,
1697 QualType &CurrentObjectType,
1698 RecordDecl::field_iterator *NextField,
1699 llvm::APSInt *NextElementIndex,
1700 unsigned &Index,
1701 InitListExpr *StructuredList,
1702 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001703 bool FinishSubobjectInit,
1704 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001705 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001706 // Check the actual initialization for the designated object type.
1707 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001708
1709 // Temporarily remove the designator expression from the
1710 // initializer list that the child calls see, so that we don't try
1711 // to re-process the designator.
1712 unsigned OldIndex = Index;
1713 IList->setInit(OldIndex, DIE->getInit());
1714
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001715 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001716 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001717
1718 // Restore the designated initializer expression in the syntactic
1719 // form of the initializer list.
1720 if (IList->getInit(OldIndex) != DIE->getInit())
1721 DIE->setInit(IList->getInit(OldIndex));
1722 IList->setInit(OldIndex, DIE);
1723
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001724 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001725 }
1726
Douglas Gregor71199712009-04-15 04:56:10 +00001727 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001728 bool IsFirstDesignator = (DesigIdx == 0);
1729 if (!VerifyOnly) {
1730 assert((IsFirstDesignator || StructuredList) &&
1731 "Need a non-designated initializer list to start from");
1732
1733 // Determine the structural initializer list that corresponds to the
1734 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001735 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001736 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1737 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001738 SourceRange(D->getLocStart(),
1739 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001740 assert(StructuredList && "Expected a structured initializer list");
1741 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001742
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001743 if (D->isFieldDesignator()) {
1744 // C99 6.7.8p7:
1745 //
1746 // If a designator has the form
1747 //
1748 // . identifier
1749 //
1750 // then the current object (defined below) shall have
1751 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001752 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001753 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001754 if (!RT) {
1755 SourceLocation Loc = D->getDotLoc();
1756 if (Loc.isInvalid())
1757 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001758 if (!VerifyOnly)
1759 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001760 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001761 ++Index;
1762 return true;
1763 }
1764
Douglas Gregor4c678342009-01-28 21:54:33 +00001765 // Note: we perform a linear search of the fields here, despite
1766 // the fact that we have a faster lookup method, because we always
1767 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001768 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001769 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001770 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001771 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001772 Field = RT->getDecl()->field_begin(),
1773 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001774 for (; Field != FieldEnd; ++Field) {
1775 if (Field->isUnnamedBitfield())
1776 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777
Francois Picheta0e27f02010-12-22 03:46:10 +00001778 // If we find a field representing an anonymous field, look in the
1779 // IndirectFieldDecl that follow for the designated initializer.
1780 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1781 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001782 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001783 // In verify mode, don't modify the original.
1784 if (VerifyOnly)
1785 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001786 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1787 D = DIE->getDesignator(DesigIdx);
1788 break;
1789 }
1790 }
David Blaikie581deb32012-06-06 20:45:41 +00001791 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001792 break;
1793 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001794 break;
1795
1796 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001797 }
1798
Douglas Gregor4c678342009-01-28 21:54:33 +00001799 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001800 if (VerifyOnly) {
1801 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001802 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001803 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001804
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001805 // There was no normal field in the struct with the designated
1806 // name. Perform another lookup for this name, which may find
1807 // something that we can't designate (e.g., a member function),
1808 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001809 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001810 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001811 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001812 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001813 // Name lookup didn't find anything. Determine whether this
1814 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001815 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smith2d670972013-08-17 00:46:16 +00001816 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1817 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1818 Sema::LookupMemberName, /*Scope=*/ 0, /*SS=*/ 0, Validator,
1819 RT->getDecl())) {
1820 SemaRef.diagnoseTypo(
1821 Corrected,
1822 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1823 << FieldName << CurrentObjectType);
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001824 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramera41ee492011-09-25 02:41:26 +00001825 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001826 } else {
1827 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1828 << FieldName << CurrentObjectType;
1829 ++Index;
1830 return true;
1831 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001832 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001833
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001834 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001835 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001836 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001837 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001838 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001839 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001840 ++Index;
1841 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001842 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001843
Francois Picheta0e27f02010-12-22 03:46:10 +00001844 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001845 // The replacement field comes from typo correction; find it
1846 // in the list of fields.
1847 FieldIndex = 0;
1848 Field = RT->getDecl()->field_begin();
1849 for (; Field != FieldEnd; ++Field) {
1850 if (Field->isUnnamedBitfield())
1851 continue;
1852
David Blaikie581deb32012-06-06 20:45:41 +00001853 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001854 Field->getIdentifier() == ReplacementField->getIdentifier())
1855 break;
1856
1857 ++FieldIndex;
1858 }
1859 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001860 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001861
1862 // All of the fields of a union are located at the same place in
1863 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001864 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001865 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001866 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001867 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001868 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001869
Douglas Gregor54001c12011-06-29 21:51:31 +00001870 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001871 bool InvalidUse;
1872 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001873 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001874 else
David Blaikie581deb32012-06-06 20:45:41 +00001875 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001876 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001877 ++Index;
1878 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001879 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001880
Sebastian Redl14b0c192011-09-24 17:48:00 +00001881 if (!VerifyOnly) {
1882 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001883 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Sebastian Redl14b0c192011-09-24 17:48:00 +00001885 // Make sure that our non-designated initializer list has space
1886 // for a subobject corresponding to this field.
1887 if (FieldIndex >= StructuredList->getNumInits())
1888 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1889 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001890
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001891 // This designator names a flexible array member.
1892 if (Field->getType()->isIncompleteArrayType()) {
1893 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001894 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001895 // We can't designate an object within the flexible array
1896 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001897 if (!VerifyOnly) {
1898 DesignatedInitExpr::Designator *NextD
1899 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001900 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001901 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001902 << SourceRange(NextD->getLocStart(),
1903 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001904 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001905 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001906 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001907 Invalid = true;
1908 }
1909
Chris Lattner9046c222010-10-10 17:49:49 +00001910 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1911 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001912 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001913 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001914 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001915 diag::err_flexible_array_init_needs_braces)
1916 << DIE->getInit()->getSourceRange();
1917 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001918 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001919 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001920 Invalid = true;
1921 }
1922
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001923 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001924 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001925 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001926 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001927
1928 if (Invalid) {
1929 ++Index;
1930 return true;
1931 }
1932
1933 // Initialize the array.
1934 bool prevHadError = hadError;
1935 unsigned newStructuredIndex = FieldIndex;
1936 unsigned OldIndex = Index;
1937 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001938
1939 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001940 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001941 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001942 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001943
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001944 IList->setInit(OldIndex, DIE);
1945 if (hadError && !prevHadError) {
1946 ++Field;
1947 ++FieldIndex;
1948 if (NextField)
1949 *NextField = Field;
1950 StructuredIndex = FieldIndex;
1951 return true;
1952 }
1953 } else {
1954 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001955 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001956 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001957
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001958 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001959 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001960 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1961 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001962 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001963 true, false))
1964 return true;
1965 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001966
1967 // Find the position of the next field to be initialized in this
1968 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001969 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001970 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001971
1972 // If this the first designator, our caller will continue checking
1973 // the rest of this struct/class/union subobject.
1974 if (IsFirstDesignator) {
1975 if (NextField)
1976 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001977 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001978 return false;
1979 }
1980
Douglas Gregor34e79462009-01-28 23:36:17 +00001981 if (!FinishSubobjectInit)
1982 return false;
1983
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001984 // We've already initialized something in the union; we're done.
1985 if (RT->getDecl()->isUnion())
1986 return hadError;
1987
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001988 // Check the remaining fields within this class/struct/union subobject.
1989 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001990
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001991 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001992 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001993 return hadError && !prevHadError;
1994 }
1995
1996 // C99 6.7.8p6:
1997 //
1998 // If a designator has the form
1999 //
2000 // [ constant-expression ]
2001 //
2002 // then the current object (defined below) shall have array
2003 // type and the expression shall be an integer constant
2004 // expression. If the array is of unknown size, any
2005 // nonnegative value is valid.
2006 //
2007 // Additionally, cope with the GNU extension that permits
2008 // designators of the form
2009 //
2010 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002011 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002012 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002013 if (!VerifyOnly)
2014 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2015 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002016 ++Index;
2017 return true;
2018 }
2019
2020 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00002021 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2022 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002023 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002024 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002025 DesignatedEndIndex = DesignatedStartIndex;
2026 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002027 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002028
Mike Stump1eb44332009-09-09 15:08:12 +00002029 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002030 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002031 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002032 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002033 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002034
Chris Lattnere0fd8322011-02-19 22:28:58 +00002035 // Codegen can't handle evaluating array range designators that have side
2036 // effects, because we replicate the AST value for each initialized element.
2037 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2038 // elements with something that has a side effect, so codegen can emit an
2039 // "error unsupported" error instead of miscompiling the app.
2040 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002041 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002042 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002043 }
2044
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002045 if (isa<ConstantArrayType>(AT)) {
2046 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002047 DesignatedStartIndex
2048 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002049 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002050 DesignatedEndIndex
2051 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002052 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2053 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002054 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002055 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002056 diag::err_array_designator_too_large)
2057 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2058 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002059 ++Index;
2060 return true;
2061 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002062 } else {
2063 // Make sure the bit-widths and signedness match.
2064 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002065 DesignatedEndIndex
2066 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002067 else if (DesignatedStartIndex.getBitWidth() <
2068 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002069 DesignatedStartIndex
2070 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002071 DesignatedStartIndex.setIsUnsigned(true);
2072 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Eli Friedman188ddb12013-06-11 21:48:11 +00002075 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2076 // We're modifying a string literal init; we have to decompose the string
2077 // so we can modify the individual characters.
2078 ASTContext &Context = SemaRef.Context;
2079 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2080
2081 // Compute the character type
2082 QualType CharTy = AT->getElementType();
2083
2084 // Compute the type of the integer literals.
2085 QualType PromotedCharTy = CharTy;
2086 if (CharTy->isPromotableIntegerType())
2087 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2088 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2089
2090 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2091 // Get the length of the string.
2092 uint64_t StrLen = SL->getLength();
2093 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2094 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2095 StructuredList->resizeInits(Context, StrLen);
2096
2097 // Build a literal for each character in the string, and put them into
2098 // the init list.
2099 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2100 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2101 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002102 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002103 if (CharTy != PromotedCharTy)
2104 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2105 Init, 0, VK_RValue);
2106 StructuredList->updateInit(Context, i, Init);
2107 }
2108 } else {
2109 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2110 std::string Str;
2111 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2112
2113 // Get the length of the string.
2114 uint64_t StrLen = Str.size();
2115 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2116 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2117 StructuredList->resizeInits(Context, StrLen);
2118
2119 // Build a literal for each character in the string, and put them into
2120 // the init list.
2121 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2122 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2123 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002124 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002125 if (CharTy != PromotedCharTy)
2126 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2127 Init, 0, VK_RValue);
2128 StructuredList->updateInit(Context, i, Init);
2129 }
2130 }
2131 }
2132
Douglas Gregor4c678342009-01-28 21:54:33 +00002133 // Make sure that our non-designated initializer list has space
2134 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002135 if (!VerifyOnly &&
2136 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002137 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002138 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002139
Douglas Gregor34e79462009-01-28 23:36:17 +00002140 // Repeatedly perform subobject initializations in the range
2141 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002142
Douglas Gregor34e79462009-01-28 23:36:17 +00002143 // Move to the next designator
2144 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2145 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002147 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002148 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002149
Douglas Gregor34e79462009-01-28 23:36:17 +00002150 while (DesignatedStartIndex <= DesignatedEndIndex) {
2151 // Recurse to check later designated subobjects.
2152 QualType ElementType = AT->getElementType();
2153 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002154
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002155 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002156 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2157 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002158 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002159 (DesignatedStartIndex == DesignatedEndIndex),
2160 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002161 return true;
2162
2163 // Move to the next index in the array that we'll be initializing.
2164 ++DesignatedStartIndex;
2165 ElementIndex = DesignatedStartIndex.getZExtValue();
2166 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002167
2168 // If this the first designator, our caller will continue checking
2169 // the rest of this array subobject.
2170 if (IsFirstDesignator) {
2171 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002172 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002173 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002174 return false;
2175 }
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Douglas Gregor34e79462009-01-28 23:36:17 +00002177 if (!FinishSubobjectInit)
2178 return false;
2179
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002180 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002181 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002182 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002183 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002184 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002185 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002186}
2187
Douglas Gregor4c678342009-01-28 21:54:33 +00002188// Get the structured initializer list for a subobject of type
2189// @p CurrentObjectType.
2190InitListExpr *
2191InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2192 QualType CurrentObjectType,
2193 InitListExpr *StructuredList,
2194 unsigned StructuredIndex,
2195 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002196 if (VerifyOnly)
2197 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002198 Expr *ExistingInit = 0;
2199 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002200 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002201 else if (StructuredIndex < StructuredList->getNumInits())
2202 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Douglas Gregor4c678342009-01-28 21:54:33 +00002204 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2205 return Result;
2206
2207 if (ExistingInit) {
2208 // We are creating an initializer list that initializes the
2209 // subobjects of the current object, but there was already an
2210 // initialization that completely initialized the current
2211 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002212 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002213 // struct X { int a, b; };
2214 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002215 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002216 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2217 // designated initializer re-initializes the whole
2218 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002219 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002220 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002221 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002222 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002223 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002224 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002225 << ExistingInit->getSourceRange();
2226 }
2227
Mike Stump1eb44332009-09-09 15:08:12 +00002228 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002229 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002230 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002231 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002232
Eli Friedman5c89c392012-02-23 02:25:10 +00002233 QualType ResultType = CurrentObjectType;
2234 if (!ResultType->isArrayType())
2235 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2236 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002237
Douglas Gregorfa219202009-03-20 23:58:33 +00002238 // Pre-allocate storage for the structured initializer list.
2239 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002240 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002241 bool GotNumInits = false;
2242 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002243 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002244 GotNumInits = true;
2245 } else if (Index < IList->getNumInits()) {
2246 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002247 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002248 GotNumInits = true;
2249 }
Douglas Gregor08457732009-03-21 18:13:52 +00002250 }
2251
Mike Stump1eb44332009-09-09 15:08:12 +00002252 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002253 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2254 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2255 NumElements = CAType->getSize().getZExtValue();
2256 // Simple heuristic so that we don't allocate a very large
2257 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002258 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002259 NumElements = 0;
2260 }
John McCall183700f2009-09-21 23:43:11 +00002261 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002262 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002263 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002264 RecordDecl *RDecl = RType->getDecl();
2265 if (RDecl->isUnion())
2266 NumElements = 1;
2267 else
Mike Stump1eb44332009-09-09 15:08:12 +00002268 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002269 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002270 }
2271
Ted Kremenek709210f2010-04-13 23:39:13 +00002272 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002273
Douglas Gregor4c678342009-01-28 21:54:33 +00002274 // Link this new initializer list into the structured initializer
2275 // lists.
2276 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002277 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002278 else {
2279 Result->setSyntacticForm(IList);
2280 SyntacticToSemantic[IList] = Result;
2281 }
2282
2283 return Result;
2284}
2285
2286/// Update the initializer at index @p StructuredIndex within the
2287/// structured initializer list to the value @p expr.
2288void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2289 unsigned &StructuredIndex,
2290 Expr *expr) {
2291 // No structured initializer list to update
2292 if (!StructuredList)
2293 return;
2294
Ted Kremenek709210f2010-04-13 23:39:13 +00002295 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2296 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002297 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002298 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002299 diag::warn_initializer_overrides)
2300 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002301 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002302 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002303 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002304 << PrevInit->getSourceRange();
2305 }
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Douglas Gregor4c678342009-01-28 21:54:33 +00002307 ++StructuredIndex;
2308}
2309
Douglas Gregor05c13a32009-01-22 00:58:24 +00002310/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002311/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002312/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002313/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002314/// failure. Returns the index expression, possibly with an implicit cast
2315/// added, on success. If everything went okay, Value will receive the
2316/// value of the constant expression.
2317static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002318CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002319 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002320
2321 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002322 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2323 if (Result.isInvalid())
2324 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002325
Chris Lattner3bf68932009-04-25 21:59:05 +00002326 if (Value.isSigned() && Value.isNegative())
2327 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002328 << Value.toString(10) << Index->getSourceRange();
2329
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002330 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002331 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002332}
2333
John McCall60d7b3a2010-08-24 06:29:42 +00002334ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002335 SourceLocation Loc,
2336 bool GNUSyntax,
2337 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002338 typedef DesignatedInitExpr::Designator ASTDesignator;
2339
2340 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002341 SmallVector<ASTDesignator, 32> Designators;
2342 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002343
2344 // Build designators and check array designator expressions.
2345 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2346 const Designator &D = Desig.getDesignator(Idx);
2347 switch (D.getKind()) {
2348 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002349 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002350 D.getFieldLoc()));
2351 break;
2352
2353 case Designator::ArrayDesignator: {
2354 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2355 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002356 if (!Index->isTypeDependent() && !Index->isValueDependent())
2357 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2358 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002359 Invalid = true;
2360 else {
2361 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002362 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002363 D.getRBracketLoc()));
2364 InitExpressions.push_back(Index);
2365 }
2366 break;
2367 }
2368
2369 case Designator::ArrayRangeDesignator: {
2370 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2371 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2372 llvm::APSInt StartValue;
2373 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002374 bool StartDependent = StartIndex->isTypeDependent() ||
2375 StartIndex->isValueDependent();
2376 bool EndDependent = EndIndex->isTypeDependent() ||
2377 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002378 if (!StartDependent)
2379 StartIndex =
2380 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2381 if (!EndDependent)
2382 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2383
2384 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002385 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002386 else {
2387 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002388 if (StartDependent || EndDependent) {
2389 // Nothing to compute.
2390 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002391 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002392 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002393 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002394
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002395 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002396 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002397 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002398 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2399 Invalid = true;
2400 } else {
2401 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002402 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002403 D.getEllipsisLoc(),
2404 D.getRBracketLoc()));
2405 InitExpressions.push_back(StartIndex);
2406 InitExpressions.push_back(EndIndex);
2407 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002408 }
2409 break;
2410 }
2411 }
2412 }
2413
2414 if (Invalid || Init.isInvalid())
2415 return ExprError();
2416
2417 // Clear out the expressions within the designation.
2418 Desig.ClearExprs(*this);
2419
2420 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002421 = DesignatedInitExpr::Create(Context,
2422 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002423 InitExpressions, Loc, GNUSyntax,
2424 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002425
David Blaikie4e4d0842012-03-11 07:00:24 +00002426 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002427 Diag(DIE->getLocStart(), diag::ext_designated_init)
2428 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002429
Douglas Gregor05c13a32009-01-22 00:58:24 +00002430 return Owned(DIE);
2431}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002432
Douglas Gregor20093b42009-12-09 23:02:17 +00002433//===----------------------------------------------------------------------===//
2434// Initialization entity
2435//===----------------------------------------------------------------------===//
2436
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002437InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002438 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002439 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002440{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002441 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2442 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002443 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002444 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002445 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002446 Type = VT->getElementType();
2447 } else {
2448 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2449 assert(CT && "Unexpected type");
2450 Kind = EK_ComplexElement;
2451 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002452 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002453}
2454
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002455InitializedEntity
2456InitializedEntity::InitializeBase(ASTContext &Context,
2457 const CXXBaseSpecifier *Base,
2458 bool IsInheritedVirtualBase) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002459 InitializedEntity Result;
2460 Result.Kind = EK_Base;
Richard Smitha4bb99c2013-06-12 21:51:50 +00002461 Result.Parent = 0;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002462 Result.Base = reinterpret_cast<uintptr_t>(Base);
2463 if (IsInheritedVirtualBase)
2464 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002465
Douglas Gregord6542d82009-12-22 15:35:07 +00002466 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002467 return Result;
2468}
2469
Douglas Gregor99a2e602009-12-16 01:38:02 +00002470DeclarationName InitializedEntity::getName() const {
2471 switch (getKind()) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002472 case EK_Parameter:
2473 case EK_Parameter_CF_Audited: {
John McCallf85e1932011-06-15 23:02:42 +00002474 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2475 return (D ? D->getDeclName() : DeclarationName());
2476 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002477
2478 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002479 case EK_Member:
2480 return VariableOrMember->getDeclName();
2481
Douglas Gregor47736542012-02-15 16:57:26 +00002482 case EK_LambdaCapture:
2483 return Capture.Var->getDeclName();
2484
Douglas Gregor99a2e602009-12-16 01:38:02 +00002485 case EK_Result:
2486 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002487 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002488 case EK_Temporary:
2489 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002490 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002491 case EK_ArrayElement:
2492 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002493 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002494 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002495 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002496 case EK_RelatedResult:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002497 return DeclarationName();
2498 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002499
David Blaikie7530c032012-01-17 06:56:22 +00002500 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002501}
2502
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002503DeclaratorDecl *InitializedEntity::getDecl() const {
2504 switch (getKind()) {
2505 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002506 case EK_Member:
2507 return VariableOrMember;
2508
John McCallf85e1932011-06-15 23:02:42 +00002509 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002510 case EK_Parameter_CF_Audited:
John McCallf85e1932011-06-15 23:02:42 +00002511 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2512
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002513 case EK_Result:
2514 case EK_Exception:
2515 case EK_New:
2516 case EK_Temporary:
2517 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002518 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002519 case EK_ArrayElement:
2520 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002521 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002522 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002523 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002524 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002525 case EK_RelatedResult:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002526 return 0;
2527 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002528
David Blaikie7530c032012-01-17 06:56:22 +00002529 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002530}
2531
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002532bool InitializedEntity::allowsNRVO() const {
2533 switch (getKind()) {
2534 case EK_Result:
2535 case EK_Exception:
2536 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002537
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002538 case EK_Variable:
2539 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002540 case EK_Parameter_CF_Audited:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002541 case EK_Member:
2542 case EK_New:
2543 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002544 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002545 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002546 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002547 case EK_ArrayElement:
2548 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002549 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002550 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002551 case EK_LambdaCapture:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002552 case EK_RelatedResult:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002553 break;
2554 }
2555
2556 return false;
2557}
2558
Richard Smith211c8dd2013-06-05 00:46:14 +00002559unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smitha4bb99c2013-06-12 21:51:50 +00002560 assert(getParent() != this);
Richard Smith211c8dd2013-06-05 00:46:14 +00002561 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2562 for (unsigned I = 0; I != Depth; ++I)
2563 OS << "`-";
2564
2565 switch (getKind()) {
2566 case EK_Variable: OS << "Variable"; break;
2567 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002568 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2569 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002570 case EK_Result: OS << "Result"; break;
2571 case EK_Exception: OS << "Exception"; break;
2572 case EK_Member: OS << "Member"; break;
2573 case EK_New: OS << "New"; break;
2574 case EK_Temporary: OS << "Temporary"; break;
2575 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002576 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002577 case EK_Base: OS << "Base"; break;
2578 case EK_Delegating: OS << "Delegating"; break;
2579 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2580 case EK_VectorElement: OS << "VectorElement " << Index; break;
2581 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2582 case EK_BlockElement: OS << "Block"; break;
2583 case EK_LambdaCapture:
2584 OS << "LambdaCapture ";
2585 getCapturedVar()->printName(OS);
2586 break;
2587 }
2588
2589 if (Decl *D = getDecl()) {
2590 OS << " ";
2591 cast<NamedDecl>(D)->printQualifiedName(OS);
2592 }
2593
2594 OS << " '" << getType().getAsString() << "'\n";
2595
2596 return Depth + 1;
2597}
2598
2599void InitializedEntity::dump() const {
2600 dumpImpl(llvm::errs());
2601}
2602
Douglas Gregor20093b42009-12-09 23:02:17 +00002603//===----------------------------------------------------------------------===//
2604// Initialization sequence
2605//===----------------------------------------------------------------------===//
2606
2607void InitializationSequence::Step::Destroy() {
2608 switch (Kind) {
2609 case SK_ResolveAddressOfOverloadedFunction:
2610 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002611 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 case SK_CastDerivedToBaseLValue:
2613 case SK_BindReference:
2614 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002615 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002616 case SK_UserConversion:
2617 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002618 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002619 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002620 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002621 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002622 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002623 case SK_UnwrapInitList:
2624 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002625 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002626 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002627 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002628 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002629 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002630 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002631 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002632 case SK_PassByIndirectCopyRestore:
2633 case SK_PassByIndirectRestore:
2634 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002635 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002636 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002637 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002638 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002639
Douglas Gregor20093b42009-12-09 23:02:17 +00002640 case SK_ConversionSequence:
2641 delete ICS;
2642 }
2643}
2644
Douglas Gregorb70cf442010-03-26 20:14:36 +00002645bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002646 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002647}
2648
2649bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002650 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002651 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002652
Douglas Gregorb70cf442010-03-26 20:14:36 +00002653 switch (getFailureKind()) {
2654 case FK_TooManyInitsForReference:
2655 case FK_ArrayNeedsInitList:
2656 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002657 case FK_ArrayNeedsInitListOrWideStringLiteral:
2658 case FK_NarrowStringIntoWideCharArray:
2659 case FK_WideStringIntoCharArray:
2660 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002661 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2662 case FK_NonConstLValueReferenceBindingToTemporary:
2663 case FK_NonConstLValueReferenceBindingToUnrelated:
2664 case FK_RValueReferenceBindingToLValue:
2665 case FK_ReferenceInitDropsQualifiers:
2666 case FK_ReferenceInitFailed:
2667 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002668 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002669 case FK_TooManyInitsForScalar:
2670 case FK_ReferenceBindingToInitList:
2671 case FK_InitListBadDestinationType:
2672 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002673 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002674 case FK_ArrayTypeMismatch:
2675 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002676 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002677 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002678 case FK_PlaceholderType:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002679 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002680 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002681
Douglas Gregorb70cf442010-03-26 20:14:36 +00002682 case FK_ReferenceInitOverloadFailed:
2683 case FK_UserConversionOverloadFailed:
2684 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002685 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002686 return FailedOverloadResult == OR_Ambiguous;
2687 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002688
David Blaikie7530c032012-01-17 06:56:22 +00002689 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002690}
2691
Douglas Gregord6e44a32010-04-16 22:09:46 +00002692bool InitializationSequence::isConstructorInitialization() const {
2693 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2694}
2695
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002696void
2697InitializationSequence
2698::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2699 DeclAccessPair Found,
2700 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002701 Step S;
2702 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2703 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002704 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002705 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002706 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002707 Steps.push_back(S);
2708}
2709
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002710void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002711 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002712 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002713 switch (VK) {
2714 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2715 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2716 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002717 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002718 S.Type = BaseType;
2719 Steps.push_back(S);
2720}
2721
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002722void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002723 bool BindingTemporary) {
2724 Step S;
2725 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2726 S.Type = T;
2727 Steps.push_back(S);
2728}
2729
Douglas Gregor523d46a2010-04-18 07:40:54 +00002730void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2731 Step S;
2732 S.Kind = SK_ExtraneousCopyToTemporary;
2733 S.Type = T;
2734 Steps.push_back(S);
2735}
2736
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002737void
2738InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2739 DeclAccessPair FoundDecl,
2740 QualType T,
2741 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002742 Step S;
2743 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002744 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002745 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002746 S.Function.Function = Function;
2747 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002748 Steps.push_back(S);
2749}
2750
2751void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002752 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002753 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002754 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002755 switch (VK) {
2756 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002757 S.Kind = SK_QualificationConversionRValue;
2758 break;
John McCall5baba9d2010-08-25 10:28:54 +00002759 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002760 S.Kind = SK_QualificationConversionXValue;
2761 break;
John McCall5baba9d2010-08-25 10:28:54 +00002762 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002763 S.Kind = SK_QualificationConversionLValue;
2764 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002765 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002766 S.Type = Ty;
2767 Steps.push_back(S);
2768}
2769
Jordan Rose1fd1e282013-04-11 00:58:58 +00002770void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2771 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2772
2773 Step S;
2774 S.Kind = SK_LValueToRValue;
2775 S.Type = Ty;
2776 Steps.push_back(S);
2777}
2778
Douglas Gregor20093b42009-12-09 23:02:17 +00002779void InitializationSequence::AddConversionSequenceStep(
2780 const ImplicitConversionSequence &ICS,
2781 QualType T) {
2782 Step S;
2783 S.Kind = SK_ConversionSequence;
2784 S.Type = T;
2785 S.ICS = new ImplicitConversionSequence(ICS);
2786 Steps.push_back(S);
2787}
2788
Douglas Gregord87b61f2009-12-10 17:56:55 +00002789void InitializationSequence::AddListInitializationStep(QualType T) {
2790 Step S;
2791 S.Kind = SK_ListInitialization;
2792 S.Type = T;
2793 Steps.push_back(S);
2794}
2795
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002796void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002797InitializationSequence
2798::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2799 AccessSpecifier Access,
2800 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002801 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002802 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002803 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002804 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2805 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002806 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002807 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002808 S.Function.Function = Constructor;
2809 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002810 Steps.push_back(S);
2811}
2812
Douglas Gregor71d17402009-12-15 00:01:57 +00002813void InitializationSequence::AddZeroInitializationStep(QualType T) {
2814 Step S;
2815 S.Kind = SK_ZeroInitialization;
2816 S.Type = T;
2817 Steps.push_back(S);
2818}
2819
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002820void InitializationSequence::AddCAssignmentStep(QualType T) {
2821 Step S;
2822 S.Kind = SK_CAssignment;
2823 S.Type = T;
2824 Steps.push_back(S);
2825}
2826
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002827void InitializationSequence::AddStringInitStep(QualType T) {
2828 Step S;
2829 S.Kind = SK_StringInit;
2830 S.Type = T;
2831 Steps.push_back(S);
2832}
2833
Douglas Gregor569c3162010-08-07 11:51:51 +00002834void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2835 Step S;
2836 S.Kind = SK_ObjCObjectConversion;
2837 S.Type = T;
2838 Steps.push_back(S);
2839}
2840
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002841void InitializationSequence::AddArrayInitStep(QualType T) {
2842 Step S;
2843 S.Kind = SK_ArrayInit;
2844 S.Type = T;
2845 Steps.push_back(S);
2846}
2847
Richard Smith0f163e92012-02-15 22:38:09 +00002848void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2849 Step S;
2850 S.Kind = SK_ParenthesizedArrayInit;
2851 S.Type = T;
2852 Steps.push_back(S);
2853}
2854
John McCallf85e1932011-06-15 23:02:42 +00002855void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2856 bool shouldCopy) {
2857 Step s;
2858 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2859 : SK_PassByIndirectRestore);
2860 s.Type = type;
2861 Steps.push_back(s);
2862}
2863
2864void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2865 Step S;
2866 S.Kind = SK_ProduceObjCObject;
2867 S.Type = T;
2868 Steps.push_back(S);
2869}
2870
Sebastian Redl2b916b82012-01-17 22:49:42 +00002871void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2872 Step S;
2873 S.Kind = SK_StdInitializerList;
2874 S.Type = T;
2875 Steps.push_back(S);
2876}
2877
Guy Benyei21f18c42013-02-07 10:55:47 +00002878void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2879 Step S;
2880 S.Kind = SK_OCLSamplerInit;
2881 S.Type = T;
2882 Steps.push_back(S);
2883}
2884
Guy Benyeie6b9d802013-01-20 12:31:11 +00002885void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2886 Step S;
2887 S.Kind = SK_OCLZeroEvent;
2888 S.Type = T;
2889 Steps.push_back(S);
2890}
2891
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002892void InitializationSequence::RewrapReferenceInitList(QualType T,
2893 InitListExpr *Syntactic) {
2894 assert(Syntactic->getNumInits() == 1 &&
2895 "Can only rewrap trivial init lists.");
2896 Step S;
2897 S.Kind = SK_UnwrapInitList;
2898 S.Type = Syntactic->getInit(0)->getType();
2899 Steps.insert(Steps.begin(), S);
2900
2901 S.Kind = SK_RewrapInitList;
2902 S.Type = T;
2903 S.WrappingSyntacticList = Syntactic;
2904 Steps.push_back(S);
2905}
2906
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002907void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002908 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002909 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002910 this->Failure = Failure;
2911 this->FailedOverloadResult = Result;
2912}
2913
2914//===----------------------------------------------------------------------===//
2915// Attempt initialization
2916//===----------------------------------------------------------------------===//
2917
John McCallf85e1932011-06-15 23:02:42 +00002918static void MaybeProduceObjCObject(Sema &S,
2919 InitializationSequence &Sequence,
2920 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002921 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002922
2923 /// When initializing a parameter, produce the value if it's marked
2924 /// __attribute__((ns_consumed)).
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002925 if (Entity.isParameterKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002926 if (!Entity.isParameterConsumed())
2927 return;
2928
2929 assert(Entity.getType()->isObjCRetainableType() &&
2930 "consuming an object of unretainable type?");
2931 Sequence.AddProduceObjCObjectStep(Entity.getType());
2932
2933 /// When initializing a return value, if the return type is a
2934 /// retainable type, then returns need to immediately retain the
2935 /// object. If an autorelease is required, it will be done at the
2936 /// last instant.
2937 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2938 if (!Entity.getType()->isObjCRetainableType())
2939 return;
2940
2941 Sequence.AddProduceObjCObjectStep(Entity.getType());
2942 }
2943}
2944
Richard Smith7c3e6152013-06-12 22:31:48 +00002945static void TryListInitialization(Sema &S,
2946 const InitializedEntity &Entity,
2947 const InitializationKind &Kind,
2948 InitListExpr *InitList,
2949 InitializationSequence &Sequence);
2950
Richard Smithf4bb8d02012-07-05 08:39:21 +00002951/// \brief When initializing from init list via constructor, handle
2952/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002953///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002954/// \return true if we have handled initialization of an object of type
2955/// std::initializer_list<T>, false otherwise.
2956static bool TryInitializerListConstruction(Sema &S,
2957 InitListExpr *List,
2958 QualType DestType,
2959 InitializationSequence &Sequence) {
2960 QualType E;
2961 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002962 return false;
2963
Richard Smith7c3e6152013-06-12 22:31:48 +00002964 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
2965 Sequence.setIncompleteTypeFailure(E);
2966 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002967 }
Richard Smith7c3e6152013-06-12 22:31:48 +00002968
2969 // Try initializing a temporary array from the init list.
2970 QualType ArrayType = S.Context.getConstantArrayType(
2971 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2972 List->getNumInits()),
2973 clang::ArrayType::Normal, 0);
2974 InitializedEntity HiddenArray =
2975 InitializedEntity::InitializeTemporary(ArrayType);
2976 InitializationKind Kind =
2977 InitializationKind::CreateDirectList(List->getExprLoc());
2978 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
2979 if (Sequence)
2980 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithf4bb8d02012-07-05 08:39:21 +00002981 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002982}
2983
Sebastian Redl96715b22012-02-04 21:27:39 +00002984static OverloadingResult
2985ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002986 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002987 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002988 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002989 OverloadCandidateSet::iterator &Best,
2990 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002991 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002992 CandidateSet.clear();
2993
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002994 for (ArrayRef<NamedDecl *>::iterator
2995 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002996 NamedDecl *D = *Con;
2997 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2998 bool SuppressUserConversions = false;
2999
3000 // Find the constructor (which may be a template).
3001 CXXConstructorDecl *Constructor = 0;
3002 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3003 if (ConstructorTmpl)
3004 Constructor = cast<CXXConstructorDecl>(
3005 ConstructorTmpl->getTemplatedDecl());
3006 else {
3007 Constructor = cast<CXXConstructorDecl>(D);
3008
3009 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003010 // suppress user-defined conversions on the arguments. We do the same for
3011 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003012 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003013 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00003014 SuppressUserConversions = true;
3015 }
3016
3017 if (!Constructor->isInvalidDecl() &&
3018 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003019 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003020 if (ConstructorTmpl)
3021 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003022 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003023 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00003024 else {
3025 // C++ [over.match.copy]p1:
3026 // - When initializing a temporary to be bound to the first parameter
3027 // of a constructor that takes a reference to possibly cv-qualified
3028 // T as its first argument, called with a single argument in the
3029 // context of direct-initialization, explicit conversion functions
3030 // are also considered.
3031 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003032 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00003033 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003034 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00003035 SuppressUserConversions,
3036 /*PartialOverloading=*/false,
3037 /*AllowExplicit=*/AllowExplicitConv);
3038 }
Sebastian Redl96715b22012-02-04 21:27:39 +00003039 }
3040 }
3041
3042 // Perform overload resolution and return the result.
3043 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3044}
3045
Sebastian Redl10f04a62011-12-22 14:44:04 +00003046/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3047/// enumerates the constructors of the initialized entity and performs overload
3048/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00003049/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00003050/// class type.
3051static void TryConstructorInitialization(Sema &S,
3052 const InitializedEntity &Entity,
3053 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003054 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003055 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00003056 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003057 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00003058 "InitListSyntax must come with a single initializer list argument.");
3059
Sebastian Redl10f04a62011-12-22 14:44:04 +00003060 // The type we're constructing needs to be complete.
3061 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003062 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00003063 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003064 }
3065
3066 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3067 assert(DestRecordType && "Constructor initialization requires record type");
3068 CXXRecordDecl *DestRecordDecl
3069 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3070
Sebastian Redl96715b22012-02-04 21:27:39 +00003071 // Build the candidate set directly in the initialization sequence
3072 // structure, so that it will persist if we fail.
3073 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3074
3075 // Determine whether we are allowed to call explicit constructors or
3076 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003077 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003078 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00003079
Sebastian Redl10f04a62011-12-22 14:44:04 +00003080 // - Otherwise, if T is a class type, constructors are considered. The
3081 // applicable constructors are enumerated, and the best one is chosen
3082 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00003083 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003084 // The container holding the constructors can under certain conditions
3085 // be changed while iterating (e.g. because of deserialization).
3086 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003087 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00003088
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003089 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003090 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003091 bool AsInitializerList = false;
3092
3093 // C++11 [over.match.list]p1:
3094 // When objects of non-aggregate type T are list-initialized, overload
3095 // resolution selects the constructor in two phases:
3096 // - Initially, the candidate functions are the initializer-list
3097 // constructors of the class T and the argument list consists of the
3098 // initializer list as a single argument.
3099 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003100 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003101 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003102
3103 // If the initializer list has no elements and T has a default constructor,
3104 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003105 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003106 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003107 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003108 CopyInitialization, AllowExplicit,
3109 /*OnlyListConstructor=*/true,
3110 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003111
3112 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003113 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003114 }
3115
3116 // C++11 [over.match.list]p1:
3117 // - If no viable initializer-list constructor is found, overload resolution
3118 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003119 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003120 // elements of the initializer list.
3121 if (Result == OR_No_Viable_Function) {
3122 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003123 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003124 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003125 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003126 /*OnlyListConstructors=*/false,
3127 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003128 }
3129 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003130 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003131 InitializationSequence::FK_ListConstructorOverloadFailed :
3132 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003133 Result);
3134 return;
3135 }
3136
Richard Smithf4bb8d02012-07-05 08:39:21 +00003137 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003138 // If a program calls for the default initialization of an object
3139 // of a const-qualified type T, T shall be a class type with a
3140 // user-provided default constructor.
3141 if (Kind.getKind() == InitializationKind::IK_Default &&
3142 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003143 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003144 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3145 return;
3146 }
3147
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003148 // C++11 [over.match.list]p1:
3149 // In copy-list-initialization, if an explicit constructor is chosen, the
3150 // initializer is ill-formed.
3151 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3152 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3153 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3154 return;
3155 }
3156
Sebastian Redl10f04a62011-12-22 14:44:04 +00003157 // Add the constructor initialization step. Any cv-qualification conversion is
3158 // subsumed by the initialization.
3159 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003160 Sequence.AddConstructorInitializationStep(CtorDecl,
3161 Best->FoundDecl.getAccess(),
3162 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003163 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003164}
3165
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003166static bool
3167ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3168 Expr *Initializer,
3169 QualType &SourceType,
3170 QualType &UnqualifiedSourceType,
3171 QualType UnqualifiedTargetType,
3172 InitializationSequence &Sequence) {
3173 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3174 S.Context.OverloadTy) {
3175 DeclAccessPair Found;
3176 bool HadMultipleCandidates = false;
3177 if (FunctionDecl *Fn
3178 = S.ResolveAddressOfOverloadedFunction(Initializer,
3179 UnqualifiedTargetType,
3180 false, Found,
3181 &HadMultipleCandidates)) {
3182 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3183 HadMultipleCandidates);
3184 SourceType = Fn->getType();
3185 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3186 } else if (!UnqualifiedTargetType->isRecordType()) {
3187 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3188 return true;
3189 }
3190 }
3191 return false;
3192}
3193
3194static void TryReferenceInitializationCore(Sema &S,
3195 const InitializedEntity &Entity,
3196 const InitializationKind &Kind,
3197 Expr *Initializer,
3198 QualType cv1T1, QualType T1,
3199 Qualifiers T1Quals,
3200 QualType cv2T2, QualType T2,
3201 Qualifiers T2Quals,
3202 InitializationSequence &Sequence);
3203
Richard Smithf4bb8d02012-07-05 08:39:21 +00003204static void TryValueInitialization(Sema &S,
3205 const InitializedEntity &Entity,
3206 const InitializationKind &Kind,
3207 InitializationSequence &Sequence,
3208 InitListExpr *InitList = 0);
3209
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003210/// \brief Attempt list initialization of a reference.
3211static void TryReferenceListInitialization(Sema &S,
3212 const InitializedEntity &Entity,
3213 const InitializationKind &Kind,
3214 InitListExpr *InitList,
Richard Smithb6e38082013-06-08 00:02:08 +00003215 InitializationSequence &Sequence) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003216 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003217 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003218 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3219 return;
3220 }
3221
3222 QualType DestType = Entity.getType();
3223 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3224 Qualifiers T1Quals;
3225 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3226
3227 // Reference initialization via an initializer list works thus:
3228 // If the initializer list consists of a single element that is
3229 // reference-related to the referenced type, bind directly to that element
3230 // (possibly creating temporaries).
3231 // Otherwise, initialize a temporary with the initializer list and
3232 // bind to that.
3233 if (InitList->getNumInits() == 1) {
3234 Expr *Initializer = InitList->getInit(0);
3235 QualType cv2T2 = Initializer->getType();
3236 Qualifiers T2Quals;
3237 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3238
3239 // If this fails, creating a temporary wouldn't work either.
3240 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3241 T1, Sequence))
3242 return;
3243
3244 SourceLocation DeclLoc = Initializer->getLocStart();
3245 bool dummy1, dummy2, dummy3;
3246 Sema::ReferenceCompareResult RefRelationship
3247 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3248 dummy2, dummy3);
3249 if (RefRelationship >= Sema::Ref_Related) {
3250 // Try to bind the reference here.
3251 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3252 T1Quals, cv2T2, T2, T2Quals, Sequence);
3253 if (Sequence)
3254 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3255 return;
3256 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003257
3258 // Update the initializer if we've resolved an overloaded function.
3259 if (Sequence.step_begin() != Sequence.step_end())
3260 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003261 }
3262
3263 // Not reference-related. Create a temporary and bind to that.
3264 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3265
3266 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3267 if (Sequence) {
3268 if (DestType->isRValueReferenceType() ||
3269 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3270 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3271 else
3272 Sequence.SetFailed(
3273 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3274 }
3275}
3276
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003277/// \brief Attempt list initialization (C++0x [dcl.init.list])
3278static void TryListInitialization(Sema &S,
3279 const InitializedEntity &Entity,
3280 const InitializationKind &Kind,
3281 InitListExpr *InitList,
3282 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003283 QualType DestType = Entity.getType();
3284
Sebastian Redl14b0c192011-09-24 17:48:00 +00003285 // C++ doesn't allow scalar initialization with more than one argument.
3286 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003287 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003288 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3289 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3290 return;
3291 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003292 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003293 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003294 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003295 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003296 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003297 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003298 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003299 return;
3300 }
3301
Richard Smithf4bb8d02012-07-05 08:39:21 +00003302 // C++11 [dcl.init.list]p3:
3303 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003304 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003305 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003306 // - Otherwise, if the initializer list has no elements and T is a
3307 // class type with a default constructor, the object is
3308 // value-initialized.
3309 if (InitList->getNumInits() == 0) {
3310 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003311 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003312 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3313 return;
3314 }
3315 }
3316
3317 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3318 // an initializer_list object constructed [...]
3319 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3320 return;
3321
3322 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003323 Expr *InitListAsExpr = InitList;
3324 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003325 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003326 } else
3327 Sequence.SetFailed(
3328 InitializationSequence::FK_InitListBadDestinationType);
3329 return;
3330 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003331 }
3332
Sebastian Redl14b0c192011-09-24 17:48:00 +00003333 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00003334 DestType, /*VerifyOnly=*/true);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003335 if (CheckInitList.HadError()) {
3336 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3337 return;
3338 }
3339
3340 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003341 Sequence.AddListInitializationStep(DestType);
3342}
Douglas Gregor20093b42009-12-09 23:02:17 +00003343
3344/// \brief Try a reference initialization that involves calling a conversion
3345/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003346static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3347 const InitializedEntity &Entity,
3348 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003349 Expr *Initializer,
3350 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003351 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003352 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003353 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3354 QualType T1 = cv1T1.getUnqualifiedType();
3355 QualType cv2T2 = Initializer->getType();
3356 QualType T2 = cv2T2.getUnqualifiedType();
3357
3358 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003359 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003360 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003361 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003362 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003363 ObjCConversion,
3364 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003365 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003366 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003367 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003368 (void)ObjCLifetimeConversion;
3369
Douglas Gregor20093b42009-12-09 23:02:17 +00003370 // Build the candidate set directly in the initialization sequence
3371 // structure, so that it will persist if we fail.
3372 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3373 CandidateSet.clear();
3374
3375 // Determine whether we are allowed to call explicit constructors or
3376 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003377 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003378 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3379
Douglas Gregor20093b42009-12-09 23:02:17 +00003380 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003381 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3382 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 // The type we're converting to is a class type. Enumerate its constructors
3384 // to see if there is a suitable conversion.
3385 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003386
David Blaikie3bc93e32012-12-19 00:45:41 +00003387 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003388 // The container holding the constructors can under certain conditions
3389 // be changed while iterating (e.g. because of deserialization).
3390 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003391 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00003392 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003393 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3394 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003395 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3396
Douglas Gregor20093b42009-12-09 23:02:17 +00003397 // Find the constructor (which may be a template).
3398 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003399 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003400 if (ConstructorTmpl)
3401 Constructor = cast<CXXConstructorDecl>(
3402 ConstructorTmpl->getTemplatedDecl());
3403 else
John McCall9aa472c2010-03-19 07:35:19 +00003404 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003405
Douglas Gregor20093b42009-12-09 23:02:17 +00003406 if (!Constructor->isInvalidDecl() &&
3407 Constructor->isConvertingConstructor(AllowExplicit)) {
3408 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003409 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003410 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003411 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003412 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003413 else
John McCall9aa472c2010-03-19 07:35:19 +00003414 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003415 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003416 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003417 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003418 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003419 }
John McCall572fc622010-08-17 07:23:57 +00003420 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3421 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003422
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003423 const RecordType *T2RecordType = 0;
3424 if ((T2RecordType = T2->getAs<RecordType>()) &&
3425 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003426 // The type we're converting from is a class type, enumerate its conversion
3427 // functions.
3428 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3429
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003430 std::pair<CXXRecordDecl::conversion_iterator,
3431 CXXRecordDecl::conversion_iterator>
3432 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3433 for (CXXRecordDecl::conversion_iterator
3434 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003435 NamedDecl *D = *I;
3436 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3437 if (isa<UsingShadowDecl>(D))
3438 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003439
Douglas Gregor20093b42009-12-09 23:02:17 +00003440 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3441 CXXConversionDecl *Conv;
3442 if (ConvTemplate)
3443 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3444 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003445 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003446
Douglas Gregor20093b42009-12-09 23:02:17 +00003447 // If the conversion function doesn't return a reference type,
3448 // it can't be considered for this conversion unless we're allowed to
3449 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003450 // FIXME: Do we need to make sure that we only consider conversion
3451 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003452 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003453 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003454 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3455 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003456 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003457 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003458 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003459 else
John McCall9aa472c2010-03-19 07:35:19 +00003460 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003461 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003462 }
3463 }
3464 }
John McCall572fc622010-08-17 07:23:57 +00003465 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3466 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003467
Douglas Gregor20093b42009-12-09 23:02:17 +00003468 SourceLocation DeclLoc = Initializer->getLocStart();
3469
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003470 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003471 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003472 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003473 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003474 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003475
Douglas Gregor20093b42009-12-09 23:02:17 +00003476 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003477 // This is the overload that will be used for this initialization step if we
3478 // use this initialization. Mark it as referenced.
3479 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003480
Eli Friedman03981012009-12-11 02:42:07 +00003481 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003482 if (isa<CXXConversionDecl>(Function))
3483 T2 = Function->getResultType();
3484 else
3485 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003486
3487 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003488 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003489 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003490 T2.getNonLValueExprType(S.Context),
3491 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003492
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003494 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003495 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003496 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003497 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003498 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003499 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003500
Douglas Gregor20093b42009-12-09 23:02:17 +00003501 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003502 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003503 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003504 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003505 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003506 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003507 NewDerivedToBase, NewObjCConversion,
3508 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003509 if (NewRefRelationship == Sema::Ref_Incompatible) {
3510 // If the type we've converted to is not reference-related to the
3511 // type we're looking for, then there is another conversion step
3512 // we need to perform to produce a temporary of the right type
3513 // that we'll be binding to.
3514 ImplicitConversionSequence ICS;
3515 ICS.setStandard();
3516 ICS.Standard = Best->FinalConversion;
3517 T2 = ICS.Standard.getToType(2);
3518 Sequence.AddConversionSequenceStep(ICS, T2);
3519 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003520 Sequence.AddDerivedToBaseCastStep(
3521 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003522 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003523 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003524 else if (NewObjCConversion)
3525 Sequence.AddObjCObjectConversionStep(
3526 S.Context.getQualifiedType(T1,
3527 T2.getNonReferenceType().getQualifiers()));
3528
Douglas Gregor20093b42009-12-09 23:02:17 +00003529 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003530 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531
Douglas Gregor20093b42009-12-09 23:02:17 +00003532 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3533 return OR_Success;
3534}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003535
Richard Smith83da2e72011-10-19 16:55:56 +00003536static void CheckCXX98CompatAccessibleCopy(Sema &S,
3537 const InitializedEntity &Entity,
3538 Expr *CurInitExpr);
3539
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003540/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3541static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003542 const InitializedEntity &Entity,
3543 const InitializationKind &Kind,
3544 Expr *Initializer,
3545 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003546 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003547 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003548 Qualifiers T1Quals;
3549 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003550 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003551 Qualifiers T2Quals;
3552 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003553
Douglas Gregor20093b42009-12-09 23:02:17 +00003554 // If the initializer is the address of an overloaded function, try
3555 // to resolve the overloaded function. If all goes well, T2 is the
3556 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003557 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3558 T1, Sequence))
3559 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003560
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003561 // Delegate everything else to a subfunction.
3562 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3563 T1Quals, cv2T2, T2, T2Quals, Sequence);
3564}
3565
Jordan Rose1fd1e282013-04-11 00:58:58 +00003566/// Converts the target of reference initialization so that it has the
3567/// appropriate qualifiers and value kind.
3568///
3569/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3570/// \code
3571/// int x;
3572/// const int &r = x;
3573/// \endcode
3574///
3575/// In this case the reference is binding to a bitfield lvalue, which isn't
3576/// valid. Perform a load to create a lifetime-extended temporary instead.
3577/// \code
3578/// const int &r = someStruct.bitfield;
3579/// \endcode
3580static ExprValueKind
3581convertQualifiersAndValueKindIfNecessary(Sema &S,
3582 InitializationSequence &Sequence,
3583 Expr *Initializer,
3584 QualType cv1T1,
3585 Qualifiers T1Quals,
3586 Qualifiers T2Quals,
3587 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003588 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003589 Initializer->refersToVectorElement();
3590
3591 if (IsNonAddressableType) {
3592 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3593 // lvalue reference to a non-volatile const type, or the reference shall be
3594 // an rvalue reference.
3595 //
3596 // If not, we can't make a temporary and bind to that. Give up and allow the
3597 // error to be diagnosed later.
3598 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3599 assert(Initializer->isGLValue());
3600 return Initializer->getValueKind();
3601 }
3602
3603 // Force a load so we can materialize a temporary.
3604 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3605 return VK_RValue;
3606 }
3607
3608 if (T1Quals != T2Quals) {
3609 Sequence.AddQualificationConversionStep(cv1T1,
3610 Initializer->getValueKind());
3611 }
3612
3613 return Initializer->getValueKind();
3614}
3615
3616
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003617/// \brief Reference initialization without resolving overloaded functions.
3618static void TryReferenceInitializationCore(Sema &S,
3619 const InitializedEntity &Entity,
3620 const InitializationKind &Kind,
3621 Expr *Initializer,
3622 QualType cv1T1, QualType T1,
3623 Qualifiers T1Quals,
3624 QualType cv2T2, QualType T2,
3625 Qualifiers T2Quals,
3626 InitializationSequence &Sequence) {
3627 QualType DestType = Entity.getType();
3628 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003629 // Compute some basic properties of the types and the initializer.
3630 bool isLValueRef = DestType->isLValueReferenceType();
3631 bool isRValueRef = !isLValueRef;
3632 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003633 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003634 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003635 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003636 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003637 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003638 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003639
Douglas Gregor20093b42009-12-09 23:02:17 +00003640 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003641 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003642 // "cv2 T2" as follows:
3643 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003644 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003645 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003646 // Note the analogous bullet points for rvlaue refs to functions. Because
3647 // there are no function rvalues in C++, rvalue refs to functions are treated
3648 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003649 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003650 bool T1Function = T1->isFunctionType();
3651 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003652 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003653 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003654 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003655 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003656 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003657 // reference-compatible with "cv2 T2," or
3658 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003659 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003660 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003661 // can occur. However, we do pay attention to whether it is a bit-field
3662 // to decide whether we're actually binding to a temporary created from
3663 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003664 if (DerivedToBase)
3665 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003666 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003667 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003668 else if (ObjCConversion)
3669 Sequence.AddObjCObjectConversionStep(
3670 S.Context.getQualifiedType(T1, T2Quals));
3671
Jordan Rose1fd1e282013-04-11 00:58:58 +00003672 ExprValueKind ValueKind =
3673 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3674 cv1T1, T1Quals, T2Quals,
3675 isLValueRef);
3676 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003677 return;
3678 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003679
3680 // - has a class type (i.e., T2 is a class type), where T1 is not
3681 // reference-related to T2, and can be implicitly converted to an
3682 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3683 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003684 // applicable conversion functions (13.3.1.6) and choosing the best
3685 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003686 // If we have an rvalue ref to function type here, the rhs must be
3687 // an rvalue.
3688 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3689 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003690 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003691 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003692 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003693 Sequence);
3694 if (ConvOvlResult == OR_Success)
3695 return;
John McCall1d318332010-01-12 00:44:57 +00003696 if (ConvOvlResult != OR_No_Viable_Function) {
3697 Sequence.SetOverloadFailure(
3698 InitializationSequence::FK_ReferenceInitOverloadFailed,
3699 ConvOvlResult);
3700 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003701 }
3702 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003703
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003705 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003706 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003707 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003708 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3709 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3710 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003711 Sequence.SetOverloadFailure(
3712 InitializationSequence::FK_ReferenceInitOverloadFailed,
3713 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003714 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003715 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003716 ? (RefRelationship == Sema::Ref_Related
3717 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3718 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3719 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003720
Douglas Gregor20093b42009-12-09 23:02:17 +00003721 return;
3722 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003723
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003724 // - If the initializer expression
3725 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3726 // "cv1 T1" is reference-compatible with "cv2 T2"
3727 // Note: functions are handled below.
3728 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003729 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003730 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003731 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003732 (InitCategory.isXValue() ||
3733 (InitCategory.isPRValue() && T2->isRecordType()) ||
3734 (InitCategory.isPRValue() && T2->isArrayType()))) {
3735 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3736 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003737 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3738 // compiler the freedom to perform a copy here or bind to the
3739 // object, while C++0x requires that we bind directly to the
3740 // object. Hence, we always bind to the object without making an
3741 // extra copy. However, in C++03 requires that we check for the
3742 // presence of a suitable copy constructor:
3743 //
3744 // The constructor that would be used to make the copy shall
3745 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003746 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003747 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003748 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003749 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003751
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003752 if (DerivedToBase)
3753 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3754 ValueKind);
3755 else if (ObjCConversion)
3756 Sequence.AddObjCObjectConversionStep(
3757 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003758
Jordan Rose1fd1e282013-04-11 00:58:58 +00003759 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3760 Initializer, cv1T1,
3761 T1Quals, T2Quals,
3762 isLValueRef);
3763
3764 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003766 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003767
3768 // - has a class type (i.e., T2 is a class type), where T1 is not
3769 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003770 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3771 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003772 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003773 if (RefRelationship == Sema::Ref_Incompatible) {
3774 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3775 Kind, Initializer,
3776 /*AllowRValues=*/true,
3777 Sequence);
3778 if (ConvOvlResult)
3779 Sequence.SetOverloadFailure(
3780 InitializationSequence::FK_ReferenceInitOverloadFailed,
3781 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003782
Douglas Gregor20093b42009-12-09 23:02:17 +00003783 return;
3784 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785
Douglas Gregordefa32e2013-03-26 23:59:23 +00003786 if ((RefRelationship == Sema::Ref_Compatible ||
3787 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3788 isRValueRef && InitCategory.isLValue()) {
3789 Sequence.SetFailed(
3790 InitializationSequence::FK_RValueReferenceBindingToLValue);
3791 return;
3792 }
3793
Douglas Gregor20093b42009-12-09 23:02:17 +00003794 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3795 return;
3796 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003797
3798 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003799 // from the initializer expression using the rules for a non-reference
Richard Smith4e47ecb2013-06-13 00:57:57 +00003800 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003801 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003802
John McCall369371c2010-06-04 02:29:22 +00003803 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3804
Richard Smith4e47ecb2013-06-13 00:57:57 +00003805 // FIXME: Why do we use an implicit conversion here rather than trying
3806 // copy-initialization?
John McCallf85e1932011-06-15 23:02:42 +00003807 ImplicitConversionSequence ICS
3808 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith4e47ecb2013-06-13 00:57:57 +00003809 /*SuppressUserConversions=*/false,
3810 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003811 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003812 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3813 /*AllowObjCWritebackConversion=*/false);
3814
3815 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003816 // FIXME: Use the conversion function set stored in ICS to turn
3817 // this into an overloading ambiguity diagnostic. However, we need
3818 // to keep that set as an OverloadCandidateSet rather than as some
3819 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003820 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3821 Sequence.SetOverloadFailure(
3822 InitializationSequence::FK_ReferenceInitOverloadFailed,
3823 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003824 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3825 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003826 else
3827 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003828 return;
John McCallf85e1932011-06-15 23:02:42 +00003829 } else {
3830 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003831 }
3832
3833 // [...] If T1 is reference-related to T2, cv1 must be the
3834 // same cv-qualification as, or greater cv-qualification
3835 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003836 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3837 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003838 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003839 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003840 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3841 return;
3842 }
3843
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003845 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003847 InitCategory.isLValue()) {
3848 Sequence.SetFailed(
3849 InitializationSequence::FK_RValueReferenceBindingToLValue);
3850 return;
3851 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003852
Douglas Gregor20093b42009-12-09 23:02:17 +00003853 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3854 return;
3855}
3856
3857/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003858/// (C++ [dcl.init.string], C99 6.7.8).
3859static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003860 const InitializedEntity &Entity,
3861 const InitializationKind &Kind,
3862 Expr *Initializer,
3863 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003864 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003865}
3866
Douglas Gregor71d17402009-12-15 00:01:57 +00003867/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003869 const InitializedEntity &Entity,
3870 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003871 InitializationSequence &Sequence,
3872 InitListExpr *InitList) {
3873 assert((!InitList || InitList->getNumInits() == 0) &&
3874 "Shouldn't use value-init for non-empty init lists");
3875
Richard Smith1d0c9a82012-02-14 21:14:13 +00003876 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003877 //
3878 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003879 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003880
Douglas Gregor71d17402009-12-15 00:01:57 +00003881 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003882 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003883
Douglas Gregor71d17402009-12-15 00:01:57 +00003884 if (const RecordType *RT = T->getAs<RecordType>()) {
3885 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003886 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003887 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003888 // C++98:
3889 // -- if T is a class type (clause 9) with a user-declared constructor
3890 // (12.1), then the default constructor for T is called (and the
3891 // initialization is ill-formed if T has no accessible default
3892 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003893 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003894 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003895 } else {
3896 // C++11:
3897 // -- if T is a class type (clause 9) with either no default constructor
3898 // (12.1 [class.ctor]) or a default constructor that is user-provided
3899 // or deleted, then the object is default-initialized;
3900 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3901 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003902 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003903 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003904
Richard Smith1d0c9a82012-02-14 21:14:13 +00003905 // -- if T is a (possibly cv-qualified) non-union class type without a
3906 // user-provided or deleted default constructor, then the object is
3907 // zero-initialized and, if T has a non-trivial default constructor,
3908 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003909 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3910 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003911 if (NeedZeroInitialization)
3912 Sequence.AddZeroInitializationStep(Entity.getType());
3913
Richard Smithd5bc8672012-12-08 02:01:17 +00003914 // C++03:
3915 // -- if T is a non-union class type without a user-declared constructor,
3916 // then every non-static data member and base class component of T is
3917 // value-initialized;
3918 // [...] A program that calls for [...] value-initialization of an
3919 // entity of reference type is ill-formed.
3920 //
3921 // C++11 doesn't need this handling, because value-initialization does not
3922 // occur recursively there, and the implicit default constructor is
3923 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003924 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003925 ClassDecl->hasUninitializedReferenceMember()) {
3926 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3927 return;
3928 }
3929
Richard Smithf4bb8d02012-07-05 08:39:21 +00003930 // If this is list-value-initialization, pass the empty init list on when
3931 // building the constructor call. This affects the semantics of a few
3932 // things (such as whether an explicit default constructor can be called).
3933 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003934 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003935 bool InitListSyntax = InitList;
3936
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003937 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3938 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003939 }
3940 }
3941
Douglas Gregord6542d82009-12-22 15:35:07 +00003942 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003943}
3944
Douglas Gregor99a2e602009-12-16 01:38:02 +00003945/// \brief Attempt default initialization (C++ [dcl.init]p6).
3946static void TryDefaultInitialization(Sema &S,
3947 const InitializedEntity &Entity,
3948 const InitializationKind &Kind,
3949 InitializationSequence &Sequence) {
3950 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003951
Douglas Gregor99a2e602009-12-16 01:38:02 +00003952 // C++ [dcl.init]p6:
3953 // To default-initialize an object of type T means:
3954 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003955 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3956
Douglas Gregor99a2e602009-12-16 01:38:02 +00003957 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3958 // constructor for T is called (and the initialization is ill-formed if
3959 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003960 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003961 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003962 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003963 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003964
Douglas Gregor99a2e602009-12-16 01:38:02 +00003965 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003966
Douglas Gregor99a2e602009-12-16 01:38:02 +00003967 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003968 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003969 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003970 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003971 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003972 return;
3973 }
3974
3975 // If the destination type has a lifetime property, zero-initialize it.
3976 if (DestType.getQualifiers().hasObjCLifetime()) {
3977 Sequence.AddZeroInitializationStep(Entity.getType());
3978 return;
3979 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003980}
3981
Douglas Gregor20093b42009-12-09 23:02:17 +00003982/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3983/// which enumerates all conversion functions and performs overload resolution
3984/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003985static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003986 const InitializedEntity &Entity,
3987 const InitializationKind &Kind,
3988 Expr *Initializer,
3989 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003990 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003991 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3992 QualType SourceType = Initializer->getType();
3993 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3994 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003995
Douglas Gregor4a520a22009-12-14 17:27:33 +00003996 // Build the candidate set directly in the initialization sequence
3997 // structure, so that it will persist if we fail.
3998 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3999 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004000
Douglas Gregor4a520a22009-12-14 17:27:33 +00004001 // Determine whether we are allowed to call explicit constructors or
4002 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00004003 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004004
Douglas Gregor4a520a22009-12-14 17:27:33 +00004005 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4006 // The type we're converting to is a class type. Enumerate its constructors
4007 // to see if there is a suitable conversion.
4008 CXXRecordDecl *DestRecordDecl
4009 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004010
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004011 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004012 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004013 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004014 // The container holding the constructors can under certain conditions
4015 // be changed while iterating. To be safe we copy the lookup results
4016 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004017 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004018 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004019 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004020 Con != ConEnd; ++Con) {
4021 NamedDecl *D = *Con;
4022 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004023
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004024 // Find the constructor (which may be a template).
4025 CXXConstructorDecl *Constructor = 0;
4026 FunctionTemplateDecl *ConstructorTmpl
4027 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004028 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004029 Constructor = cast<CXXConstructorDecl>(
4030 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00004031 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004032 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004033
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004034 if (!Constructor->isInvalidDecl() &&
4035 Constructor->isConvertingConstructor(AllowExplicit)) {
4036 if (ConstructorTmpl)
4037 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4038 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004039 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004040 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004041 else
4042 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004043 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004044 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004045 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004046 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004047 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004048 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004049
4050 SourceLocation DeclLoc = Initializer->getLocStart();
4051
Douglas Gregor4a520a22009-12-14 17:27:33 +00004052 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4053 // The type we're converting from is a class type, enumerate its conversion
4054 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004055
Eli Friedman33c2da92009-12-20 22:12:03 +00004056 // We can only enumerate the conversion functions for a complete type; if
4057 // the type isn't complete, simply skip this step.
4058 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4059 CXXRecordDecl *SourceRecordDecl
4060 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004061
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004062 std::pair<CXXRecordDecl::conversion_iterator,
4063 CXXRecordDecl::conversion_iterator>
4064 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4065 for (CXXRecordDecl::conversion_iterator
4066 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00004067 NamedDecl *D = *I;
4068 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4069 if (isa<UsingShadowDecl>(D))
4070 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004071
Eli Friedman33c2da92009-12-20 22:12:03 +00004072 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4073 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00004074 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00004075 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00004076 else
John McCall32daa422010-03-31 01:36:47 +00004077 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004078
Eli Friedman33c2da92009-12-20 22:12:03 +00004079 if (AllowExplicit || !Conv->isExplicit()) {
4080 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00004081 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00004082 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00004083 CandidateSet);
4084 else
John McCall9aa472c2010-03-19 07:35:19 +00004085 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00004086 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00004087 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004088 }
4089 }
4090 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004091
4092 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004093 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004094 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004095 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004096 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004097 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004098 Result);
4099 return;
4100 }
John McCall1d318332010-01-12 00:44:57 +00004101
Douglas Gregor4a520a22009-12-14 17:27:33 +00004102 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004103 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004104 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004105
Douglas Gregor4a520a22009-12-14 17:27:33 +00004106 if (isa<CXXConstructorDecl>(Function)) {
4107 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004108 // subsumed by the initialization. Per DR5, the created temporary is of the
4109 // cv-unqualified type of the destination.
4110 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4111 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004112 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004113 return;
4114 }
4115
4116 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004117 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004118 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004119 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004120 // the resulting temporary object (possible to create an object of
4121 // a base class type). That copy is not a separate conversion, so
4122 // we just make a note of the actual destination type (possibly a
4123 // base class of the type returned by the conversion function) and
4124 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004125 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4126 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004127 return;
4128 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004129
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004130 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4131 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004132
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004133 // If the conversion following the call to the conversion function
4134 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004135 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4136 Best->FinalConversion.Third) {
4137 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004138 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004139 ICS.Standard = Best->FinalConversion;
4140 Sequence.AddConversionSequenceStep(ICS, DestType);
4141 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004142}
4143
Richard Smith87c29322013-06-20 02:18:31 +00004144/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4145/// a function with a pointer return type contains a 'return false;' statement.
4146/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4147/// code using that header.
4148///
4149/// Work around this by treating 'return false;' as zero-initializing the result
4150/// if it's used in a pointer-returning function in a system header.
4151static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4152 const InitializedEntity &Entity,
4153 const Expr *Init) {
4154 return S.getLangOpts().CPlusPlus11 &&
4155 Entity.getKind() == InitializedEntity::EK_Result &&
4156 Entity.getType()->isPointerType() &&
4157 isa<CXXBoolLiteralExpr>(Init) &&
4158 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4159 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4160}
4161
John McCallf85e1932011-06-15 23:02:42 +00004162/// The non-zero enum values here are indexes into diagnostic alternatives.
4163enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4164
4165/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004166static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004167 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004168 // Skip parens.
4169 e = e->IgnoreParens();
4170
4171 // Skip address-of nodes.
4172 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4173 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004174 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4175 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004176
4177 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004178 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4179 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004180 case CK_Dependent:
4181 case CK_BitCast:
4182 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004183 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004184 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004185
4186 case CK_ArrayToPointerDecay:
4187 return IIK_nonscalar;
4188
4189 case CK_NullToPointer:
4190 return IIK_okay;
4191
4192 default:
4193 break;
4194 }
4195
4196 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004197 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004198 // set isWeakAccess to true, to mean that there will be an implicit
4199 // load which requires a cleanup.
4200 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4201 isWeakAccess = true;
4202
John McCallc03fa492011-06-27 23:59:58 +00004203 if (!isAddressOf) return IIK_nonlocal;
4204
John McCallf4b88a42012-03-10 09:33:50 +00004205 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4206 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004207
4208 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004209
4210 // If we have a conditional operator, check both sides.
4211 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004212 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4213 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004214 return iik;
4215
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004216 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004217
4218 // These are never scalar.
4219 } else if (isa<ArraySubscriptExpr>(e)) {
4220 return IIK_nonscalar;
4221
4222 // Otherwise, it needs to be a null pointer constant.
4223 } else {
4224 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4225 ? IIK_okay : IIK_nonlocal);
4226 }
4227
4228 return IIK_nonlocal;
4229}
4230
4231/// Check whether the given expression is a valid operand for an
4232/// indirect copy/restore.
4233static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4234 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004235 bool isWeakAccess = false;
4236 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4237 // If isWeakAccess to true, there will be an implicit
4238 // load which requires a cleanup.
4239 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4240 S.ExprNeedsCleanups = true;
4241
John McCallf85e1932011-06-15 23:02:42 +00004242 if (iik == IIK_okay) return;
4243
4244 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4245 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4246 << src->getSourceRange();
4247}
4248
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004249/// \brief Determine whether we have compatible array types for the
4250/// purposes of GNU by-copy array initialization.
4251static bool hasCompatibleArrayTypes(ASTContext &Context,
4252 const ArrayType *Dest,
4253 const ArrayType *Source) {
4254 // If the source and destination array types are equivalent, we're
4255 // done.
4256 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4257 return true;
4258
4259 // Make sure that the element types are the same.
4260 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4261 return false;
4262
4263 // The only mismatch we allow is when the destination is an
4264 // incomplete array type and the source is a constant array type.
4265 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4266}
4267
John McCallf85e1932011-06-15 23:02:42 +00004268static bool tryObjCWritebackConversion(Sema &S,
4269 InitializationSequence &Sequence,
4270 const InitializedEntity &Entity,
4271 Expr *Initializer) {
4272 bool ArrayDecay = false;
4273 QualType ArgType = Initializer->getType();
4274 QualType ArgPointee;
4275 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4276 ArrayDecay = true;
4277 ArgPointee = ArgArrayType->getElementType();
4278 ArgType = S.Context.getPointerType(ArgPointee);
4279 }
4280
4281 // Handle write-back conversion.
4282 QualType ConvertedArgType;
4283 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4284 ConvertedArgType))
4285 return false;
4286
4287 // We should copy unless we're passing to an argument explicitly
4288 // marked 'out'.
4289 bool ShouldCopy = true;
4290 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4291 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4292
4293 // Do we need an lvalue conversion?
4294 if (ArrayDecay || Initializer->isGLValue()) {
4295 ImplicitConversionSequence ICS;
4296 ICS.setStandard();
4297 ICS.Standard.setAsIdentityConversion();
4298
4299 QualType ResultType;
4300 if (ArrayDecay) {
4301 ICS.Standard.First = ICK_Array_To_Pointer;
4302 ResultType = S.Context.getPointerType(ArgPointee);
4303 } else {
4304 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4305 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4306 }
4307
4308 Sequence.AddConversionSequenceStep(ICS, ResultType);
4309 }
4310
4311 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4312 return true;
4313}
4314
Guy Benyei21f18c42013-02-07 10:55:47 +00004315static bool TryOCLSamplerInitialization(Sema &S,
4316 InitializationSequence &Sequence,
4317 QualType DestType,
4318 Expr *Initializer) {
4319 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4320 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4321 return false;
4322
4323 Sequence.AddOCLSamplerInitStep(DestType);
4324 return true;
4325}
4326
Guy Benyeie6b9d802013-01-20 12:31:11 +00004327//
4328// OpenCL 1.2 spec, s6.12.10
4329//
4330// The event argument can also be used to associate the
4331// async_work_group_copy with a previous async copy allowing
4332// an event to be shared by multiple async copies; otherwise
4333// event should be zero.
4334//
4335static bool TryOCLZeroEventInitialization(Sema &S,
4336 InitializationSequence &Sequence,
4337 QualType DestType,
4338 Expr *Initializer) {
4339 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4340 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4341 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4342 return false;
4343
4344 Sequence.AddOCLZeroEventStep(DestType);
4345 return true;
4346}
4347
Douglas Gregor20093b42009-12-09 23:02:17 +00004348InitializationSequence::InitializationSequence(Sema &S,
4349 const InitializedEntity &Entity,
4350 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004351 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004352 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004353 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004354
John McCall76da55d2013-04-16 07:28:30 +00004355 // Eliminate non-overload placeholder types in the arguments. We
4356 // need to do this before checking whether types are dependent
4357 // because lowering a pseudo-object expression might well give us
4358 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004359 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004360 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4361 // FIXME: should we be doing this here?
4362 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4363 if (result.isInvalid()) {
4364 SetFailed(FK_PlaceholderType);
4365 return;
4366 }
4367 Args[I] = result.take();
4368 }
4369
Douglas Gregor20093b42009-12-09 23:02:17 +00004370 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004371 // The semantics of initializers are as follows. The destination type is
4372 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004373 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004374 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004375 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004376 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004377
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004378 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004379 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004380 SequenceKind = DependentSequence;
4381 return;
4382 }
4383
Sebastian Redl7491c492011-06-05 13:59:11 +00004384 // Almost everything is a normal sequence.
4385 setSequenceKind(NormalSequence);
4386
Douglas Gregor20093b42009-12-09 23:02:17 +00004387 QualType SourceType;
4388 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004389 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004390 Initializer = Args[0];
4391 if (!isa<InitListExpr>(Initializer))
4392 SourceType = Initializer->getType();
4393 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004394
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004395 // - If the initializer is a (non-parenthesized) braced-init-list, the
4396 // object is list-initialized (8.5.4).
4397 if (Kind.getKind() != InitializationKind::IK_Direct) {
4398 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4399 TryListInitialization(S, Entity, Kind, InitList, *this);
4400 return;
4401 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004402 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004403
Douglas Gregor20093b42009-12-09 23:02:17 +00004404 // - If the destination type is a reference type, see 8.5.3.
4405 if (DestType->isReferenceType()) {
4406 // C++0x [dcl.init.ref]p1:
4407 // A variable declared to be a T& or T&&, that is, "reference to type T"
4408 // (8.3.2), shall be initialized by an object, or function, of type T or
4409 // by an object that can be converted into a T.
4410 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004411 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004412 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004413 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004414 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004415 return;
4416 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004417
Douglas Gregor20093b42009-12-09 23:02:17 +00004418 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004419 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004420 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004421 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004422 return;
4423 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004424
Douglas Gregor99a2e602009-12-16 01:38:02 +00004425 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004426 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004427 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004428 return;
4429 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004430
John McCallce6c9b72011-02-21 07:22:22 +00004431 // - If the destination type is an array of characters, an array of
4432 // char16_t, an array of char32_t, or an array of wchar_t, and the
4433 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004435 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004436 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004437 if (Initializer && isa<VariableArrayType>(DestAT)) {
4438 SetFailed(FK_VariableLengthArrayHasInitializer);
4439 return;
4440 }
4441
Hans Wennborg0ff50742013-05-15 11:03:04 +00004442 if (Initializer) {
4443 switch (IsStringInit(Initializer, DestAT, Context)) {
4444 case SIF_None:
4445 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4446 return;
4447 case SIF_NarrowStringIntoWideChar:
4448 SetFailed(FK_NarrowStringIntoWideCharArray);
4449 return;
4450 case SIF_WideStringIntoChar:
4451 SetFailed(FK_WideStringIntoCharArray);
4452 return;
4453 case SIF_IncompatWideStringIntoWideChar:
4454 SetFailed(FK_IncompatWideStringIntoWideChar);
4455 return;
4456 case SIF_Other:
4457 break;
4458 }
John McCallce6c9b72011-02-21 07:22:22 +00004459 }
4460
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004461 // Note: as an GNU C extension, we allow initialization of an
4462 // array from a compound literal that creates an array of the same
4463 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004464 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004465 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4466 Initializer->getType()->isArrayType()) {
4467 const ArrayType *SourceAT
4468 = Context.getAsArrayType(Initializer->getType());
4469 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004470 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004471 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004472 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004473 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004474 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004475 }
Richard Smith0f163e92012-02-15 22:38:09 +00004476 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004477 // Note: as a GNU C++ extension, we allow list-initialization of a
4478 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004479 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004480 Entity.getKind() == InitializedEntity::EK_Member &&
4481 Initializer && isa<InitListExpr>(Initializer)) {
4482 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4483 *this);
4484 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004485 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004486 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004487 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4488 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004489 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004490 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004491
Douglas Gregor20093b42009-12-09 23:02:17 +00004492 return;
4493 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004494
John McCallf85e1932011-06-15 23:02:42 +00004495 // Determine whether we should consider writeback conversions for
4496 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004497 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004498 Entity.isParameterKind();
John McCallf85e1932011-06-15 23:02:42 +00004499
4500 // We're at the end of the line for C: it's either a write-back conversion
4501 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004502 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004503 // If allowed, check whether this is an Objective-C writeback conversion.
4504 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004505 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004506 return;
4507 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004508
4509 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4510 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004511
4512 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4513 return;
4514
John McCallf85e1932011-06-15 23:02:42 +00004515 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004516 AddCAssignmentStep(DestType);
4517 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004518 return;
4519 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004520
David Blaikie4e4d0842012-03-11 07:00:24 +00004521 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004522
Douglas Gregor20093b42009-12-09 23:02:17 +00004523 // - If the destination type is a (possibly cv-qualified) class type:
4524 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004525 // - If the initialization is direct-initialization, or if it is
4526 // copy-initialization where the cv-unqualified version of the
4527 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004528 // class of the destination, constructors are considered. [...]
4529 if (Kind.getKind() == InitializationKind::IK_Direct ||
4530 (Kind.getKind() == InitializationKind::IK_Copy &&
4531 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4532 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004533 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004534 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004535 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004536 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004537 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004538 // used) to a derived class thereof are enumerated as described in
4539 // 13.3.1.4, and the best one is chosen through overload resolution
4540 // (13.3).
4541 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004542 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004543 return;
4544 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004545
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004546 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004547 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004548 return;
4549 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004550 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004551
4552 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004553 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004554 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004555 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4556 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004557 return;
4558 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004559
Douglas Gregor20093b42009-12-09 23:02:17 +00004560 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004561 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004562 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004563 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004564 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004565
4566 ImplicitConversionSequence ICS
4567 = S.TryImplicitConversion(Initializer, Entity.getType(),
4568 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004569 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004570 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004571 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4572 allowObjCWritebackConversion);
4573
4574 if (ICS.isStandard() &&
4575 ICS.Standard.Second == ICK_Writeback_Conversion) {
4576 // Objective-C ARC writeback conversion.
4577
4578 // We should copy unless we're passing to an argument explicitly
4579 // marked 'out'.
4580 bool ShouldCopy = true;
4581 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4582 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4583
4584 // If there was an lvalue adjustment, add it as a separate conversion.
4585 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4586 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4587 ImplicitConversionSequence LvalueICS;
4588 LvalueICS.setStandard();
4589 LvalueICS.Standard.setAsIdentityConversion();
4590 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4591 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004592 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004593 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004594
4595 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004596 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004597 DeclAccessPair dap;
Richard Smith87c29322013-06-20 02:18:31 +00004598 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4599 AddZeroInitializationStep(Entity.getType());
4600 } else if (Initializer->getType() == Context.OverloadTy &&
4601 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4602 false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004603 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004604 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004605 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004606 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004607 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004608
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004609 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004610 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004611}
4612
4613InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004614 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004615 StepEnd = Steps.end();
4616 Step != StepEnd; ++Step)
4617 Step->Destroy();
4618}
4619
4620//===----------------------------------------------------------------------===//
4621// Perform initialization
4622//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004623static Sema::AssignmentAction
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004624getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004625 switch(Entity.getKind()) {
4626 case InitializedEntity::EK_Variable:
4627 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004628 case InitializedEntity::EK_Exception:
4629 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004630 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004631 return Sema::AA_Initializing;
4632
4633 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004635 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4636 return Sema::AA_Sending;
4637
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004638 return Sema::AA_Passing;
4639
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004640 case InitializedEntity::EK_Parameter_CF_Audited:
4641 if (Entity.getDecl() &&
4642 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4643 return Sema::AA_Sending;
4644
4645 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4646
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004647 case InitializedEntity::EK_Result:
4648 return Sema::AA_Returning;
4649
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004650 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf5200d62013-07-11 19:13:34 +00004651 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004652 // FIXME: Can we tell apart casting vs. converting?
4653 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004654
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004655 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004656 case InitializedEntity::EK_ArrayElement:
4657 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004658 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004659 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004660 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004661 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004662 return Sema::AA_Initializing;
4663 }
4664
David Blaikie7530c032012-01-17 06:56:22 +00004665 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004666}
4667
Richard Smith774d8b42013-01-08 00:08:23 +00004668/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004669/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004670static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004671 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004672 case InitializedEntity::EK_ArrayElement:
4673 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004674 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004675 case InitializedEntity::EK_New:
4676 case InitializedEntity::EK_Variable:
4677 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004678 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004679 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004680 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004681 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004682 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004683 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004684 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004685 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004686
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004687 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004688 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004689 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004690 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004691 return true;
4692 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004693
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004694 llvm_unreachable("missed an InitializedEntity kind?");
4695}
4696
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004697/// \brief Whether the given entity, when initialized with an object
4698/// created for that initialization, requires destruction.
4699static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4700 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004701 case InitializedEntity::EK_Result:
4702 case InitializedEntity::EK_New:
4703 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004704 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004705 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004706 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004707 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004708 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004709 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004710
Richard Smith774d8b42013-01-08 00:08:23 +00004711 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004712 case InitializedEntity::EK_Variable:
4713 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004714 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004715 case InitializedEntity::EK_Temporary:
4716 case InitializedEntity::EK_ArrayElement:
4717 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004718 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004719 case InitializedEntity::EK_RelatedResult:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004720 return true;
4721 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004722
4723 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004724}
4725
Richard Smith83da2e72011-10-19 16:55:56 +00004726/// \brief Look for copy and move constructors and constructor templates, for
4727/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4728static void LookupCopyAndMoveConstructors(Sema &S,
4729 OverloadCandidateSet &CandidateSet,
4730 CXXRecordDecl *Class,
4731 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004732 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004733 // The container holding the constructors can under certain conditions
4734 // be changed while iterating (e.g. because of deserialization).
4735 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004736 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004737 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004738 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4739 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004740 CXXConstructorDecl *Constructor = 0;
4741
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004742 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004743 // Handle copy/moveconstructors, only.
4744 if (!Constructor || Constructor->isInvalidDecl() ||
4745 !Constructor->isCopyOrMoveConstructor() ||
4746 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4747 continue;
4748
4749 DeclAccessPair FoundDecl
4750 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4751 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004752 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004753 continue;
4754 }
4755
4756 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004757 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004758 if (ConstructorTmpl->isInvalidDecl())
4759 continue;
4760
4761 Constructor = cast<CXXConstructorDecl>(
4762 ConstructorTmpl->getTemplatedDecl());
4763 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4764 continue;
4765
4766 // FIXME: Do we need to limit this to copy-constructor-like
4767 // candidates?
4768 DeclAccessPair FoundDecl
4769 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4770 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004771 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004772 }
4773}
4774
4775/// \brief Get the location at which initialization diagnostics should appear.
4776static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4777 Expr *Initializer) {
4778 switch (Entity.getKind()) {
4779 case InitializedEntity::EK_Result:
4780 return Entity.getReturnLoc();
4781
4782 case InitializedEntity::EK_Exception:
4783 return Entity.getThrowLoc();
4784
4785 case InitializedEntity::EK_Variable:
4786 return Entity.getDecl()->getLocation();
4787
Douglas Gregor47736542012-02-15 16:57:26 +00004788 case InitializedEntity::EK_LambdaCapture:
4789 return Entity.getCaptureLoc();
4790
Richard Smith83da2e72011-10-19 16:55:56 +00004791 case InitializedEntity::EK_ArrayElement:
4792 case InitializedEntity::EK_Member:
4793 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004794 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith83da2e72011-10-19 16:55:56 +00004795 case InitializedEntity::EK_Temporary:
4796 case InitializedEntity::EK_New:
4797 case InitializedEntity::EK_Base:
4798 case InitializedEntity::EK_Delegating:
4799 case InitializedEntity::EK_VectorElement:
4800 case InitializedEntity::EK_ComplexElement:
4801 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004802 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004803 case InitializedEntity::EK_RelatedResult:
Richard Smith83da2e72011-10-19 16:55:56 +00004804 return Initializer->getLocStart();
4805 }
4806 llvm_unreachable("missed an InitializedEntity kind?");
4807}
4808
Douglas Gregor523d46a2010-04-18 07:40:54 +00004809/// \brief Make a (potentially elidable) temporary copy of the object
4810/// provided by the given initializer by calling the appropriate copy
4811/// constructor.
4812///
4813/// \param S The Sema object used for type-checking.
4814///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004815/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004816/// the type of the initializer expression or a superclass thereof.
4817///
James Dennett1dfbd922012-06-14 21:40:34 +00004818/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004819///
4820/// \param CurInit The initializer expression.
4821///
4822/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4823/// is permitted in C++03 (but not C++0x) when binding a reference to
4824/// an rvalue.
4825///
4826/// \returns An expression that copies the initializer expression into
4827/// a temporary object, or an error expression if a copy could not be
4828/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004829static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004830 QualType T,
4831 const InitializedEntity &Entity,
4832 ExprResult CurInit,
4833 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004834 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004835 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004836 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004837 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004838 Class = cast<CXXRecordDecl>(Record->getDecl());
4839 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004840 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004841
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004842 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004843 // When certain criteria are met, an implementation is allowed to
4844 // omit the copy/move construction of a class object, even if the
4845 // copy/move constructor and/or destructor for the object have
4846 // side effects. [...]
4847 // - when a temporary class object that has not been bound to a
4848 // reference (12.2) would be copied/moved to a class object
4849 // with the same cv-unqualified type, the copy/move operation
4850 // can be omitted by constructing the temporary object
4851 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004852 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004853 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004854 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004855 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004856 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004857 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004858 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004859
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004860 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004861 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004862 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004863
Douglas Gregorcc15f012011-01-21 19:38:21 +00004864 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004865 // Only consider constructors and constructor templates. Per
4866 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4867 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004868 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004869 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004870
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004871 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4872
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004873 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004874 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004875 case OR_Success:
4876 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004877
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004878 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004879 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4880 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4881 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004882 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004883 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004884 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004885 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004886 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004887 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004888
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004889 case OR_Ambiguous:
4890 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004891 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004892 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004893 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004894 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004895
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004896 case OR_Deleted:
4897 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004898 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004899 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004900 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004901 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004902 }
4903
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004904 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004905 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004906 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004907
Anders Carlsson9a68a672010-04-21 18:47:17 +00004908 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004909 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004910
4911 if (IsExtraneousCopy) {
4912 // If this is a totally extraneous copy for C++03 reference
4913 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004914 // expression. We don't generate an (elided) copy operation here
4915 // because doing so would require us to pass down a flag to avoid
4916 // infinite recursion, where each step adds another extraneous,
4917 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004918
Douglas Gregor2559a702010-04-18 07:57:34 +00004919 // Instantiate the default arguments of any extra parameters in
4920 // the selected copy constructor, as if we were going to create a
4921 // proper call to the copy constructor.
4922 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4923 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4924 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004925 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004926 break;
4927
4928 // Build the default argument expression; we don't actually care
4929 // if this succeeds or not, because this routine will complain
4930 // if there was a problem.
4931 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4932 }
4933
Douglas Gregor523d46a2010-04-18 07:40:54 +00004934 return S.Owned(CurInitExpr);
4935 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004936
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004937 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004938 // constructor call (we might have derived-to-base conversions, or
4939 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004940 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004941 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004942
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004943 // Actually perform the constructor call.
4944 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004945 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004946 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004947 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004948 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004949 CXXConstructExpr::CK_Complete,
4950 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004951
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004952 // If we're supposed to bind temporaries, do so.
4953 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4954 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004955 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004956}
Douglas Gregor20093b42009-12-09 23:02:17 +00004957
Richard Smith83da2e72011-10-19 16:55:56 +00004958/// \brief Check whether elidable copy construction for binding a reference to
4959/// a temporary would have succeeded if we were building in C++98 mode, for
4960/// -Wc++98-compat.
4961static void CheckCXX98CompatAccessibleCopy(Sema &S,
4962 const InitializedEntity &Entity,
4963 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004964 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004965
4966 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4967 if (!Record)
4968 return;
4969
4970 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4971 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4972 == DiagnosticsEngine::Ignored)
4973 return;
4974
4975 // Find constructors which would have been considered.
4976 OverloadCandidateSet CandidateSet(Loc);
4977 LookupCopyAndMoveConstructors(
4978 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4979
4980 // Perform overload resolution.
4981 OverloadCandidateSet::iterator Best;
4982 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4983
4984 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4985 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4986 << CurInitExpr->getSourceRange();
4987
4988 switch (OR) {
4989 case OR_Success:
4990 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004991 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004992 // FIXME: Check default arguments as far as that's possible.
4993 break;
4994
4995 case OR_No_Viable_Function:
4996 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004997 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004998 break;
4999
5000 case OR_Ambiguous:
5001 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005002 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005003 break;
5004
5005 case OR_Deleted:
5006 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005007 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00005008 break;
5009 }
5010}
5011
Douglas Gregora41a8c52010-04-22 00:20:18 +00005012void InitializationSequence::PrintInitLocationNote(Sema &S,
5013 const InitializedEntity &Entity) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005014 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregora41a8c52010-04-22 00:20:18 +00005015 if (Entity.getDecl()->getLocation().isInvalid())
5016 return;
5017
5018 if (Entity.getDecl()->getDeclName())
5019 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5020 << Entity.getDecl()->getDeclName();
5021 else
5022 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5023 }
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005024 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5025 Entity.getMethodDecl())
5026 S.Diag(Entity.getMethodDecl()->getLocation(),
5027 diag::note_method_return_type_change)
5028 << Entity.getMethodDecl()->getDeclName();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005029}
5030
Sebastian Redl3b802322011-07-14 19:07:55 +00005031static bool isReferenceBinding(const InitializationSequence::Step &s) {
5032 return s.Kind == InitializationSequence::SK_BindReference ||
5033 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5034}
5035
Jordan Rose2624b812013-05-06 16:48:12 +00005036/// Returns true if the parameters describe a constructor initialization of
5037/// an explicit temporary object, e.g. "Point(x, y)".
5038static bool isExplicitTemporary(const InitializedEntity &Entity,
5039 const InitializationKind &Kind,
5040 unsigned NumArgs) {
5041 switch (Entity.getKind()) {
5042 case InitializedEntity::EK_Temporary:
5043 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005044 case InitializedEntity::EK_RelatedResult:
Jordan Rose2624b812013-05-06 16:48:12 +00005045 break;
5046 default:
5047 return false;
5048 }
5049
5050 switch (Kind.getKind()) {
5051 case InitializationKind::IK_DirectList:
5052 return true;
5053 // FIXME: Hack to work around cast weirdness.
5054 case InitializationKind::IK_Direct:
5055 case InitializationKind::IK_Value:
5056 return NumArgs != 1;
5057 default:
5058 return false;
5059 }
5060}
5061
Sebastian Redl10f04a62011-12-22 14:44:04 +00005062static ExprResult
5063PerformConstructorInitialization(Sema &S,
5064 const InitializedEntity &Entity,
5065 const InitializationKind &Kind,
5066 MultiExprArg Args,
5067 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005068 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005069 bool IsListInitialization,
5070 SourceLocation LBraceLoc,
5071 SourceLocation RBraceLoc) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005072 unsigned NumArgs = Args.size();
5073 CXXConstructorDecl *Constructor
5074 = cast<CXXConstructorDecl>(Step.Function.Function);
5075 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5076
5077 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005078 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005079 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5080 ? Kind.getEqualLoc()
5081 : Kind.getLocation();
5082
5083 if (Kind.getKind() == InitializationKind::IK_Default) {
5084 // Force even a trivial, implicit default constructor to be
5085 // semantically checked. We do this explicitly because we don't build
5086 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00005087 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00005088 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00005089 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005090 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5091 }
5092
5093 ExprResult CurInit = S.Owned((Expr *)0);
5094
Douglas Gregored878af2012-02-24 23:56:31 +00005095 // C++ [over.match.copy]p1:
5096 // - When initializing a temporary to be bound to the first parameter
5097 // of a constructor that takes a reference to possibly cv-qualified
5098 // T as its first argument, called with a single argument in the
5099 // context of direct-initialization, explicit conversion functions
5100 // are also considered.
5101 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5102 Args.size() == 1 &&
5103 Constructor->isCopyOrMoveConstructor();
5104
Sebastian Redl10f04a62011-12-22 14:44:04 +00005105 // Determine the arguments required to actually perform the constructor
5106 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005107 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00005108 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00005109 AllowExplicitConv,
5110 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005111 return ExprError();
5112
5113
Jordan Rose2624b812013-05-06 16:48:12 +00005114 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005115 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00005116 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005117 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5118 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005119
5120 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5121 if (!TSInfo)
5122 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella1245a542013-09-07 05:49:53 +00005123 SourceRange ParenOrBraceRange =
5124 (Kind.getKind() == InitializationKind::IK_DirectList)
5125 ? SourceRange(LBraceLoc, RBraceLoc)
5126 : Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005127
Richard Smithc83c2302012-12-19 01:39:02 +00005128 CurInit = S.Owned(
5129 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5130 TSInfo, ConstructorArgs,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005131 ParenOrBraceRange,
Richard Smithc83c2302012-12-19 01:39:02 +00005132 HadMultipleCandidates,
Enea Zaffanella14dcaa92013-09-07 11:22:02 +00005133 IsListInitialization,
Richard Smithc83c2302012-12-19 01:39:02 +00005134 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00005135 } else {
5136 CXXConstructExpr::ConstructionKind ConstructKind =
5137 CXXConstructExpr::CK_Complete;
5138
5139 if (Entity.getKind() == InitializedEntity::EK_Base) {
5140 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5141 CXXConstructExpr::CK_VirtualBase :
5142 CXXConstructExpr::CK_NonVirtualBase;
5143 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5144 ConstructKind = CXXConstructExpr::CK_Delegating;
5145 }
5146
5147 // Only get the parenthesis range if it is a direct construction.
5148 SourceRange parenRange =
5149 Kind.getKind() == InitializationKind::IK_Direct ?
5150 Kind.getParenRange() : SourceRange();
5151
5152 // If the entity allows NRVO, mark the construction as elidable
5153 // unconditionally.
5154 if (Entity.allowsNRVO())
5155 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5156 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005157 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005158 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005159 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005160 ConstructorInitRequiresZeroInit,
5161 ConstructKind,
5162 parenRange);
5163 else
5164 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5165 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005166 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005167 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005168 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005169 ConstructorInitRequiresZeroInit,
5170 ConstructKind,
5171 parenRange);
5172 }
5173 if (CurInit.isInvalid())
5174 return ExprError();
5175
5176 // Only check access if all of that succeeded.
5177 S.CheckConstructorAccess(Loc, Constructor, Entity,
5178 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005179 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5180 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005181
5182 if (shouldBindAsTemporary(Entity))
Richard Smith7c3e6152013-06-12 22:31:48 +00005183 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redl10f04a62011-12-22 14:44:04 +00005184
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005185 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005186}
5187
Richard Smith36d02af2012-06-04 22:27:30 +00005188/// Determine whether the specified InitializedEntity definitely has a lifetime
5189/// longer than the current full-expression. Conservatively returns false if
5190/// it's unclear.
5191static bool
5192InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5193 const InitializedEntity *Top = &Entity;
5194 while (Top->getParent())
5195 Top = Top->getParent();
5196
5197 switch (Top->getKind()) {
5198 case InitializedEntity::EK_Variable:
5199 case InitializedEntity::EK_Result:
5200 case InitializedEntity::EK_Exception:
5201 case InitializedEntity::EK_Member:
5202 case InitializedEntity::EK_New:
5203 case InitializedEntity::EK_Base:
5204 case InitializedEntity::EK_Delegating:
5205 return true;
5206
5207 case InitializedEntity::EK_ArrayElement:
5208 case InitializedEntity::EK_VectorElement:
5209 case InitializedEntity::EK_BlockElement:
5210 case InitializedEntity::EK_ComplexElement:
5211 // Could not determine what the full initialization is. Assume it might not
5212 // outlive the full-expression.
5213 return false;
5214
5215 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005216 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith36d02af2012-06-04 22:27:30 +00005217 case InitializedEntity::EK_Temporary:
5218 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005219 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005220 case InitializedEntity::EK_RelatedResult:
Richard Smith36d02af2012-06-04 22:27:30 +00005221 // The entity being initialized might not outlive the full-expression.
5222 return false;
5223 }
5224
5225 llvm_unreachable("unknown entity kind");
5226}
5227
Richard Smith211c8dd2013-06-05 00:46:14 +00005228/// Determine the declaration which an initialized entity ultimately refers to,
5229/// for the purpose of lifetime-extending a temporary bound to a reference in
5230/// the initialization of \p Entity.
5231static const ValueDecl *
5232getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5233 const ValueDecl *FallbackDecl = 0) {
5234 // C++11 [class.temporary]p5:
5235 switch (Entity.getKind()) {
5236 case InitializedEntity::EK_Variable:
5237 // The temporary [...] persists for the lifetime of the reference
5238 return Entity.getDecl();
5239
5240 case InitializedEntity::EK_Member:
5241 // For subobjects, we look at the complete object.
5242 if (Entity.getParent())
5243 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5244 Entity.getDecl());
5245
5246 // except:
5247 // -- A temporary bound to a reference member in a constructor's
5248 // ctor-initializer persists until the constructor exits.
5249 return Entity.getDecl();
5250
5251 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005252 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith211c8dd2013-06-05 00:46:14 +00005253 // -- A temporary bound to a reference parameter in a function call
5254 // persists until the completion of the full-expression containing
5255 // the call.
5256 case InitializedEntity::EK_Result:
5257 // -- The lifetime of a temporary bound to the returned value in a
5258 // function return statement is not extended; the temporary is
5259 // destroyed at the end of the full-expression in the return statement.
5260 case InitializedEntity::EK_New:
5261 // -- A temporary bound to a reference in a new-initializer persists
5262 // until the completion of the full-expression containing the
5263 // new-initializer.
5264 return 0;
5265
5266 case InitializedEntity::EK_Temporary:
5267 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005268 case InitializedEntity::EK_RelatedResult:
Richard Smith211c8dd2013-06-05 00:46:14 +00005269 // We don't yet know the storage duration of the surrounding temporary.
5270 // Assume it's got full-expression duration for now, it will patch up our
5271 // storage duration if that's not correct.
5272 return 0;
5273
5274 case InitializedEntity::EK_ArrayElement:
5275 // For subobjects, we look at the complete object.
5276 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5277 FallbackDecl);
5278
5279 case InitializedEntity::EK_Base:
5280 case InitializedEntity::EK_Delegating:
5281 // We can reach this case for aggregate initialization in a constructor:
5282 // struct A { int &&r; };
5283 // struct B : A { B() : A{0} {} };
5284 // In this case, use the innermost field decl as the context.
5285 return FallbackDecl;
5286
5287 case InitializedEntity::EK_BlockElement:
5288 case InitializedEntity::EK_LambdaCapture:
5289 case InitializedEntity::EK_Exception:
5290 case InitializedEntity::EK_VectorElement:
5291 case InitializedEntity::EK_ComplexElement:
Richard Smithd6b69872013-06-15 00:30:29 +00005292 return 0;
Richard Smith211c8dd2013-06-05 00:46:14 +00005293 }
Benjamin Kramer6f773e82013-06-05 15:37:50 +00005294 llvm_unreachable("unknown entity kind");
Richard Smith211c8dd2013-06-05 00:46:14 +00005295}
5296
5297static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5298
5299/// Update a glvalue expression that is used as the initializer of a reference
5300/// to note that its lifetime is extended.
Richard Smithd6b69872013-06-15 00:30:29 +00005301/// \return \c true if any temporary had its lifetime extended.
5302static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005303 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5304 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5305 // This is just redundant braces around an initializer. Step over it.
5306 Init = ILE->getInit(0);
5307 }
5308 }
5309
Richard Smithd6b69872013-06-15 00:30:29 +00005310 // Walk past any constructs which we can lifetime-extend across.
5311 Expr *Old;
5312 do {
5313 Old = Init;
5314
5315 // Step over any subobject adjustments; we may have a materialized
5316 // temporary inside them.
5317 SmallVector<const Expr *, 2> CommaLHSs;
5318 SmallVector<SubobjectAdjustment, 2> Adjustments;
5319 Init = const_cast<Expr *>(
5320 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5321
5322 // Per current approach for DR1376, look through casts to reference type
5323 // when performing lifetime extension.
5324 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5325 if (CE->getSubExpr()->isGLValue())
5326 Init = CE->getSubExpr();
5327
5328 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5329 // It's unclear if binding a reference to that xvalue extends the array
5330 // temporary.
5331 } while (Init != Old);
5332
Richard Smith211c8dd2013-06-05 00:46:14 +00005333 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5334 // Update the storage duration of the materialized temporary.
5335 // FIXME: Rebuild the expression instead of mutating it.
5336 ME->setExtendingDecl(ExtendingD);
5337 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
Richard Smithd6b69872013-06-15 00:30:29 +00005338 return true;
Richard Smith211c8dd2013-06-05 00:46:14 +00005339 }
Richard Smithd6b69872013-06-15 00:30:29 +00005340
5341 return false;
Richard Smith211c8dd2013-06-05 00:46:14 +00005342}
5343
5344/// Update a prvalue expression that is going to be materialized as a
5345/// lifetime-extended temporary.
5346static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5347 // Dig out the expression which constructs the extended temporary.
5348 SmallVector<const Expr *, 2> CommaLHSs;
5349 SmallVector<SubobjectAdjustment, 2> Adjustments;
5350 Init = const_cast<Expr *>(
5351 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5352
Richard Smith8a07cd32013-06-12 20:42:33 +00005353 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5354 Init = BTE->getSubExpr();
5355
Richard Smith7c3e6152013-06-12 22:31:48 +00005356 if (CXXStdInitializerListExpr *ILE =
Richard Smithd6b69872013-06-15 00:30:29 +00005357 dyn_cast<CXXStdInitializerListExpr>(Init)) {
5358 performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5359 return;
5360 }
Richard Smith7c3e6152013-06-12 22:31:48 +00005361
Richard Smith211c8dd2013-06-05 00:46:14 +00005362 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith7c3e6152013-06-12 22:31:48 +00005363 if (ILE->getType()->isArrayType()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005364 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5365 performLifetimeExtension(ILE->getInit(I), ExtendingD);
5366 return;
5367 }
5368
Richard Smith7c3e6152013-06-12 22:31:48 +00005369 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005370 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5371
5372 // If we lifetime-extend a braced initializer which is initializing an
5373 // aggregate, and that aggregate contains reference members which are
5374 // bound to temporaries, those temporaries are also lifetime-extended.
5375 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5376 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5377 performReferenceExtension(ILE->getInit(0), ExtendingD);
5378 else {
5379 unsigned Index = 0;
5380 for (RecordDecl::field_iterator I = RD->field_begin(),
5381 E = RD->field_end();
5382 I != E; ++I) {
Richard Smith3c3af142013-07-01 06:08:20 +00005383 if (Index >= ILE->getNumInits())
5384 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005385 if (I->isUnnamedBitfield())
5386 continue;
Richard Smith5771aab2013-06-27 22:54:33 +00005387 Expr *SubInit = ILE->getInit(Index);
Richard Smith211c8dd2013-06-05 00:46:14 +00005388 if (I->getType()->isReferenceType())
Richard Smith5771aab2013-06-27 22:54:33 +00005389 performReferenceExtension(SubInit, ExtendingD);
5390 else if (isa<InitListExpr>(SubInit) ||
5391 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smith211c8dd2013-06-05 00:46:14 +00005392 // This may be either aggregate-initialization of a member or
5393 // initialization of a std::initializer_list object. Either way,
5394 // we should recursively lifetime-extend that initializer.
Richard Smith5771aab2013-06-27 22:54:33 +00005395 performLifetimeExtension(SubInit, ExtendingD);
Richard Smith211c8dd2013-06-05 00:46:14 +00005396 ++Index;
5397 }
5398 }
5399 }
5400 }
5401}
5402
Richard Smith7c3e6152013-06-12 22:31:48 +00005403static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5404 const Expr *Init, bool IsInitializerList,
5405 const ValueDecl *ExtendingDecl) {
5406 // Warn if a field lifetime-extends a temporary.
5407 if (isa<FieldDecl>(ExtendingDecl)) {
5408 if (IsInitializerList) {
5409 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5410 << /*at end of constructor*/true;
5411 return;
5412 }
5413
5414 bool IsSubobjectMember = false;
5415 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5416 Ent = Ent->getParent()) {
5417 if (Ent->getKind() != InitializedEntity::EK_Base) {
5418 IsSubobjectMember = true;
5419 break;
5420 }
5421 }
5422 S.Diag(Init->getExprLoc(),
5423 diag::warn_bind_ref_member_to_temporary)
5424 << ExtendingDecl << Init->getSourceRange()
5425 << IsSubobjectMember << IsInitializerList;
5426 if (IsSubobjectMember)
5427 S.Diag(ExtendingDecl->getLocation(),
5428 diag::note_ref_subobject_of_member_declared_here);
5429 else
5430 S.Diag(ExtendingDecl->getLocation(),
5431 diag::note_ref_or_ptr_member_declared_here)
5432 << /*is pointer*/false;
5433 }
5434}
5435
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005436ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005437InitializationSequence::Perform(Sema &S,
5438 const InitializedEntity &Entity,
5439 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005440 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005441 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005442 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005443 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005444 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005445 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005446
Sebastian Redl7491c492011-06-05 13:59:11 +00005447 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005448 // If the declaration is a non-dependent, incomplete array type
5449 // that has an initializer, then its type will be completed once
5450 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005451 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005452 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005453 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005454 if (const IncompleteArrayType *ArrayT
5455 = S.Context.getAsIncompleteArrayType(DeclType)) {
5456 // FIXME: We don't currently have the ability to accurately
5457 // compute the length of an initializer list without
5458 // performing full type-checking of the initializer list
5459 // (since we have to determine where braces are implicitly
5460 // introduced and such). So, we fall back to making the array
5461 // type a dependently-sized array type with no specified
5462 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005463 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005464 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005465
Douglas Gregord87b61f2009-12-10 17:56:55 +00005466 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005467 if (DeclaratorDecl *DD = Entity.getDecl()) {
5468 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5469 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005470 if (IncompleteArrayTypeLoc ArrayLoc =
5471 TL.getAs<IncompleteArrayTypeLoc>())
5472 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005473 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005474 }
5475
5476 *ResultType
5477 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5478 /*NumElts=*/0,
5479 ArrayT->getSizeModifier(),
5480 ArrayT->getIndexTypeCVRQualifiers(),
5481 Brackets);
5482 }
5483
5484 }
5485 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005486 if (Kind.getKind() == InitializationKind::IK_Direct &&
5487 !Kind.isExplicitCast()) {
5488 // Rebuild the ParenListExpr.
5489 SourceRange ParenRange = Kind.getParenRange();
5490 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005491 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005492 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005493 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005494 Kind.isExplicitCast() ||
5495 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005496 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005497 }
5498
Sebastian Redl7491c492011-06-05 13:59:11 +00005499 // No steps means no initialization.
5500 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005501 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005502
Richard Smith80ad52f2013-01-02 11:42:31 +00005503 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005504 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005505 !Entity.isParameterKind()) {
Richard Smith03544fc2012-04-19 06:58:00 +00005506 // Produce a C++98 compatibility warning if we are initializing a reference
5507 // from an initializer list. For parameters, we produce a better warning
5508 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005509 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005510 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5511 << Init->getSourceRange();
5512 }
5513
Richard Smith36d02af2012-06-04 22:27:30 +00005514 // Diagnose cases where we initialize a pointer to an array temporary, and the
5515 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005516 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005517 Entity.getType()->isPointerType() &&
5518 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005519 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005520 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5521 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5522 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5523 << Init->getSourceRange();
5524 }
5525
Douglas Gregord6542d82009-12-22 15:35:07 +00005526 QualType DestType = Entity.getType().getNonReferenceType();
5527 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005528 // the same as Entity.getDecl()->getType() in cases involving type merging,
5529 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005530 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005531 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005532 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005533
John McCall60d7b3a2010-08-24 06:29:42 +00005534 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005535
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005536 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005537 // grab the only argument out the Args and place it into the "current"
5538 // initializer.
5539 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005540 case SK_ResolveAddressOfOverloadedFunction:
5541 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005542 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005543 case SK_CastDerivedToBaseLValue:
5544 case SK_BindReference:
5545 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005546 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005547 case SK_UserConversion:
5548 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005549 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005550 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005551 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005552 case SK_ConversionSequence:
5553 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005554 case SK_UnwrapInitList:
5555 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005556 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005557 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005558 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005559 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005560 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005561 case SK_PassByIndirectCopyRestore:
5562 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005563 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005564 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005565 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005566 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005567 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005568 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005569 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005570 break;
John McCallf6a16482010-12-04 03:47:34 +00005571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005572
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005573 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005574 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005575 case SK_ZeroInitialization:
5576 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005577 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005578
5579 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005580 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005581 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005582 for (step_iterator Step = step_begin(), StepEnd = step_end();
5583 Step != StepEnd; ++Step) {
5584 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005585 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005586
John Wiegley429bb272011-04-08 18:41:53 +00005587 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005588
Douglas Gregor20093b42009-12-09 23:02:17 +00005589 switch (Step->Kind) {
5590 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005591 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005592 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005593 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005594 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5595 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005596 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005597 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005598 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005599 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005600
Douglas Gregor20093b42009-12-09 23:02:17 +00005601 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005602 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005603 case SK_CastDerivedToBaseLValue: {
5604 // We have a derived-to-base cast that produces either an rvalue or an
5605 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005606
John McCallf871d0c2010-08-07 06:22:56 +00005607 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005608
Douglas Gregor20093b42009-12-09 23:02:17 +00005609 // Casts to inaccessible base classes are allowed with C-style casts.
5610 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5611 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005612 CurInit.get()->getLocStart(),
5613 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005614 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005615 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005616
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005617 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5618 QualType T = SourceType;
5619 if (const PointerType *Pointer = T->getAs<PointerType>())
5620 T = Pointer->getPointeeType();
5621 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005622 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005623 cast<CXXRecordDecl>(RecordTy->getDecl()));
5624 }
5625
John McCall5baba9d2010-08-25 10:28:54 +00005626 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005627 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005628 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005629 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005630 VK_XValue :
5631 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005632 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5633 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005634 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005635 CurInit.get(),
5636 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005637 break;
5638 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005639
Douglas Gregor20093b42009-12-09 23:02:17 +00005640 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005641 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5642 if (CurInit.get()->refersToBitField()) {
5643 // We don't necessarily have an unambiguous source bit-field.
5644 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005645 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005646 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005647 << (BitField ? BitField->getDeclName() : DeclarationName())
5648 << (BitField != NULL)
John Wiegley429bb272011-04-08 18:41:53 +00005649 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005650 if (BitField)
5651 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5652
John McCallf312b1e2010-08-26 23:41:50 +00005653 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005654 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005655
John Wiegley429bb272011-04-08 18:41:53 +00005656 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005657 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005658 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5659 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005660 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005661 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005662 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005663 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005664
Douglas Gregor20093b42009-12-09 23:02:17 +00005665 // Reference binding does not have any corresponding ASTs.
5666
5667 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005668 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005669 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005670
Richard Smithd6b69872013-06-15 00:30:29 +00005671 // Even though we didn't materialize a temporary, the binding may still
5672 // extend the lifetime of a temporary. This happens if we bind a reference
5673 // to the result of a cast to reference type.
5674 if (const ValueDecl *ExtendingDecl =
5675 getDeclForTemporaryLifetimeExtension(Entity)) {
5676 if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5677 warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5678 ExtendingDecl);
5679 }
5680
Douglas Gregor20093b42009-12-09 23:02:17 +00005681 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005682
Richard Smith211c8dd2013-06-05 00:46:14 +00005683 case SK_BindReferenceToTemporary: {
Jordan Rose1fd1e282013-04-11 00:58:58 +00005684 // Make sure the "temporary" is actually an rvalue.
5685 assert(CurInit.get()->isRValue() && "not a temporary");
5686
Douglas Gregor20093b42009-12-09 23:02:17 +00005687 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005688 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005689 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005690
Richard Smith211c8dd2013-06-05 00:46:14 +00005691 // Maybe lifetime-extend the temporary's subobjects to match the
5692 // entity's lifetime.
5693 const ValueDecl *ExtendingDecl =
5694 getDeclForTemporaryLifetimeExtension(Entity);
Richard Smitha4bb99c2013-06-12 21:51:50 +00005695 if (ExtendingDecl) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005696 performLifetimeExtension(CurInit.get(), ExtendingDecl);
Richard Smith7c3e6152013-06-12 22:31:48 +00005697 warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
Richard Smitha4bb99c2013-06-12 21:51:50 +00005698 }
5699
Douglas Gregor03e80032011-06-21 17:03:29 +00005700 // Materialize the temporary into memory.
Richard Smith8a07cd32013-06-12 20:42:33 +00005701 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smith211c8dd2013-06-05 00:46:14 +00005702 Entity.getType().getNonReferenceType(), CurInit.get(),
5703 Entity.getType()->isLValueReferenceType(), ExtendingDecl);
Douglas Gregord7b23162011-06-22 16:12:01 +00005704
5705 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith8a07cd32013-06-12 20:42:33 +00005706 // need cleanups. Likewise if we're extending this temporary to automatic
5707 // storage duration -- we need to register its cleanup during the
5708 // full-expression's cleanups.
5709 if ((S.getLangOpts().ObjCAutoRefCount &&
5710 MTE->getType()->isObjCLifetimeType()) ||
5711 (MTE->getStorageDuration() == SD_Automatic &&
5712 MTE->getType().isDestructedType()))
Douglas Gregord7b23162011-06-22 16:12:01 +00005713 S.ExprNeedsCleanups = true;
Richard Smith8a07cd32013-06-12 20:42:33 +00005714
5715 CurInit = S.Owned(MTE);
Douglas Gregor20093b42009-12-09 23:02:17 +00005716 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005717 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005718
Douglas Gregor523d46a2010-04-18 07:40:54 +00005719 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005720 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005721 /*IsExtraneousCopy=*/true);
5722 break;
5723
Douglas Gregor20093b42009-12-09 23:02:17 +00005724 case SK_UserConversion: {
5725 // We have a user-defined conversion that invokes either a constructor
5726 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005727 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005728 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005729 FunctionDecl *Fn = Step->Function.Function;
5730 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005731 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005732 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005733 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005734 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005735 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005736 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005737 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005738
Douglas Gregor20093b42009-12-09 23:02:17 +00005739 // Determine the arguments required to actually perform the constructor
5740 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005741 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005742 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005743 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005744 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005745 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005746
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005747 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005748 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005749 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005750 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005751 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005752 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005753 CXXConstructExpr::CK_Complete,
5754 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005755 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005756 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005757
Anders Carlsson9a68a672010-04-21 18:47:17 +00005758 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005759 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005760 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5761 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005762
John McCall2de56d12010-08-25 11:45:40 +00005763 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005764 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5765 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5766 S.IsDerivedFrom(SourceType, Class))
5767 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005768
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005769 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005770 } else {
5771 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005772 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005773 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005774 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005775 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5776 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005777
5778 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005779 // derived-to-base conversion? I believe the answer is "no", because
5780 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005781 ExprResult CurInitExprRes =
5782 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5783 FoundFn, Conversion);
5784 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005785 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005786 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005787
Douglas Gregor20093b42009-12-09 23:02:17 +00005788 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005789 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5790 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005791 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005792 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005793
John McCall2de56d12010-08-25 11:45:40 +00005794 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005795
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005796 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005797 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005798
Sebastian Redl3b802322011-07-14 19:07:55 +00005799 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005800 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5801
5802 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005803 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005804 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005805 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005806 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005807 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005808 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005809 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005810 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5811 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005812 }
5813 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005814
John McCallf871d0c2010-08-07 06:22:56 +00005815 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005816 CurInit.get()->getType(),
5817 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005818 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005819 if (MaybeBindToTemp)
5820 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005821 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005822 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005823 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005824 break;
5825 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005826
Douglas Gregor20093b42009-12-09 23:02:17 +00005827 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005828 case SK_QualificationConversionXValue:
5829 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005830 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005831 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005832 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005833 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005834 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005835 VK_XValue :
5836 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005837 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005838 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005839 }
5840
Jordan Rose1fd1e282013-04-11 00:58:58 +00005841 case SK_LValueToRValue: {
5842 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5843 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5844 CK_LValueToRValue,
5845 CurInit.take(),
5846 /*BasePath=*/0,
5847 VK_RValue));
5848 break;
5849 }
5850
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005851 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005852 Sema::CheckedConversionKind CCK
5853 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5854 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005855 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005856 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005857 ExprResult CurInitExprRes =
5858 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005859 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005860 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005861 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005862 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005863 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005864 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005865
Douglas Gregord87b61f2009-12-10 17:56:55 +00005866 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005867 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smith7c3e6152013-06-12 22:31:48 +00005868 // If we're not initializing the top-level entity, we need to create an
5869 // InitializeTemporary entity for our target type.
5870 QualType Ty = Step->Type;
5871 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005872 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005873 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5874 InitListChecker PerformInitList(S, InitEntity,
Richard Smith40cba902013-06-06 11:41:05 +00005875 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005876 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005877 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005878
Richard Smith7c3e6152013-06-12 22:31:48 +00005879 // Hack: We must update *ResultType if available in order to set the
5880 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5881 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5882 if (ResultType &&
5883 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005884 if ((*ResultType)->isRValueReferenceType())
5885 Ty = S.Context.getRValueReferenceType(Ty);
5886 else if ((*ResultType)->isLValueReferenceType())
5887 Ty = S.Context.getLValueReferenceType(Ty,
5888 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5889 *ResultType = Ty;
5890 }
5891
5892 InitListExpr *StructuredInitList =
5893 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005894 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005895 CurInit = shouldBindAsTemporary(InitEntity)
5896 ? S.MaybeBindToTemporary(StructuredInitList)
5897 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005898 break;
5899 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005900
Sebastian Redl10f04a62011-12-22 14:44:04 +00005901 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005902 // When an initializer list is passed for a parameter of type "reference
5903 // to object", we don't get an EK_Temporary entity, but instead an
5904 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005905 // FIXME: This is a hack. What we really should do is create a user
5906 // conversion step for this case, but this makes it considerably more
5907 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005908 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5909 Entity.getType().getNonReferenceType());
5910 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005911 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005912 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005913 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5914 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005915 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005916 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5917 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005918 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005919 ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005920 /*IsListInitialization*/ true,
5921 InitList->getLBraceLoc(),
5922 InitList->getRBraceLoc());
Sebastian Redl10f04a62011-12-22 14:44:04 +00005923 break;
5924 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005925
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005926 case SK_UnwrapInitList:
5927 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5928 break;
5929
5930 case SK_RewrapInitList: {
5931 Expr *E = CurInit.take();
5932 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5933 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005934 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005935 ILE->setSyntacticForm(Syntactic);
5936 ILE->setType(E->getType());
5937 ILE->setValueKind(E->getValueKind());
5938 CurInit = S.Owned(ILE);
5939 break;
5940 }
5941
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005942 case SK_ConstructorInitialization: {
5943 // When an initializer list is passed for a parameter of type "reference
5944 // to object", we don't get an EK_Temporary entity, but instead an
5945 // EK_Parameter entity with reference type.
5946 // FIXME: This is a hack. What we really should do is create a user
5947 // conversion step for this case, but this makes it considerably more
5948 // complicated. For now, this will do.
5949 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5950 Entity.getType().getNonReferenceType());
5951 bool UseTemporary = Entity.getType()->isReferenceType();
5952 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5953 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005954 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005955 ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005956 /*IsListInitialization*/ false,
5957 /*LBraceLoc*/ SourceLocation(),
5958 /*RBraceLoc*/ SourceLocation());
Douglas Gregor51c56d62009-12-14 20:49:26 +00005959 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005960 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005961
Douglas Gregor71d17402009-12-15 00:01:57 +00005962 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005963 step_iterator NextStep = Step;
5964 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005965 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005966 (NextStep->Kind == SK_ConstructorInitialization ||
5967 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005968 // The need for zero-initialization is recorded directly into
5969 // the call to the object's constructor within the next step.
5970 ConstructorInitRequiresZeroInit = true;
5971 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005972 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005973 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005974 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5975 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005976 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005977 Kind.getRange().getBegin());
5978
5979 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5980 TSInfo->getType().getNonLValueExprType(S.Context),
5981 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005982 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005983 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005984 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005985 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005986 break;
5987 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005988
5989 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005990 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005991 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005992 Sema::AssignConvertType ConvTy =
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00005993 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
5994 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley429bb272011-04-08 18:41:53 +00005995 if (Result.isInvalid())
5996 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005997 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005998
5999 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006000 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00006001 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006002 Entity.isParameterKind() &&
John Wiegley429bb272011-04-08 18:41:53 +00006003 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00006004 == Sema::Compatible)
6005 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00006006 if (CurInitExprRes.isInvalid())
6007 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006008 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00006009
Douglas Gregora41a8c52010-04-22 00:20:18 +00006010 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006011 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6012 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00006013 CurInit.get(),
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00006014 getAssignmentAction(Entity, true),
Douglas Gregora41a8c52010-04-22 00:20:18 +00006015 &Complained)) {
6016 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00006017 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00006018 } else if (Complained)
6019 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006020 break;
6021 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006022
6023 case SK_StringInit: {
6024 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00006025 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00006026 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006027 break;
6028 }
Douglas Gregor569c3162010-08-07 11:51:51 +00006029
6030 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00006031 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00006032 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00006033 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00006034 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006035
6036 case SK_ArrayInit:
6037 // Okay: we checked everything before creating this step. Note that
6038 // this is a GNU extension.
6039 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00006040 << Step->Type << CurInit.get()->getType()
6041 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006042
6043 // If the destination type is an incomplete array type, update the
6044 // type accordingly.
6045 if (ResultType) {
6046 if (const IncompleteArrayType *IncompleteDest
6047 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6048 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00006049 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006050 *ResultType = S.Context.getConstantArrayType(
6051 IncompleteDest->getElementType(),
6052 ConstantSource->getSize(),
6053 ArrayType::Normal, 0);
6054 }
6055 }
6056 }
John McCallf85e1932011-06-15 23:02:42 +00006057 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006058
Richard Smith0f163e92012-02-15 22:38:09 +00006059 case SK_ParenthesizedArrayInit:
6060 // Okay: we checked everything before creating this step. Note that
6061 // this is a GNU extension.
6062 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6063 << CurInit.get()->getSourceRange();
6064 break;
6065
John McCallf85e1932011-06-15 23:02:42 +00006066 case SK_PassByIndirectCopyRestore:
6067 case SK_PassByIndirectRestore:
6068 checkIndirectCopyRestoreSource(S, CurInit.get());
6069 CurInit = S.Owned(new (S.Context)
6070 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6071 Step->Kind == SK_PassByIndirectCopyRestore));
6072 break;
6073
6074 case SK_ProduceObjCObject:
6075 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00006076 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00006077 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006078 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006079
6080 case SK_StdInitializerList: {
Richard Smith7c3e6152013-06-12 22:31:48 +00006081 S.Diag(CurInit.get()->getExprLoc(),
6082 diag::warn_cxx98_compat_initializer_list_init)
6083 << CurInit.get()->getSourceRange();
Sebastian Redl28357452012-03-05 19:35:43 +00006084
Richard Smith7c3e6152013-06-12 22:31:48 +00006085 // Maybe lifetime-extend the array temporary's subobjects to match the
6086 // entity's lifetime.
6087 const ValueDecl *ExtendingDecl =
6088 getDeclForTemporaryLifetimeExtension(Entity);
6089 if (ExtendingDecl) {
6090 performLifetimeExtension(CurInit.get(), ExtendingDecl);
6091 warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
Sebastian Redl28357452012-03-05 19:35:43 +00006092 }
6093
Richard Smith7c3e6152013-06-12 22:31:48 +00006094 // Materialize the temporary into memory.
6095 MaterializeTemporaryExpr *MTE = new (S.Context)
6096 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6097 /*lvalue reference*/ false, ExtendingDecl);
6098
6099 // Wrap it in a construction of a std::initializer_list<T>.
6100 CurInit = S.Owned(
6101 new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6102
6103 // Bind the result, in case the library has given initializer_list a
6104 // non-trivial destructor.
6105 if (shouldBindAsTemporary(Entity))
6106 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redl2b916b82012-01-17 22:49:42 +00006107 break;
6108 }
Richard Smith7c3e6152013-06-12 22:31:48 +00006109
Guy Benyei21f18c42013-02-07 10:55:47 +00006110 case SK_OCLSamplerInit: {
6111 assert(Step->Type->isSamplerT() &&
6112 "Sampler initialization on non sampler type.");
6113
6114 QualType SourceType = CurInit.get()->getType();
Guy Benyei21f18c42013-02-07 10:55:47 +00006115
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006116 if (Entity.isParameterKind()) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006117 if (!SourceType->isSamplerT())
6118 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6119 << SourceType;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006120 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006121 llvm_unreachable("Invalid EntityKind!");
6122 }
6123
6124 break;
6125 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00006126 case SK_OCLZeroEvent: {
6127 assert(Step->Type->isEventT() &&
6128 "Event initialization on non event type.");
6129
6130 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6131 CK_ZeroToOCLEvent,
6132 CurInit.get()->getValueKind());
6133 break;
6134 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006135 }
6136 }
John McCall15d7d122010-11-11 03:21:53 +00006137
6138 // Diagnose non-fatal problems with the completed initialization.
6139 if (Entity.getKind() == InitializedEntity::EK_Member &&
6140 cast<FieldDecl>(Entity.getDecl())->isBitField())
6141 S.CheckBitFieldInitialization(Kind.getLocation(),
6142 cast<FieldDecl>(Entity.getDecl()),
6143 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006144
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006145 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00006146}
6147
Richard Smithd5bc8672012-12-08 02:01:17 +00006148/// Somewhere within T there is an uninitialized reference subobject.
6149/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00006150static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6151 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006152 if (T->isReferenceType()) {
6153 S.Diag(Loc, diag::err_reference_without_init)
6154 << T.getNonReferenceType();
6155 return true;
6156 }
6157
6158 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6159 if (!RD || !RD->hasUninitializedReferenceMember())
6160 return false;
6161
6162 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6163 FE = RD->field_end(); FI != FE; ++FI) {
6164 if (FI->isUnnamedBitfield())
6165 continue;
6166
6167 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6168 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6169 return true;
6170 }
6171 }
6172
6173 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6174 BE = RD->bases_end();
6175 BI != BE; ++BI) {
6176 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6177 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6178 return true;
6179 }
6180 }
6181
6182 return false;
6183}
6184
6185
Douglas Gregor20093b42009-12-09 23:02:17 +00006186//===----------------------------------------------------------------------===//
6187// Diagnose initialization failures
6188//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00006189
6190/// Emit notes associated with an initialization that failed due to a
6191/// "simple" conversion failure.
6192static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6193 Expr *op) {
6194 QualType destType = entity.getType();
6195 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6196 op->getType()->isObjCObjectPointerType()) {
6197
6198 // Emit a possible note about the conversion failing because the
6199 // operand is a message send with a related result type.
6200 S.EmitRelatedResultTypeNote(op);
6201
6202 // Emit a possible note about a return failing because we're
6203 // expecting a related result type.
6204 if (entity.getKind() == InitializedEntity::EK_Result)
6205 S.EmitRelatedResultTypeNoteForReturn(destType);
6206 }
6207}
6208
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006209bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00006210 const InitializedEntity &Entity,
6211 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006212 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00006213 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00006214 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006215
Douglas Gregord6542d82009-12-22 15:35:07 +00006216 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00006217 switch (Failure) {
6218 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006219 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006220 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006221 // Dig out the reference subobject which is uninitialized and diagnose it.
6222 // If this is value-initialization, this could be nested some way within
6223 // the target type.
6224 assert(Kind.getKind() == InitializationKind::IK_Value ||
6225 DestType->isReferenceType());
6226 bool Diagnosed =
6227 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6228 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6229 (void)Diagnosed;
6230 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006231 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006232 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00006233 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006234
Douglas Gregor20093b42009-12-09 23:02:17 +00006235 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00006236 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00006237 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00006238 case FK_ArrayNeedsInitListOrStringLiteral:
6239 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6240 break;
6241 case FK_ArrayNeedsInitListOrWideStringLiteral:
6242 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6243 break;
6244 case FK_NarrowStringIntoWideCharArray:
6245 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6246 break;
6247 case FK_WideStringIntoCharArray:
6248 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6249 break;
6250 case FK_IncompatWideStringIntoWideChar:
6251 S.Diag(Kind.getLocation(),
6252 diag::err_array_init_incompat_wide_string_into_wchar);
6253 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006254 case FK_ArrayTypeMismatch:
6255 case FK_NonConstantArrayInit:
6256 S.Diag(Kind.getLocation(),
6257 (Failure == FK_ArrayTypeMismatch
6258 ? diag::err_array_init_different_type
6259 : diag::err_array_init_non_constant_array))
6260 << DestType.getNonReferenceType()
6261 << Args[0]->getType()
6262 << Args[0]->getSourceRange();
6263 break;
6264
John McCall73076432012-01-05 00:13:19 +00006265 case FK_VariableLengthArrayHasInitializer:
6266 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6267 << Args[0]->getSourceRange();
6268 break;
6269
John McCall6bb80172010-03-30 21:47:33 +00006270 case FK_AddressOfOverloadFailed: {
6271 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006272 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00006273 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00006274 true,
6275 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00006276 break;
John McCall6bb80172010-03-30 21:47:33 +00006277 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006278
Douglas Gregor20093b42009-12-09 23:02:17 +00006279 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00006280 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00006281 switch (FailedOverloadResult) {
6282 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006283 if (Failure == FK_UserConversionOverloadFailed)
6284 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6285 << Args[0]->getType() << DestType
6286 << Args[0]->getSourceRange();
6287 else
6288 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6289 << DestType << Args[0]->getType()
6290 << Args[0]->getSourceRange();
6291
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006292 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006293 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006294
Douglas Gregor20093b42009-12-09 23:02:17 +00006295 case OR_No_Viable_Function:
Larisse Voufo288f76a2013-06-27 03:36:30 +00006296 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo7419d012013-06-27 01:50:25 +00006297 DestType.getNonReferenceType(),
6298 diag::err_typecheck_nonviable_condition_incomplete,
6299 Args[0]->getType(), Args[0]->getSourceRange()))
6300 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6301 << Args[0]->getType() << Args[0]->getSourceRange()
6302 << DestType.getNonReferenceType();
6303
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006304 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006305 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006306
Douglas Gregor20093b42009-12-09 23:02:17 +00006307 case OR_Deleted: {
6308 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6309 << Args[0]->getType() << DestType.getNonReferenceType()
6310 << Args[0]->getSourceRange();
6311 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006312 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006313 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6314 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00006315 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00006316 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00006317 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006318 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00006319 }
6320 break;
6321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006322
Douglas Gregor20093b42009-12-09 23:02:17 +00006323 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006324 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00006325 }
6326 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006327
Douglas Gregor20093b42009-12-09 23:02:17 +00006328 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006329 if (isa<InitListExpr>(Args[0])) {
6330 S.Diag(Kind.getLocation(),
6331 diag::err_lvalue_reference_bind_to_initlist)
6332 << DestType.getNonReferenceType().isVolatileQualified()
6333 << DestType.getNonReferenceType()
6334 << Args[0]->getSourceRange();
6335 break;
6336 }
6337 // Intentional fallthrough
6338
Douglas Gregor20093b42009-12-09 23:02:17 +00006339 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006340 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00006341 Failure == FK_NonConstLValueReferenceBindingToTemporary
6342 ? diag::err_lvalue_reference_bind_to_temporary
6343 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00006344 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00006345 << DestType.getNonReferenceType()
6346 << Args[0]->getType()
6347 << Args[0]->getSourceRange();
6348 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006349
Douglas Gregor20093b42009-12-09 23:02:17 +00006350 case FK_RValueReferenceBindingToLValue:
6351 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00006352 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00006353 << Args[0]->getSourceRange();
6354 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006355
Douglas Gregor20093b42009-12-09 23:02:17 +00006356 case FK_ReferenceInitDropsQualifiers:
6357 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6358 << DestType.getNonReferenceType()
6359 << Args[0]->getType()
6360 << Args[0]->getSourceRange();
6361 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006362
Douglas Gregor20093b42009-12-09 23:02:17 +00006363 case FK_ReferenceInitFailed:
6364 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6365 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006366 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006367 << Args[0]->getType()
6368 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006369 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006370 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006371
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006372 case FK_ConversionFailed: {
6373 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006374 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006375 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006376 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006377 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006378 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006379 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006380 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6381 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006382 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006383 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006384 }
John Wiegley429bb272011-04-08 18:41:53 +00006385
6386 case FK_ConversionFromPropertyFailed:
6387 // No-op. This error has already been reported.
6388 break;
6389
Douglas Gregord87b61f2009-12-10 17:56:55 +00006390 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006391 SourceRange R;
6392
6393 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006394 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006395 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006396 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006397 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006398
Douglas Gregor19311e72010-09-08 21:40:08 +00006399 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6400 if (Kind.isCStyleOrFunctionalCast())
6401 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6402 << R;
6403 else
6404 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6405 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006406 break;
6407 }
6408
6409 case FK_ReferenceBindingToInitList:
6410 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6411 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6412 break;
6413
6414 case FK_InitListBadDestinationType:
6415 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6416 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6417 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006418
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006419 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006420 case FK_ConstructorOverloadFailed: {
6421 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006422 if (Args.size())
6423 ArgsRange = SourceRange(Args.front()->getLocStart(),
6424 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006425
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006426 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006427 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006428 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006429 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006430 }
6431
Douglas Gregor51c56d62009-12-14 20:49:26 +00006432 // FIXME: Using "DestType" for the entity we're printing is probably
6433 // bad.
6434 switch (FailedOverloadResult) {
6435 case OR_Ambiguous:
6436 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6437 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006438 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006439 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006440
Douglas Gregor51c56d62009-12-14 20:49:26 +00006441 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006442 if (Kind.getKind() == InitializationKind::IK_Default &&
6443 (Entity.getKind() == InitializedEntity::EK_Base ||
6444 Entity.getKind() == InitializedEntity::EK_Member) &&
6445 isa<CXXConstructorDecl>(S.CurContext)) {
6446 // This is implicit default initialization of a member or
6447 // base within a constructor. If no viable function was
6448 // found, notify the user that she needs to explicitly
6449 // initialize this base/member.
6450 CXXConstructorDecl *Constructor
6451 = cast<CXXConstructorDecl>(S.CurContext);
6452 if (Entity.getKind() == InitializedEntity::EK_Base) {
6453 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006454 << (Constructor->getInheritedConstructor() ? 2 :
6455 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006456 << S.Context.getTypeDeclType(Constructor->getParent())
6457 << /*base=*/0
6458 << Entity.getType();
6459
6460 RecordDecl *BaseDecl
6461 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6462 ->getDecl();
6463 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6464 << S.Context.getTagDeclType(BaseDecl);
6465 } else {
6466 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006467 << (Constructor->getInheritedConstructor() ? 2 :
6468 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006469 << S.Context.getTypeDeclType(Constructor->getParent())
6470 << /*member=*/1
6471 << Entity.getName();
6472 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6473
6474 if (const RecordType *Record
6475 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006476 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006477 diag::note_previous_decl)
6478 << S.Context.getTagDeclType(Record->getDecl());
6479 }
6480 break;
6481 }
6482
Douglas Gregor51c56d62009-12-14 20:49:26 +00006483 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6484 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006485 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006486 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006487
Douglas Gregor51c56d62009-12-14 20:49:26 +00006488 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006489 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006490 OverloadingResult Ovl
6491 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006492 if (Ovl != OR_Deleted) {
6493 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6494 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006495 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006496 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006497 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006498
6499 // If this is a defaulted or implicitly-declared function, then
6500 // it was implicitly deleted. Make it clear that the deletion was
6501 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006502 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006503 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006504 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006505 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006506 else
6507 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6508 << true << DestType << ArgsRange;
6509
6510 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006511 break;
6512 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006513
Douglas Gregor51c56d62009-12-14 20:49:26 +00006514 case OR_Success:
6515 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006516 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006517 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006518 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006519
Douglas Gregor99a2e602009-12-16 01:38:02 +00006520 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006521 if (Entity.getKind() == InitializedEntity::EK_Member &&
6522 isa<CXXConstructorDecl>(S.CurContext)) {
6523 // This is implicit default-initialization of a const member in
6524 // a constructor. Complain that it needs to be explicitly
6525 // initialized.
6526 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6527 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006528 << (Constructor->getInheritedConstructor() ? 2 :
6529 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006530 << S.Context.getTypeDeclType(Constructor->getParent())
6531 << /*const=*/1
6532 << Entity.getName();
6533 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6534 << Entity.getName();
6535 } else {
6536 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6537 << DestType << (bool)DestType->getAs<RecordType>();
6538 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006539 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006540
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006541 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006542 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006543 diag::err_init_incomplete_type);
6544 break;
6545
Sebastian Redl14b0c192011-09-24 17:48:00 +00006546 case FK_ListInitializationFailed: {
6547 // Run the init list checker again to emit diagnostics.
6548 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6549 QualType DestType = Entity.getType();
6550 InitListChecker DiagnoseInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00006551 DestType, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006552 assert(DiagnoseInitList.HadError() &&
6553 "Inconsistent init list check result.");
6554 break;
6555 }
John McCall5acb0c92011-10-17 18:40:02 +00006556
6557 case FK_PlaceholderType: {
6558 // FIXME: Already diagnosed!
6559 break;
6560 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006561
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006562 case FK_ExplicitConstructor: {
6563 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6564 << Args[0]->getSourceRange();
6565 OverloadCandidateSet::iterator Best;
6566 OverloadingResult Ovl
6567 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006568 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006569 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6570 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6571 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6572 break;
6573 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006574 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006575
Douglas Gregora41a8c52010-04-22 00:20:18 +00006576 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006577 return true;
6578}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006579
Chris Lattner5f9e2722011-07-23 10:55:15 +00006580void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006581 switch (SequenceKind) {
6582 case FailedSequence: {
6583 OS << "Failed sequence: ";
6584 switch (Failure) {
6585 case FK_TooManyInitsForReference:
6586 OS << "too many initializers for reference";
6587 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006588
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006589 case FK_ArrayNeedsInitList:
6590 OS << "array requires initializer list";
6591 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006592
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006593 case FK_ArrayNeedsInitListOrStringLiteral:
6594 OS << "array requires initializer list or string literal";
6595 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006596
Hans Wennborg0ff50742013-05-15 11:03:04 +00006597 case FK_ArrayNeedsInitListOrWideStringLiteral:
6598 OS << "array requires initializer list or wide string literal";
6599 break;
6600
6601 case FK_NarrowStringIntoWideCharArray:
6602 OS << "narrow string into wide char array";
6603 break;
6604
6605 case FK_WideStringIntoCharArray:
6606 OS << "wide string into char array";
6607 break;
6608
6609 case FK_IncompatWideStringIntoWideChar:
6610 OS << "incompatible wide string into wide char array";
6611 break;
6612
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006613 case FK_ArrayTypeMismatch:
6614 OS << "array type mismatch";
6615 break;
6616
6617 case FK_NonConstantArrayInit:
6618 OS << "non-constant array initializer";
6619 break;
6620
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006621 case FK_AddressOfOverloadFailed:
6622 OS << "address of overloaded function failed";
6623 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006624
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006625 case FK_ReferenceInitOverloadFailed:
6626 OS << "overload resolution for reference initialization failed";
6627 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006628
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006629 case FK_NonConstLValueReferenceBindingToTemporary:
6630 OS << "non-const lvalue reference bound to temporary";
6631 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006632
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006633 case FK_NonConstLValueReferenceBindingToUnrelated:
6634 OS << "non-const lvalue reference bound to unrelated type";
6635 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006636
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006637 case FK_RValueReferenceBindingToLValue:
6638 OS << "rvalue reference bound to an lvalue";
6639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006640
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006641 case FK_ReferenceInitDropsQualifiers:
6642 OS << "reference initialization drops qualifiers";
6643 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006644
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006645 case FK_ReferenceInitFailed:
6646 OS << "reference initialization failed";
6647 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006648
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006649 case FK_ConversionFailed:
6650 OS << "conversion failed";
6651 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006652
John Wiegley429bb272011-04-08 18:41:53 +00006653 case FK_ConversionFromPropertyFailed:
6654 OS << "conversion from property failed";
6655 break;
6656
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006657 case FK_TooManyInitsForScalar:
6658 OS << "too many initializers for scalar";
6659 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006660
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006661 case FK_ReferenceBindingToInitList:
6662 OS << "referencing binding to initializer list";
6663 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006664
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006665 case FK_InitListBadDestinationType:
6666 OS << "initializer list for non-aggregate, non-scalar type";
6667 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006668
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006669 case FK_UserConversionOverloadFailed:
6670 OS << "overloading failed for user-defined conversion";
6671 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006672
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006673 case FK_ConstructorOverloadFailed:
6674 OS << "constructor overloading failed";
6675 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006676
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006677 case FK_DefaultInitOfConst:
6678 OS << "default initialization of a const variable";
6679 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006680
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006681 case FK_Incomplete:
6682 OS << "initialization of incomplete type";
6683 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006684
6685 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006686 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006687 break;
6688
John McCall73076432012-01-05 00:13:19 +00006689 case FK_VariableLengthArrayHasInitializer:
6690 OS << "variable length array has an initializer";
6691 break;
6692
John McCall5acb0c92011-10-17 18:40:02 +00006693 case FK_PlaceholderType:
6694 OS << "initializer expression isn't contextually valid";
6695 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006696
6697 case FK_ListConstructorOverloadFailed:
6698 OS << "list constructor overloading failed";
6699 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006700
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006701 case FK_ExplicitConstructor:
6702 OS << "list copy initialization chose explicit constructor";
6703 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006704 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006705 OS << '\n';
6706 return;
6707 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006708
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006709 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006710 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006711 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006712
Sebastian Redl7491c492011-06-05 13:59:11 +00006713 case NormalSequence:
6714 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006715 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006716 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006717
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006718 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6719 if (S != step_begin()) {
6720 OS << " -> ";
6721 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006722
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006723 switch (S->Kind) {
6724 case SK_ResolveAddressOfOverloadedFunction:
6725 OS << "resolve address of overloaded function";
6726 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006727
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006728 case SK_CastDerivedToBaseRValue:
6729 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6730 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006731
Sebastian Redl906082e2010-07-20 04:20:21 +00006732 case SK_CastDerivedToBaseXValue:
6733 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6734 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006735
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006736 case SK_CastDerivedToBaseLValue:
6737 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6738 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006739
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006740 case SK_BindReference:
6741 OS << "bind reference to lvalue";
6742 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006743
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006744 case SK_BindReferenceToTemporary:
6745 OS << "bind reference to a temporary";
6746 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006747
Douglas Gregor523d46a2010-04-18 07:40:54 +00006748 case SK_ExtraneousCopyToTemporary:
6749 OS << "extraneous C++03 copy to temporary";
6750 break;
6751
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006752 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006753 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006754 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006755
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006756 case SK_QualificationConversionRValue:
6757 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006758 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006759
Sebastian Redl906082e2010-07-20 04:20:21 +00006760 case SK_QualificationConversionXValue:
6761 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006762 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006763
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006764 case SK_QualificationConversionLValue:
6765 OS << "qualification conversion (lvalue)";
6766 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006767
Jordan Rose1fd1e282013-04-11 00:58:58 +00006768 case SK_LValueToRValue:
6769 OS << "load (lvalue to rvalue)";
6770 break;
6771
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006772 case SK_ConversionSequence:
6773 OS << "implicit conversion sequence (";
6774 S->ICS->DebugPrint(); // FIXME: use OS
6775 OS << ")";
6776 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006777
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006778 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006779 OS << "list aggregate initialization";
6780 break;
6781
6782 case SK_ListConstructorCall:
6783 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006784 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006785
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006786 case SK_UnwrapInitList:
6787 OS << "unwrap reference initializer list";
6788 break;
6789
6790 case SK_RewrapInitList:
6791 OS << "rewrap reference initializer list";
6792 break;
6793
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006794 case SK_ConstructorInitialization:
6795 OS << "constructor initialization";
6796 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006797
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006798 case SK_ZeroInitialization:
6799 OS << "zero initialization";
6800 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006801
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006802 case SK_CAssignment:
6803 OS << "C assignment";
6804 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006805
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006806 case SK_StringInit:
6807 OS << "string initialization";
6808 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006809
6810 case SK_ObjCObjectConversion:
6811 OS << "Objective-C object conversion";
6812 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006813
6814 case SK_ArrayInit:
6815 OS << "array initialization";
6816 break;
John McCallf85e1932011-06-15 23:02:42 +00006817
Richard Smith0f163e92012-02-15 22:38:09 +00006818 case SK_ParenthesizedArrayInit:
6819 OS << "parenthesized array initialization";
6820 break;
6821
John McCallf85e1932011-06-15 23:02:42 +00006822 case SK_PassByIndirectCopyRestore:
6823 OS << "pass by indirect copy and restore";
6824 break;
6825
6826 case SK_PassByIndirectRestore:
6827 OS << "pass by indirect restore";
6828 break;
6829
6830 case SK_ProduceObjCObject:
6831 OS << "Objective-C object retension";
6832 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006833
6834 case SK_StdInitializerList:
6835 OS << "std::initializer_list from initializer list";
6836 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006837
Guy Benyei21f18c42013-02-07 10:55:47 +00006838 case SK_OCLSamplerInit:
6839 OS << "OpenCL sampler_t from integer constant";
6840 break;
6841
Guy Benyeie6b9d802013-01-20 12:31:11 +00006842 case SK_OCLZeroEvent:
6843 OS << "OpenCL event_t from zero";
6844 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006845 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006846
6847 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006848 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006849
6850 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006851}
6852
6853void InitializationSequence::dump() const {
6854 dump(llvm::errs());
6855}
6856
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006857static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6858 QualType EntityType,
6859 const Expr *PreInit,
6860 const Expr *PostInit) {
6861 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6862 return;
6863
6864 // A narrowing conversion can only appear as the final implicit conversion in
6865 // an initialization sequence.
6866 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6867 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6868 return;
6869
6870 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6871 const StandardConversionSequence *SCS = 0;
6872 switch (ICS.getKind()) {
6873 case ImplicitConversionSequence::StandardConversion:
6874 SCS = &ICS.Standard;
6875 break;
6876 case ImplicitConversionSequence::UserDefinedConversion:
6877 SCS = &ICS.UserDefined.After;
6878 break;
6879 case ImplicitConversionSequence::AmbiguousConversion:
6880 case ImplicitConversionSequence::EllipsisConversion:
6881 case ImplicitConversionSequence::BadConversion:
6882 return;
6883 }
6884
6885 // Determine the type prior to the narrowing conversion. If a conversion
6886 // operator was used, this may be different from both the type of the entity
6887 // and of the pre-initialization expression.
6888 QualType PreNarrowingType = PreInit->getType();
6889 if (Seq.step_begin() + 1 != Seq.step_end())
6890 PreNarrowingType = Seq.step_end()[-2].Type;
6891
6892 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6893 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006894 QualType ConstantType;
6895 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6896 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006897 case NK_Not_Narrowing:
6898 // No narrowing occurred.
6899 return;
6900
6901 case NK_Type_Narrowing:
6902 // This was a floating-to-integer conversion, which is always considered a
6903 // narrowing conversion even if the value is a constant and can be
6904 // represented exactly as an integer.
6905 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006906 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006907 diag::warn_init_list_type_narrowing
6908 : S.isSFINAEContext()?
6909 diag::err_init_list_type_narrowing_sfinae
6910 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006911 << PostInit->getSourceRange()
6912 << PreNarrowingType.getLocalUnqualifiedType()
6913 << EntityType.getLocalUnqualifiedType();
6914 break;
6915
6916 case NK_Constant_Narrowing:
6917 // A constant value was narrowed.
6918 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006919 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006920 diag::warn_init_list_constant_narrowing
6921 : S.isSFINAEContext()?
6922 diag::err_init_list_constant_narrowing_sfinae
6923 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006924 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006925 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006926 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006927 break;
6928
6929 case NK_Variable_Narrowing:
6930 // A variable's value may have been narrowed.
6931 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006932 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006933 diag::warn_init_list_variable_narrowing
6934 : S.isSFINAEContext()?
6935 diag::err_init_list_variable_narrowing_sfinae
6936 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006937 << PostInit->getSourceRange()
6938 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006939 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006940 break;
6941 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006942
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006943 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006944 llvm::raw_svector_ostream OS(StaticCast);
6945 OS << "static_cast<";
6946 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6947 // It's important to use the typedef's name if there is one so that the
6948 // fixit doesn't break code using types like int64_t.
6949 //
6950 // FIXME: This will break if the typedef requires qualification. But
6951 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006952 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006953 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006954 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006955 else {
6956 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6957 // with a broken cast.
6958 return;
6959 }
6960 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006961 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6962 << PostInit->getSourceRange()
6963 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006964 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006965 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006966}
6967
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006968//===----------------------------------------------------------------------===//
6969// Initialization helper functions
6970//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006971bool
6972Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6973 ExprResult Init) {
6974 if (Init.isInvalid())
6975 return false;
6976
6977 Expr *InitE = Init.get();
6978 assert(InitE && "No initialization expression");
6979
Douglas Gregor3c394c52012-07-31 22:15:04 +00006980 InitializationKind Kind
6981 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006982 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006983 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006984}
6985
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006986ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006987Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6988 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006989 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006990 bool TopLevelOfInitList,
6991 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006992 if (Init.isInvalid())
6993 return ExprError();
6994
John McCall15d7d122010-11-11 03:21:53 +00006995 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006996 assert(InitE && "No initialization expression?");
6997
6998 if (EqualLoc.isInvalid())
6999 EqualLoc = InitE->getLocStart();
7000
7001 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00007002 EqualLoc,
7003 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007004 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007005 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007006
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007007 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007008
7009 if (!Result.isInvalid() && TopLevelOfInitList)
7010 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
7011 InitE, Result.get());
7012
7013 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007014}