blob: 034c1b6c7184be4bd138b0e183e26675938d000d [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,
Richard Smithb9bf3122013-09-20 20:10:22 +0000248 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000249 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000250 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000251 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000252 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000253 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000257 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000258 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000259 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000262 void CheckComplexType(const InitializedEntity &Entity,
263 InitListExpr *IList, QualType DeclType,
264 unsigned &Index,
265 InitListExpr *StructuredList,
266 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000267 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000268 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000269 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000274 unsigned &Index,
275 InitListExpr *StructuredList,
276 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000277 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000278 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000281 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000282 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000283 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000284 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000286 unsigned &StructuredIndex,
287 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000288 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000289 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000290 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000294 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000295 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000296 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000297 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000303 bool FinishSubobjectInit,
304 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000305 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
306 QualType CurrentObjectType,
307 InitListExpr *StructuredList,
308 unsigned StructuredIndex,
309 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000310 void UpdateStructuredListElement(InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000312 Expr *expr);
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000315
Douglas Gregord6d37de2009-12-22 00:05:34 +0000316 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
317 const InitializedEntity &ParentEntity,
318 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000319 void FillInValueInitializations(const InitializedEntity &Entity,
320 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000321 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
322 Expr *InitExpr, FieldDecl *Field,
323 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000324 void CheckValueInitializable(const InitializedEntity &Entity);
325
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000326public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000327 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smith40cba902013-06-06 11:41:05 +0000328 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000329 bool HadError() { return hadError; }
330
331 // @brief Retrieves the fully-structured initializer list used for
332 // semantic analysis and code generation.
333 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
334};
Chris Lattner8b419b92009-02-24 22:48:58 +0000335} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000336
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000337void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
338 assert(VerifyOnly &&
339 "CheckValueInitializable is only inteded for verification mode.");
340
341 SourceLocation Loc;
342 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
343 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000344 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000345 if (InitSeq.Failed())
346 hadError = true;
347}
348
Douglas Gregord6d37de2009-12-22 00:05:34 +0000349void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
350 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000351 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000352 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000353 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000354 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000356 = InitializedEntity::InitializeMember(Field, &ParentEntity);
357 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000358 // If there's no explicit initializer but we have a default initializer, use
359 // that. This only happens in C++1y, since classes with default
360 // initializers are not aggregates in C++11.
361 if (Field->hasInClassInitializer()) {
362 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
363 ILE->getRBraceLoc(), Field);
364 if (Init < NumInits)
365 ILE->setInit(Init, DIE);
366 else {
367 ILE->updateInit(SemaRef.Context, Init, DIE);
368 RequiresSecondPass = true;
369 }
370 return;
371 }
372
Douglas Gregord6d37de2009-12-22 00:05:34 +0000373 // FIXME: We probably don't need to handle references
374 // specially here, since value-initialization of references is
375 // handled in InitializationSequence.
376 if (Field->getType()->isReferenceType()) {
377 // C++ [dcl.init.aggr]p9:
378 // If an incomplete or empty initializer-list leaves a
379 // member of reference type uninitialized, the program is
380 // ill-formed.
381 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
382 << Field->getType()
383 << ILE->getSyntacticForm()->getSourceRange();
384 SemaRef.Diag(Field->getLocation(),
385 diag::note_uninit_reference_member);
386 hadError = true;
387 return;
388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000389
Douglas Gregord6d37de2009-12-22 00:05:34 +0000390 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
391 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000392 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000393 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000394 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000395 hadError = true;
396 return;
397 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398
John McCall60d7b3a2010-08-24 06:29:42 +0000399 ExprResult MemberInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000400 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000401 if (MemberInit.isInvalid()) {
402 hadError = true;
403 return;
404 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000405
Douglas Gregord6d37de2009-12-22 00:05:34 +0000406 if (hadError) {
407 // Do nothing
408 } else if (Init < NumInits) {
409 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000410 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000411 // Value-initialization requires a constructor call, so
412 // extend the initializer list to include the constructor
413 // call and make a note that we'll need to take another pass
414 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000415 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000416 RequiresSecondPass = true;
417 }
418 } else if (InitListExpr *InnerILE
419 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000420 FillInValueInitializations(MemberEntity, InnerILE,
421 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000422}
423
Douglas Gregor4c678342009-01-28 21:54:33 +0000424/// Recursively replaces NULL values within the given initializer list
425/// with expressions that perform value-initialization of the
426/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000427void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000428InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
429 InitListExpr *ILE,
430 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000431 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000432 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000433 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000434 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000435 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Ted Kremenek6217b802009-07-29 21:53:49 +0000437 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000438 const RecordDecl *RDecl = RType->getDecl();
439 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000440 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
441 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000442 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
443 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
444 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
445 FieldEnd = RDecl->field_end();
446 Field != FieldEnd; ++Field) {
447 if (Field->hasInClassInitializer()) {
448 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
449 break;
450 }
451 }
452 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000453 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000454 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
455 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000456 Field != FieldEnd; ++Field) {
457 if (Field->isUnnamedBitfield())
458 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000459
Douglas Gregord6d37de2009-12-22 00:05:34 +0000460 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000461 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000462
David Blaikie581deb32012-06-06 20:45:41 +0000463 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000464 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000465 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000466
Douglas Gregord6d37de2009-12-22 00:05:34 +0000467 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000468
Douglas Gregord6d37de2009-12-22 00:05:34 +0000469 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000470 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000471 break;
472 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000473 }
474
475 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000476 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000477
478 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000480 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000481 unsigned NumInits = ILE->getNumInits();
482 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000483 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000484 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000485 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
486 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000487 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000488 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000489 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000490 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000491 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000492 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000493 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000494 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000495 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000496
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000497
Douglas Gregor87fd7032009-02-02 17:43:21 +0000498 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000499 if (hadError)
500 return;
501
Anders Carlssond3d824d2010-01-23 04:34:47 +0000502 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
503 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000504 ElementEntity.setElementIndex(Init);
505
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000506 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
507 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000508 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
509 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000510 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000511 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000512 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000513 hadError = true;
514 return;
515 }
516
John McCall60d7b3a2010-08-24 06:29:42 +0000517 ExprResult ElementInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000518 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000519 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000520 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000521 return;
522 }
523
524 if (hadError) {
525 // Do nothing
526 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000527 // For arrays, just set the expression used for value-initialization
528 // of the "holes" in the array.
529 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
530 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
531 else
532 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000533 } else {
534 // For arrays, just set the expression used for value-initialization
535 // of the rest of elements and exit.
536 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
537 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
538 return;
539 }
540
Sebastian Redl7491c492011-06-05 13:59:11 +0000541 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000542 // Value-initialization requires a constructor call, so
543 // extend the initializer list to include the constructor
544 // call and make a note that we'll need to take another pass
545 // through the initializer list.
546 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
547 RequiresSecondPass = true;
548 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000549 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000550 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000551 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000552 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000553 }
554}
555
Chris Lattner68355a52009-01-29 05:10:57 +0000556
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000557InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000558 InitListExpr *IL, QualType &T,
Richard Smith40cba902013-06-06 11:41:05 +0000559 bool VerifyOnly)
560 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000561 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000562
Richard Smithb9bf3122013-09-20 20:10:22 +0000563 FullyStructuredList =
564 getStructuredSubobjectInit(IL, 0, T, 0, 0, IL->getSourceRange());
565 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000566 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000567
Sebastian Redl14b0c192011-09-24 17:48:00 +0000568 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000569 bool RequiresSecondPass = false;
570 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000571 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000573 RequiresSecondPass);
574 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000575}
576
577int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000578 // FIXME: use a proper constant
579 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000580 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000581 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000582 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
583 }
584 return maxElements;
585}
586
587int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000588 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000589 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000590 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000591 Field = structDecl->field_begin(),
592 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000593 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000594 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 ++InitializableMembers;
596 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000597 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000598 return std::min(InitializableMembers, 1);
599 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000600}
601
Richard Smithb9bf3122013-09-20 20:10:22 +0000602/// Check whether the range of the initializer \p ParentIList from element
603/// \p Index onwards can be used to initialize an object of type \p T. Update
604/// \p Index to indicate how many elements of the list were consumed.
605///
606/// This also fills in \p StructuredList, from element \p StructuredIndex
607/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000608void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000609 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000610 QualType T, unsigned &Index,
611 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000612 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000613 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Steve Naroff0cca7492008-05-01 22:18:59 +0000615 if (T->isArrayType())
616 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000617 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000618 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000619 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000620 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000621 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000622 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000623
Eli Friedman402256f2008-05-25 13:49:22 +0000624 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000625 if (!VerifyOnly)
626 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
627 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000628 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000629 hadError = true;
630 return;
631 }
632
Douglas Gregor4c678342009-01-28 21:54:33 +0000633 // Build a structured initializer list corresponding to this subobject.
634 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000635 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
636 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000637 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000638 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000640
Douglas Gregor4c678342009-01-28 21:54:33 +0000641 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000642 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000643 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000644 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000645 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000646 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000647
Richard Smith40cba902013-06-06 11:41:05 +0000648 if (!VerifyOnly) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000649 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000650
Sebastian Redlc2235182011-10-16 18:19:28 +0000651 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000652 // Update the structured sub-object initializer so that it's ending
653 // range corresponds with the end of the last initializer it used.
654 if (EndIndex < ParentIList->getNumInits()) {
655 SourceLocation EndLoc
656 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
657 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
658 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000659
Sebastian Redlc2235182011-10-16 18:19:28 +0000660 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000661 if (T->isArrayType() || T->isRecordType()) {
662 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smith40cba902013-06-06 11:41:05 +0000663 diag::warn_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000664 << StructuredSubobjectInitList->getSourceRange()
665 << FixItHint::CreateInsertion(
666 StructuredSubobjectInitList->getLocStart(), "{")
667 << FixItHint::CreateInsertion(
668 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000670 "}");
671 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000672 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000673}
674
Richard Smithb9bf3122013-09-20 20:10:22 +0000675/// Check whether the initializer \p IList (that was written with explicit
676/// braces) can be used to initialize an object of type \p T.
677///
678/// This also fills in \p StructuredList with the fully-braced, desugared
679/// form of the initialization.
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000680void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000681 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000682 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000683 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000684 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000685 if (!VerifyOnly) {
686 SyntacticToSemantic[IList] = StructuredList;
687 StructuredList->setSyntacticForm(IList);
688 }
Richard Smithb9bf3122013-09-20 20:10:22 +0000689
690 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000691 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000692 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000693 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000694 QualType ExprTy = T;
695 if (!ExprTy->isArrayType())
696 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000697 IList->setType(ExprTy);
698 StructuredList->setType(ExprTy);
699 }
Eli Friedman638e1442008-05-25 13:22:35 +0000700 if (hadError)
701 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000702
Eli Friedman638e1442008-05-25 13:22:35 +0000703 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000704 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000705 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000706 if (SemaRef.getLangOpts().CPlusPlus ||
707 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000708 IList->getType()->isVectorType())) {
709 hadError = true;
710 }
711 return;
712 }
713
Eli Friedmane5408582009-05-29 20:20:05 +0000714 if (StructuredIndex == 1 &&
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000715 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
716 SIF_None) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000717 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000718 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000719 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000720 hadError = true;
721 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000722 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000723 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000724 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000725 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000726 // Don't complain for incomplete types, since we'll get an error
727 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000728 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000729 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000730 CurrentObjectType->isArrayType()? 0 :
731 CurrentObjectType->isVectorType()? 1 :
732 CurrentObjectType->isScalarType()? 2 :
733 CurrentObjectType->isUnionType()? 3 :
734 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000735
736 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000737 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000738 DK = diag::err_excess_initializers;
739 hadError = true;
740 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000741 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000742 DK = diag::err_excess_initializers;
743 hadError = true;
744 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000745
Chris Lattner08202542009-02-24 22:50:46 +0000746 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000747 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000748 }
749 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000750
Sebastian Redl14b0c192011-09-24 17:48:00 +0000751 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
752 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000753 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000754 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000755 << FixItHint::CreateRemoval(IList->getLocStart())
756 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000757}
758
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000759void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000760 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000761 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000762 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000763 unsigned &Index,
764 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000765 unsigned &StructuredIndex,
766 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000767 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
768 // Explicitly braced initializer for complex type can be real+imaginary
769 // parts.
770 CheckComplexType(Entity, IList, DeclType, Index,
771 StructuredList, StructuredIndex);
772 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000773 CheckScalarType(Entity, IList, DeclType, Index,
774 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000775 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000776 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000777 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000778 } else if (DeclType->isRecordType()) {
779 assert(DeclType->isAggregateType() &&
780 "non-aggregate records should be handed in CheckSubElementType");
781 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
782 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
783 SubobjectIsDesignatorContext, Index,
784 StructuredList, StructuredIndex,
785 TopLevelObject);
786 } else if (DeclType->isArrayType()) {
787 llvm::APSInt Zero(
788 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
789 false);
790 CheckArrayType(Entity, IList, DeclType, Zero,
791 SubobjectIsDesignatorContext, Index,
792 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000793 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
794 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000795 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000796 if (!VerifyOnly)
797 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
798 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000799 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000800 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000801 CheckReferenceType(Entity, IList, DeclType, Index,
802 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000803 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000804 if (!VerifyOnly)
805 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
806 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000807 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000808 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000809 if (!VerifyOnly)
810 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
811 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000812 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000813 }
814}
815
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000816void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000817 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000818 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000819 unsigned &Index,
820 InitListExpr *StructuredList,
821 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000822 Expr *expr = IList->getInit(Index);
Richard Smith6242a452013-05-31 02:56:17 +0000823
824 if (ElemType->isReferenceType())
825 return CheckReferenceType(Entity, IList, ElemType, Index,
826 StructuredList, StructuredIndex);
827
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000828 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000829 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smithb9bf3122013-09-20 20:10:22 +0000830 InitListExpr *InnerStructuredList
Richard Smith20599392012-07-07 08:35:56 +0000831 = getStructuredSubobjectInit(IList, Index, ElemType,
832 StructuredList, StructuredIndex,
833 SubInitList->getSourceRange());
Richard Smithb9bf3122013-09-20 20:10:22 +0000834 CheckExplicitInitList(Entity, SubInitList, ElemType,
835 InnerStructuredList);
Richard Smith20599392012-07-07 08:35:56 +0000836 ++StructuredIndex;
837 ++Index;
838 return;
839 }
840 assert(SemaRef.getLangOpts().CPlusPlus &&
841 "non-aggregate records are only possible in C++");
842 // C++ initialization is handled later.
843 }
844
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000845 // FIXME: Need to handle atomic aggregate types with implicit init lists.
846 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCallfef8b342011-02-21 07:57:55 +0000847 return CheckScalarType(Entity, IList, ElemType, Index,
848 StructuredList, StructuredIndex);
Anders Carlssond28b4282009-08-27 17:18:13 +0000849
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000850 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
851 ElemType->isArrayType()) && "Unexpected type");
852
John McCallfef8b342011-02-21 07:57:55 +0000853 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
854 // arrayType can be incomplete if we're initializing a flexible
855 // array member. There's nothing we can do with the completed
856 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000857
Hans Wennborg0ff50742013-05-15 11:03:04 +0000858 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000859 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000860 CheckStringInit(expr, ElemType, arrayType, SemaRef);
861 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000862 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000863 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000864 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000865 }
John McCallfef8b342011-02-21 07:57:55 +0000866
867 // Fall through for subaggregate initialization.
868
David Blaikie4e4d0842012-03-11 07:00:24 +0000869 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000870 // C++ [dcl.init.aggr]p12:
871 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000872 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000873 // an initializer-list. If the initializer can initialize a
874 // member, the member is initialized. [...]
875
876 // FIXME: Better EqualLoc?
877 InitializationKind Kind =
878 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000879 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000880
881 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000882 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000883 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000884 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000885 if (Result.isInvalid())
886 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000887
Sebastian Redl14b0c192011-09-24 17:48:00 +0000888 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000889 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000890 }
John McCallfef8b342011-02-21 07:57:55 +0000891 ++Index;
892 return;
893 }
894
895 // Fall through for subaggregate initialization
896 } else {
897 // C99 6.7.8p13:
898 //
899 // The initializer for a structure or union object that has
900 // automatic storage duration shall be either an initializer
901 // list as described below, or a single expression that has
902 // compatible structure or union type. In the latter case, the
903 // initial value of the object, including unnamed members, is
904 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000905 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000906 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000907 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
908 !VerifyOnly)
Eli Friedman08f0bbc2013-09-17 04:07:04 +0000909 != Sema::Incompatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000910 if (ExprRes.isInvalid())
911 hadError = true;
912 else {
913 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000914 if (ExprRes.isInvalid())
915 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000916 }
917 UpdateStructuredListElement(StructuredList, StructuredIndex,
918 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000919 ++Index;
920 return;
921 }
John Wiegley429bb272011-04-08 18:41:53 +0000922 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000923 // Fall through for subaggregate initialization
924 }
925
926 // C++ [dcl.init.aggr]p12:
927 //
928 // [...] Otherwise, if the member is itself a non-empty
929 // subaggregate, brace elision is assumed and the initializer is
930 // considered for the initialization of the first member of
931 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000932 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000933 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000934 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
935 StructuredIndex);
936 ++StructuredIndex;
937 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000938 if (!VerifyOnly) {
939 // We cannot initialize this element, so let
940 // PerformCopyInitialization produce the appropriate diagnostic.
941 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
942 SemaRef.Owned(expr),
943 /*TopLevelOfInitList=*/true);
944 }
John McCallfef8b342011-02-21 07:57:55 +0000945 hadError = true;
946 ++Index;
947 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000948 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000949}
950
Eli Friedman0c706c22011-09-19 23:17:44 +0000951void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
952 InitListExpr *IList, QualType DeclType,
953 unsigned &Index,
954 InitListExpr *StructuredList,
955 unsigned &StructuredIndex) {
956 assert(Index == 0 && "Index in explicit init list must be zero");
957
958 // As an extension, clang supports complex initializers, which initialize
959 // a complex number component-wise. When an explicit initializer list for
960 // a complex number contains two two initializers, this extension kicks in:
961 // it exepcts the initializer list to contain two elements convertible to
962 // the element type of the complex type. The first element initializes
963 // the real part, and the second element intitializes the imaginary part.
964
965 if (IList->getNumInits() != 2)
966 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
967 StructuredIndex);
968
969 // This is an extension in C. (The builtin _Complex type does not exist
970 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000971 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000972 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
973 << IList->getSourceRange();
974
975 // Initialize the complex number.
976 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
977 InitializedEntity ElementEntity =
978 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
979
980 for (unsigned i = 0; i < 2; ++i) {
981 ElementEntity.setElementIndex(Index);
982 CheckSubElementType(ElementEntity, IList, elementType, Index,
983 StructuredList, StructuredIndex);
984 }
985}
986
987
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000988void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000989 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000990 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000991 InitListExpr *StructuredList,
992 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000993 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000994 if (!VerifyOnly)
995 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000996 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000997 diag::warn_cxx98_compat_empty_scalar_initializer :
998 diag::err_empty_scalar_initializer)
999 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +00001000 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +00001001 ++Index;
1002 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +00001003 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001004 }
John McCallb934c2d2010-11-11 00:46:36 +00001005
1006 Expr *expr = IList->getInit(Index);
1007 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001008 if (!VerifyOnly)
1009 SemaRef.Diag(SubIList->getLocStart(),
1010 diag::warn_many_braces_around_scalar_init)
1011 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001012
1013 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1014 StructuredIndex);
1015 return;
1016 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001017 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001018 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001019 diag::err_designator_for_scalar_init)
1020 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001021 hadError = true;
1022 ++Index;
1023 ++StructuredIndex;
1024 return;
1025 }
1026
Sebastian Redl14b0c192011-09-24 17:48:00 +00001027 if (VerifyOnly) {
1028 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1029 hadError = true;
1030 ++Index;
1031 return;
1032 }
1033
John McCallb934c2d2010-11-11 00:46:36 +00001034 ExprResult Result =
1035 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001036 SemaRef.Owned(expr),
1037 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001038
1039 Expr *ResultExpr = 0;
1040
1041 if (Result.isInvalid())
1042 hadError = true; // types weren't compatible.
1043 else {
1044 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045
John McCallb934c2d2010-11-11 00:46:36 +00001046 if (ResultExpr != expr) {
1047 // The type was promoted, update initializer list.
1048 IList->setInit(Index, ResultExpr);
1049 }
1050 }
1051 if (hadError)
1052 ++StructuredIndex;
1053 else
1054 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1055 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001056}
1057
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001058void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1059 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001060 unsigned &Index,
1061 InitListExpr *StructuredList,
1062 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001063 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001064 // FIXME: It would be wonderful if we could point at the actual member. In
1065 // general, it would be useful to pass location information down the stack,
1066 // so that we know the location (or decl) of the "current object" being
1067 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001068 if (!VerifyOnly)
1069 SemaRef.Diag(IList->getLocStart(),
1070 diag::err_init_reference_member_uninitialized)
1071 << DeclType
1072 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001073 hadError = true;
1074 ++Index;
1075 ++StructuredIndex;
1076 return;
1077 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001078
1079 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001080 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001081 if (!VerifyOnly)
1082 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1083 << DeclType << IList->getSourceRange();
1084 hadError = true;
1085 ++Index;
1086 ++StructuredIndex;
1087 return;
1088 }
1089
1090 if (VerifyOnly) {
1091 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1092 hadError = true;
1093 ++Index;
1094 return;
1095 }
1096
1097 ExprResult Result =
1098 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1099 SemaRef.Owned(expr),
1100 /*TopLevelOfInitList=*/true);
1101
1102 if (Result.isInvalid())
1103 hadError = true;
1104
1105 expr = Result.takeAs<Expr>();
1106 IList->setInit(Index, expr);
1107
1108 if (hadError)
1109 ++StructuredIndex;
1110 else
1111 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1112 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001113}
1114
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001115void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001116 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001117 unsigned &Index,
1118 InitListExpr *StructuredList,
1119 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001120 const VectorType *VT = DeclType->getAs<VectorType>();
1121 unsigned maxElements = VT->getNumElements();
1122 unsigned numEltsInit = 0;
1123 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001124
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001125 if (Index >= IList->getNumInits()) {
1126 // Make sure the element type can be value-initialized.
1127 if (VerifyOnly)
1128 CheckValueInitializable(
1129 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1130 return;
1131 }
1132
David Blaikie4e4d0842012-03-11 07:00:24 +00001133 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001134 // If the initializing element is a vector, try to copy-initialize
1135 // instead of breaking it apart (which is doomed to failure anyway).
1136 Expr *Init = IList->getInit(Index);
1137 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001138 if (VerifyOnly) {
1139 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1140 hadError = true;
1141 ++Index;
1142 return;
1143 }
1144
John McCall20e047a2010-10-30 00:11:39 +00001145 ExprResult Result =
1146 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001147 SemaRef.Owned(Init),
1148 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001149
1150 Expr *ResultExpr = 0;
1151 if (Result.isInvalid())
1152 hadError = true; // types weren't compatible.
1153 else {
1154 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001155
John McCall20e047a2010-10-30 00:11:39 +00001156 if (ResultExpr != Init) {
1157 // The type was promoted, update initializer list.
1158 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001159 }
1160 }
John McCall20e047a2010-10-30 00:11:39 +00001161 if (hadError)
1162 ++StructuredIndex;
1163 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001164 UpdateStructuredListElement(StructuredList, StructuredIndex,
1165 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001166 ++Index;
1167 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001168 }
Mike Stump1eb44332009-09-09 15:08:12 +00001169
John McCall20e047a2010-10-30 00:11:39 +00001170 InitializedEntity ElementEntity =
1171 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001172
John McCall20e047a2010-10-30 00:11:39 +00001173 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1174 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001175 if (Index >= IList->getNumInits()) {
1176 if (VerifyOnly)
1177 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001178 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001180
John McCall20e047a2010-10-30 00:11:39 +00001181 ElementEntity.setElementIndex(Index);
1182 CheckSubElementType(ElementEntity, IList, elementType, Index,
1183 StructuredList, StructuredIndex);
1184 }
1185 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001186 }
John McCall20e047a2010-10-30 00:11:39 +00001187
1188 InitializedEntity ElementEntity =
1189 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001190
John McCall20e047a2010-10-30 00:11:39 +00001191 // OpenCL initializers allows vectors to be constructed from vectors.
1192 for (unsigned i = 0; i < maxElements; ++i) {
1193 // Don't attempt to go past the end of the init list
1194 if (Index >= IList->getNumInits())
1195 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001196
John McCall20e047a2010-10-30 00:11:39 +00001197 ElementEntity.setElementIndex(Index);
1198
1199 QualType IType = IList->getInit(Index)->getType();
1200 if (!IType->isVectorType()) {
1201 CheckSubElementType(ElementEntity, IList, elementType, Index,
1202 StructuredList, StructuredIndex);
1203 ++numEltsInit;
1204 } else {
1205 QualType VecType;
1206 const VectorType *IVT = IType->getAs<VectorType>();
1207 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001208
John McCall20e047a2010-10-30 00:11:39 +00001209 if (IType->isExtVectorType())
1210 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1211 else
1212 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001213 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001214 CheckSubElementType(ElementEntity, IList, VecType, Index,
1215 StructuredList, StructuredIndex);
1216 numEltsInit += numIElts;
1217 }
1218 }
1219
1220 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001221 if (numEltsInit != maxElements) {
1222 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001223 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001224 diag::err_vector_incorrect_num_initializers)
1225 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1226 hadError = true;
1227 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001228}
1229
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001230void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001231 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001232 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001233 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001234 unsigned &Index,
1235 InitListExpr *StructuredList,
1236 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001237 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1238
Steve Naroff0cca7492008-05-01 22:18:59 +00001239 // Check for the special-case of initializing an array with a string.
1240 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001241 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1242 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001243 // We place the string literal directly into the resulting
1244 // initializer list. This is the only place where the structure
1245 // of the structured initializer list doesn't match exactly,
1246 // because doing so would involve allocating one character
1247 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001248 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001249 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1250 UpdateStructuredListElement(StructuredList, StructuredIndex,
1251 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001252 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1253 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001254 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001255 return;
1256 }
1257 }
John McCallce6c9b72011-02-21 07:22:22 +00001258 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001259 // Check for VLAs; in standard C it would be possible to check this
1260 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1261 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001262 if (!VerifyOnly)
1263 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1264 diag::err_variable_object_no_init)
1265 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001266 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001267 ++Index;
1268 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001269 return;
1270 }
1271
Douglas Gregor05c13a32009-01-22 00:58:24 +00001272 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001273 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1274 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001275 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001276 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001277 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001278 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001279 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001280 maxElementsKnown = true;
1281 }
1282
John McCallce6c9b72011-02-21 07:22:22 +00001283 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001284 while (Index < IList->getNumInits()) {
1285 Expr *Init = IList->getInit(Index);
1286 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001287 // If we're not the subobject that matches up with the '{' for
1288 // the designator, we shouldn't be handling the
1289 // designator. Return immediately.
1290 if (!SubobjectIsDesignatorContext)
1291 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001292
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001293 // Handle this designated initializer. elementIndex will be
1294 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001295 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001296 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001297 StructuredList, StructuredIndex, true,
1298 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001299 hadError = true;
1300 continue;
1301 }
1302
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001303 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001304 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001305 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001306 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001307 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001308
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001309 // If the array is of incomplete type, keep track of the number of
1310 // elements in the initializer.
1311 if (!maxElementsKnown && elementIndex > maxElements)
1312 maxElements = elementIndex;
1313
Douglas Gregor05c13a32009-01-22 00:58:24 +00001314 continue;
1315 }
1316
1317 // If we know the maximum number of elements, and we've already
1318 // hit it, stop consuming elements in the initializer list.
1319 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001320 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001321
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001322 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001323 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001324 Entity);
1325 // Check this element.
1326 CheckSubElementType(ElementEntity, IList, elementType, Index,
1327 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001328 ++elementIndex;
1329
1330 // If the array is of incomplete type, keep track of the number of
1331 // elements in the initializer.
1332 if (!maxElementsKnown && elementIndex > maxElements)
1333 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001334 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001335 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001336 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001337 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001338 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001339 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001340 // Sizing an array implicitly to zero is not allowed by ISO C,
1341 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001342 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001343 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001344 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001345
Mike Stump1eb44332009-09-09 15:08:12 +00001346 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001347 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001348 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001349 if (!hadError && VerifyOnly) {
1350 // Check if there are any members of the array that get value-initialized.
1351 // If so, check if doing that is possible.
1352 // FIXME: This needs to detect holes left by designated initializers too.
1353 if (maxElementsKnown && elementIndex < maxElements)
1354 CheckValueInitializable(InitializedEntity::InitializeElement(
1355 SemaRef.Context, 0, Entity));
1356 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001357}
1358
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001359bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1360 Expr *InitExpr,
1361 FieldDecl *Field,
1362 bool TopLevelObject) {
1363 // Handle GNU flexible array initializers.
1364 unsigned FlexArrayDiag;
1365 if (isa<InitListExpr>(InitExpr) &&
1366 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1367 // Empty flexible array init always allowed as an extension
1368 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001369 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001370 // Disallow flexible array init in C++; it is not required for gcc
1371 // compatibility, and it needs work to IRGen correctly in general.
1372 FlexArrayDiag = diag::err_flexible_array_init;
1373 } else if (!TopLevelObject) {
1374 // Disallow flexible array init on non-top-level object
1375 FlexArrayDiag = diag::err_flexible_array_init;
1376 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1377 // Disallow flexible array init on anything which is not a variable.
1378 FlexArrayDiag = diag::err_flexible_array_init;
1379 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1380 // Disallow flexible array init on local variables.
1381 FlexArrayDiag = diag::err_flexible_array_init;
1382 } else {
1383 // Allow other cases.
1384 FlexArrayDiag = diag::ext_flexible_array_init;
1385 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001386
1387 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001388 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001389 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001390 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001391 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1392 << Field;
1393 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001394
1395 return FlexArrayDiag != diag::ext_flexible_array_init;
1396}
1397
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001398void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001399 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001400 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001401 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001402 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001403 unsigned &Index,
1404 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001405 unsigned &StructuredIndex,
1406 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001407 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Eli Friedmanb85f7072008-05-19 19:16:24 +00001409 // If the record is invalid, some of it's members are invalid. To avoid
1410 // confusion, we forgo checking the intializer for the entire record.
1411 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001412 // Assume it was supposed to consume a single initializer.
1413 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001414 hadError = true;
1415 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001416 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001417
1418 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001419 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001420
1421 // If there's a default initializer, use it.
1422 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1423 if (VerifyOnly)
1424 return;
1425 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1426 Field != FieldEnd; ++Field) {
1427 if (Field->hasInClassInitializer()) {
1428 StructuredList->setInitializedFieldInUnion(*Field);
1429 // FIXME: Actually build a CXXDefaultInitExpr?
1430 return;
1431 }
1432 }
1433 }
1434
1435 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001436 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1437 Field != FieldEnd; ++Field) {
1438 if (Field->getDeclName()) {
1439 if (VerifyOnly)
1440 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001441 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001442 else
David Blaikie581deb32012-06-06 20:45:41 +00001443 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001444 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001445 }
1446 }
1447 return;
1448 }
1449
Douglas Gregor05c13a32009-01-22 00:58:24 +00001450 // If structDecl is a forward declaration, this loop won't do
1451 // anything except look at designated initializers; That's okay,
1452 // because an error should get printed out elsewhere. It might be
1453 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001454 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001455 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001456 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001457 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001458 while (Index < IList->getNumInits()) {
1459 Expr *Init = IList->getInit(Index);
1460
1461 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001462 // If we're not the subobject that matches up with the '{' for
1463 // the designator, we shouldn't be handling the
1464 // designator. Return immediately.
1465 if (!SubobjectIsDesignatorContext)
1466 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001467
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001468 // Handle this designated initializer. Field will be updated to
1469 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001470 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001471 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001472 StructuredList, StructuredIndex,
1473 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001474 hadError = true;
1475
Douglas Gregordfb5e592009-02-12 19:00:39 +00001476 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001477
1478 // Disable check for missing fields when designators are used.
1479 // This matches gcc behaviour.
1480 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001481 continue;
1482 }
1483
1484 if (Field == FieldEnd) {
1485 // We've run out of fields. We're done.
1486 break;
1487 }
1488
Douglas Gregordfb5e592009-02-12 19:00:39 +00001489 // We've already initialized a member of a union. We're done.
1490 if (InitializedSomething && DeclType->isUnionType())
1491 break;
1492
Douglas Gregor44b43212008-12-11 16:49:14 +00001493 // If we've hit the flexible array member at the end, we're done.
1494 if (Field->getType()->isIncompleteArrayType())
1495 break;
1496
Douglas Gregor0bb76892009-01-29 16:53:55 +00001497 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001498 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001499 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001500 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001501 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001502
Douglas Gregor54001c12011-06-29 21:51:31 +00001503 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001504 bool InvalidUse;
1505 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001506 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001507 else
David Blaikie581deb32012-06-06 20:45:41 +00001508 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001509 IList->getInit(Index)->getLocStart());
1510 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001511 ++Index;
1512 ++Field;
1513 hadError = true;
1514 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001515 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001516
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001517 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001518 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001519 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1520 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001521 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001522
Sebastian Redl14b0c192011-09-24 17:48:00 +00001523 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001524 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001525 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001526 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001527
1528 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001529 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001530
John McCall80639de2010-03-11 19:32:38 +00001531 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001532 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1533 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1534 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001535 // It is possible we have one or more unnamed bitfields remaining.
1536 // Find first (if any) named field and emit warning.
1537 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1538 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001539 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001540 SemaRef.Diag(IList->getSourceRange().getEnd(),
1541 diag::warn_missing_field_initializers) << it->getName();
1542 break;
1543 }
1544 }
1545 }
1546
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001547 // Check that any remaining fields can be value-initialized.
1548 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1549 !Field->getType()->isIncompleteArrayType()) {
1550 // FIXME: Should check for holes left by designated initializers too.
1551 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001552 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001553 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001554 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001555 }
1556 }
1557
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001559 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001560 return;
1561
David Blaikie581deb32012-06-06 20:45:41 +00001562 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001563 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001564 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001565 ++Index;
1566 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001567 }
1568
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001569 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001570 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001571
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001572 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001573 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001574 StructuredList, StructuredIndex);
1575 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001576 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001577 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001578}
Steve Naroff0cca7492008-05-01 22:18:59 +00001579
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001580/// \brief Expand a field designator that refers to a member of an
1581/// anonymous struct or union into a series of field designators that
1582/// refers to the field within the appropriate subobject.
1583///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001584static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001585 DesignatedInitExpr *DIE,
1586 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001587 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001588 typedef DesignatedInitExpr::Designator Designator;
1589
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001590 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001591 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001592 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1593 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1594 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001595 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001596 DIE->getDesignator(DesigIdx)->getDotLoc(),
1597 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1598 else
1599 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1600 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001601 assert(isa<FieldDecl>(*PI));
1602 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001603 }
1604
1605 // Expand the current designator into the set of replacement
1606 // designators, so we have a full subobject path down to where the
1607 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001608 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001609 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001610}
Mike Stump1eb44332009-09-09 15:08:12 +00001611
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001612/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001613/// corresponds to FieldName.
1614static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1615 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001616 if (!FieldName)
1617 return 0;
1618
Francois Picheta0e27f02010-12-22 03:46:10 +00001619 assert(AnonField->isAnonymousStructOrUnion());
1620 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001621 while (IndirectFieldDecl *IF =
1622 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001623 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001624 return IF;
1625 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001626 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001627 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001628}
1629
Sebastian Redl14b0c192011-09-24 17:48:00 +00001630static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1631 DesignatedInitExpr *DIE) {
1632 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1633 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1634 for (unsigned I = 0; I < NumIndexExprs; ++I)
1635 IndexExprs[I] = DIE->getSubExpr(I + 1);
1636 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001637 DIE->size(), IndexExprs,
1638 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001639 DIE->usesGNUSyntax(), DIE->getInit());
1640}
1641
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001642namespace {
1643
1644// Callback to only accept typo corrections that are for field members of
1645// the given struct or union.
1646class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1647 public:
1648 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1649 : Record(RD) {}
1650
1651 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1652 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1653 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1654 }
1655
1656 private:
1657 RecordDecl *Record;
1658};
1659
1660}
1661
Douglas Gregor05c13a32009-01-22 00:58:24 +00001662/// @brief Check the well-formedness of a C99 designated initializer.
1663///
1664/// Determines whether the designated initializer @p DIE, which
1665/// resides at the given @p Index within the initializer list @p
1666/// IList, is well-formed for a current object of type @p DeclType
1667/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001668/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001669/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001670///
1671/// @param IList The initializer list in which this designated
1672/// initializer occurs.
1673///
Douglas Gregor71199712009-04-15 04:56:10 +00001674/// @param DIE The designated initializer expression.
1675///
1676/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001677///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001678/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001679/// into which the designation in @p DIE should refer.
1680///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001681/// @param NextField If non-NULL and the first designator in @p DIE is
1682/// a field, this will be set to the field declaration corresponding
1683/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001684///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001685/// @param NextElementIndex If non-NULL and the first designator in @p
1686/// DIE is an array designator or GNU array-range designator, this
1687/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001688///
1689/// @param Index Index into @p IList where the designated initializer
1690/// @p DIE occurs.
1691///
Douglas Gregor4c678342009-01-28 21:54:33 +00001692/// @param StructuredList The initializer list expression that
1693/// describes all of the subobject initializers in the order they'll
1694/// actually be initialized.
1695///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001696/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001697bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001698InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001699 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001700 DesignatedInitExpr *DIE,
1701 unsigned DesigIdx,
1702 QualType &CurrentObjectType,
1703 RecordDecl::field_iterator *NextField,
1704 llvm::APSInt *NextElementIndex,
1705 unsigned &Index,
1706 InitListExpr *StructuredList,
1707 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001708 bool FinishSubobjectInit,
1709 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001710 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001711 // Check the actual initialization for the designated object type.
1712 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001713
1714 // Temporarily remove the designator expression from the
1715 // initializer list that the child calls see, so that we don't try
1716 // to re-process the designator.
1717 unsigned OldIndex = Index;
1718 IList->setInit(OldIndex, DIE->getInit());
1719
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001720 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001721 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001722
1723 // Restore the designated initializer expression in the syntactic
1724 // form of the initializer list.
1725 if (IList->getInit(OldIndex) != DIE->getInit())
1726 DIE->setInit(IList->getInit(OldIndex));
1727 IList->setInit(OldIndex, DIE);
1728
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001729 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001730 }
1731
Douglas Gregor71199712009-04-15 04:56:10 +00001732 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001733 bool IsFirstDesignator = (DesigIdx == 0);
1734 if (!VerifyOnly) {
1735 assert((IsFirstDesignator || StructuredList) &&
1736 "Need a non-designated initializer list to start from");
1737
1738 // Determine the structural initializer list that corresponds to the
1739 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001740 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001741 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1742 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001743 SourceRange(D->getLocStart(),
1744 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001745 assert(StructuredList && "Expected a structured initializer list");
1746 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001747
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001748 if (D->isFieldDesignator()) {
1749 // C99 6.7.8p7:
1750 //
1751 // If a designator has the form
1752 //
1753 // . identifier
1754 //
1755 // then the current object (defined below) shall have
1756 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001757 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001758 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001759 if (!RT) {
1760 SourceLocation Loc = D->getDotLoc();
1761 if (Loc.isInvalid())
1762 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001763 if (!VerifyOnly)
1764 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001765 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001766 ++Index;
1767 return true;
1768 }
1769
Douglas Gregor4c678342009-01-28 21:54:33 +00001770 // Note: we perform a linear search of the fields here, despite
1771 // the fact that we have a faster lookup method, because we always
1772 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001773 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001774 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001775 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001776 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001777 Field = RT->getDecl()->field_begin(),
1778 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 for (; Field != FieldEnd; ++Field) {
1780 if (Field->isUnnamedBitfield())
1781 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782
Francois Picheta0e27f02010-12-22 03:46:10 +00001783 // If we find a field representing an anonymous field, look in the
1784 // IndirectFieldDecl that follow for the designated initializer.
1785 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1786 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001787 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001788 // In verify mode, don't modify the original.
1789 if (VerifyOnly)
1790 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001791 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1792 D = DIE->getDesignator(DesigIdx);
1793 break;
1794 }
1795 }
David Blaikie581deb32012-06-06 20:45:41 +00001796 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001797 break;
1798 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001799 break;
1800
1801 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001802 }
1803
Douglas Gregor4c678342009-01-28 21:54:33 +00001804 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001805 if (VerifyOnly) {
1806 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001807 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001808 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001809
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001810 // There was no normal field in the struct with the designated
1811 // name. Perform another lookup for this name, which may find
1812 // something that we can't designate (e.g., a member function),
1813 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001814 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001815 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001816 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001817 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001818 // Name lookup didn't find anything. Determine whether this
1819 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001820 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smith2d670972013-08-17 00:46:16 +00001821 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1822 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1823 Sema::LookupMemberName, /*Scope=*/ 0, /*SS=*/ 0, Validator,
1824 RT->getDecl())) {
1825 SemaRef.diagnoseTypo(
1826 Corrected,
1827 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1828 << FieldName << CurrentObjectType);
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001829 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramera41ee492011-09-25 02:41:26 +00001830 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001831 } else {
1832 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1833 << FieldName << CurrentObjectType;
1834 ++Index;
1835 return true;
1836 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001837 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001838
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001839 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001840 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001841 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001842 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001843 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001844 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001845 ++Index;
1846 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001847 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001848
Francois Picheta0e27f02010-12-22 03:46:10 +00001849 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001850 // The replacement field comes from typo correction; find it
1851 // in the list of fields.
1852 FieldIndex = 0;
1853 Field = RT->getDecl()->field_begin();
1854 for (; Field != FieldEnd; ++Field) {
1855 if (Field->isUnnamedBitfield())
1856 continue;
1857
David Blaikie581deb32012-06-06 20:45:41 +00001858 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001859 Field->getIdentifier() == ReplacementField->getIdentifier())
1860 break;
1861
1862 ++FieldIndex;
1863 }
1864 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001865 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001866
1867 // All of the fields of a union are located at the same place in
1868 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001869 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001870 FieldIndex = 0;
Matthew Curtis4e499522013-10-03 12:14:24 +00001871 if (!VerifyOnly) {
1872 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1873 if (CurrentField && CurrentField != *Field) {
1874 assert(StructuredList->getNumInits() == 1
1875 && "A union should never have more than one initializer!");
1876
1877 // we're about to throw away an initializer, emit warning
1878 SemaRef.Diag(D->getFieldLoc(),
1879 diag::warn_initializer_overrides)
1880 << D->getSourceRange();
1881 Expr *ExistingInit = StructuredList->getInit(0);
1882 SemaRef.Diag(ExistingInit->getLocStart(),
1883 diag::note_previous_initializer)
1884 << /*FIXME:has side effects=*/0
1885 << ExistingInit->getSourceRange();
1886
1887 // remove existing initializer
1888 StructuredList->resizeInits(SemaRef.Context, 0);
1889 StructuredList->setInitializedFieldInUnion(0);
1890 }
1891
David Blaikie581deb32012-06-06 20:45:41 +00001892 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis4e499522013-10-03 12:14:24 +00001893 }
Douglas Gregor0bb76892009-01-29 16:53:55 +00001894 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001895
Douglas Gregor54001c12011-06-29 21:51:31 +00001896 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001897 bool InvalidUse;
1898 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001899 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001900 else
David Blaikie581deb32012-06-06 20:45:41 +00001901 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001902 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001903 ++Index;
1904 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001905 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001906
Sebastian Redl14b0c192011-09-24 17:48:00 +00001907 if (!VerifyOnly) {
1908 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001909 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Sebastian Redl14b0c192011-09-24 17:48:00 +00001911 // Make sure that our non-designated initializer list has space
1912 // for a subobject corresponding to this field.
1913 if (FieldIndex >= StructuredList->getNumInits())
1914 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1915 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001916
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001917 // This designator names a flexible array member.
1918 if (Field->getType()->isIncompleteArrayType()) {
1919 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001920 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001921 // We can't designate an object within the flexible array
1922 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001923 if (!VerifyOnly) {
1924 DesignatedInitExpr::Designator *NextD
1925 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001926 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001927 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001928 << SourceRange(NextD->getLocStart(),
1929 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001930 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001931 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001932 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001933 Invalid = true;
1934 }
1935
Chris Lattner9046c222010-10-10 17:49:49 +00001936 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1937 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001938 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001939 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001940 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001941 diag::err_flexible_array_init_needs_braces)
1942 << DIE->getInit()->getSourceRange();
1943 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001944 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001945 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001946 Invalid = true;
1947 }
1948
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001949 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001950 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001951 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001952 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001953
1954 if (Invalid) {
1955 ++Index;
1956 return true;
1957 }
1958
1959 // Initialize the array.
1960 bool prevHadError = hadError;
1961 unsigned newStructuredIndex = FieldIndex;
1962 unsigned OldIndex = Index;
1963 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001964
1965 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001966 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001967 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001968 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001969
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001970 IList->setInit(OldIndex, DIE);
1971 if (hadError && !prevHadError) {
1972 ++Field;
1973 ++FieldIndex;
1974 if (NextField)
1975 *NextField = Field;
1976 StructuredIndex = FieldIndex;
1977 return true;
1978 }
1979 } else {
1980 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001981 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001982 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001983
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001984 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001985 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001986 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1987 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001988 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001989 true, false))
1990 return true;
1991 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001992
1993 // Find the position of the next field to be initialized in this
1994 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001995 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001996 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001997
1998 // If this the first designator, our caller will continue checking
1999 // the rest of this struct/class/union subobject.
2000 if (IsFirstDesignator) {
2001 if (NextField)
2002 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00002003 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002004 return false;
2005 }
2006
Douglas Gregor34e79462009-01-28 23:36:17 +00002007 if (!FinishSubobjectInit)
2008 return false;
2009
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002010 // We've already initialized something in the union; we're done.
2011 if (RT->getDecl()->isUnion())
2012 return hadError;
2013
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002014 // Check the remaining fields within this class/struct/union subobject.
2015 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002016
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002017 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002018 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002019 return hadError && !prevHadError;
2020 }
2021
2022 // C99 6.7.8p6:
2023 //
2024 // If a designator has the form
2025 //
2026 // [ constant-expression ]
2027 //
2028 // then the current object (defined below) shall have array
2029 // type and the expression shall be an integer constant
2030 // expression. If the array is of unknown size, any
2031 // nonnegative value is valid.
2032 //
2033 // Additionally, cope with the GNU extension that permits
2034 // designators of the form
2035 //
2036 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002037 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002038 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002039 if (!VerifyOnly)
2040 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2041 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002042 ++Index;
2043 return true;
2044 }
2045
2046 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00002047 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2048 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002049 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002050 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002051 DesignatedEndIndex = DesignatedStartIndex;
2052 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002053 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002054
Mike Stump1eb44332009-09-09 15:08:12 +00002055 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002056 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002057 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002058 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002059 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002060
Chris Lattnere0fd8322011-02-19 22:28:58 +00002061 // Codegen can't handle evaluating array range designators that have side
2062 // effects, because we replicate the AST value for each initialized element.
2063 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2064 // elements with something that has a side effect, so codegen can emit an
2065 // "error unsupported" error instead of miscompiling the app.
2066 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002067 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002068 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002069 }
2070
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002071 if (isa<ConstantArrayType>(AT)) {
2072 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002073 DesignatedStartIndex
2074 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002075 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002076 DesignatedEndIndex
2077 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002078 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2079 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002080 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002081 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002082 diag::err_array_designator_too_large)
2083 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2084 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002085 ++Index;
2086 return true;
2087 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002088 } else {
2089 // Make sure the bit-widths and signedness match.
2090 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002091 DesignatedEndIndex
2092 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002093 else if (DesignatedStartIndex.getBitWidth() <
2094 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002095 DesignatedStartIndex
2096 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002097 DesignatedStartIndex.setIsUnsigned(true);
2098 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002099 }
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Eli Friedman188ddb12013-06-11 21:48:11 +00002101 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2102 // We're modifying a string literal init; we have to decompose the string
2103 // so we can modify the individual characters.
2104 ASTContext &Context = SemaRef.Context;
2105 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2106
2107 // Compute the character type
2108 QualType CharTy = AT->getElementType();
2109
2110 // Compute the type of the integer literals.
2111 QualType PromotedCharTy = CharTy;
2112 if (CharTy->isPromotableIntegerType())
2113 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2114 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2115
2116 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2117 // Get the length of the string.
2118 uint64_t StrLen = SL->getLength();
2119 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2120 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2121 StructuredList->resizeInits(Context, StrLen);
2122
2123 // Build a literal for each character in the string, and put them into
2124 // the init list.
2125 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2126 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2127 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002128 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002129 if (CharTy != PromotedCharTy)
2130 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2131 Init, 0, VK_RValue);
2132 StructuredList->updateInit(Context, i, Init);
2133 }
2134 } else {
2135 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2136 std::string Str;
2137 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2138
2139 // Get the length of the string.
2140 uint64_t StrLen = Str.size();
2141 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2142 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2143 StructuredList->resizeInits(Context, StrLen);
2144
2145 // Build a literal for each character in the string, and put them into
2146 // the init list.
2147 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2148 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2149 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002150 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002151 if (CharTy != PromotedCharTy)
2152 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2153 Init, 0, VK_RValue);
2154 StructuredList->updateInit(Context, i, Init);
2155 }
2156 }
2157 }
2158
Douglas Gregor4c678342009-01-28 21:54:33 +00002159 // Make sure that our non-designated initializer list has space
2160 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002161 if (!VerifyOnly &&
2162 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002163 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002164 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002165
Douglas Gregor34e79462009-01-28 23:36:17 +00002166 // Repeatedly perform subobject initializations in the range
2167 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002168
Douglas Gregor34e79462009-01-28 23:36:17 +00002169 // Move to the next designator
2170 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2171 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002172
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002173 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002174 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002175
Douglas Gregor34e79462009-01-28 23:36:17 +00002176 while (DesignatedStartIndex <= DesignatedEndIndex) {
2177 // Recurse to check later designated subobjects.
2178 QualType ElementType = AT->getElementType();
2179 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002180
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002181 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002182 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2183 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002184 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002185 (DesignatedStartIndex == DesignatedEndIndex),
2186 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002187 return true;
2188
2189 // Move to the next index in the array that we'll be initializing.
2190 ++DesignatedStartIndex;
2191 ElementIndex = DesignatedStartIndex.getZExtValue();
2192 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002193
2194 // If this the first designator, our caller will continue checking
2195 // the rest of this array subobject.
2196 if (IsFirstDesignator) {
2197 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002198 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002199 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002200 return false;
2201 }
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Douglas Gregor34e79462009-01-28 23:36:17 +00002203 if (!FinishSubobjectInit)
2204 return false;
2205
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002206 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002207 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002208 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002209 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002210 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002211 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002212}
2213
Douglas Gregor4c678342009-01-28 21:54:33 +00002214// Get the structured initializer list for a subobject of type
2215// @p CurrentObjectType.
2216InitListExpr *
2217InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2218 QualType CurrentObjectType,
2219 InitListExpr *StructuredList,
2220 unsigned StructuredIndex,
2221 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002222 if (VerifyOnly)
2223 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002224 Expr *ExistingInit = 0;
2225 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002226 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002227 else if (StructuredIndex < StructuredList->getNumInits())
2228 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Douglas Gregor4c678342009-01-28 21:54:33 +00002230 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2231 return Result;
2232
2233 if (ExistingInit) {
2234 // We are creating an initializer list that initializes the
2235 // subobjects of the current object, but there was already an
2236 // initialization that completely initialized the current
2237 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002238 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002239 // struct X { int a, b; };
2240 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002241 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002242 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2243 // designated initializer re-initializes the whole
2244 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002245 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002246 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002247 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002248 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002249 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002250 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002251 << ExistingInit->getSourceRange();
2252 }
2253
Mike Stump1eb44332009-09-09 15:08:12 +00002254 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002255 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002256 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002257 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002258
Eli Friedman5c89c392012-02-23 02:25:10 +00002259 QualType ResultType = CurrentObjectType;
2260 if (!ResultType->isArrayType())
2261 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2262 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002263
Douglas Gregorfa219202009-03-20 23:58:33 +00002264 // Pre-allocate storage for the structured initializer list.
2265 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002266 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002267 bool GotNumInits = false;
2268 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002269 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002270 GotNumInits = true;
2271 } else if (Index < IList->getNumInits()) {
2272 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002273 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002274 GotNumInits = true;
2275 }
Douglas Gregor08457732009-03-21 18:13:52 +00002276 }
2277
Mike Stump1eb44332009-09-09 15:08:12 +00002278 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002279 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2280 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2281 NumElements = CAType->getSize().getZExtValue();
2282 // Simple heuristic so that we don't allocate a very large
2283 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002284 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002285 NumElements = 0;
2286 }
John McCall183700f2009-09-21 23:43:11 +00002287 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002288 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002289 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002290 RecordDecl *RDecl = RType->getDecl();
2291 if (RDecl->isUnion())
2292 NumElements = 1;
2293 else
Mike Stump1eb44332009-09-09 15:08:12 +00002294 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002295 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002296 }
2297
Ted Kremenek709210f2010-04-13 23:39:13 +00002298 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002299
Douglas Gregor4c678342009-01-28 21:54:33 +00002300 // Link this new initializer list into the structured initializer
2301 // lists.
2302 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002303 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002304 else {
2305 Result->setSyntacticForm(IList);
2306 SyntacticToSemantic[IList] = Result;
2307 }
2308
2309 return Result;
2310}
2311
2312/// Update the initializer at index @p StructuredIndex within the
2313/// structured initializer list to the value @p expr.
2314void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2315 unsigned &StructuredIndex,
2316 Expr *expr) {
2317 // No structured initializer list to update
2318 if (!StructuredList)
2319 return;
2320
Ted Kremenek709210f2010-04-13 23:39:13 +00002321 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2322 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002323 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002324 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002325 diag::warn_initializer_overrides)
2326 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002327 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002328 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002329 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002330 << PrevInit->getSourceRange();
2331 }
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Douglas Gregor4c678342009-01-28 21:54:33 +00002333 ++StructuredIndex;
2334}
2335
Douglas Gregor05c13a32009-01-22 00:58:24 +00002336/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002337/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002338/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002339/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002340/// failure. Returns the index expression, possibly with an implicit cast
2341/// added, on success. If everything went okay, Value will receive the
2342/// value of the constant expression.
2343static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002344CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002345 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002346
2347 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002348 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2349 if (Result.isInvalid())
2350 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002351
Chris Lattner3bf68932009-04-25 21:59:05 +00002352 if (Value.isSigned() && Value.isNegative())
2353 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002354 << Value.toString(10) << Index->getSourceRange();
2355
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002356 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002357 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002358}
2359
John McCall60d7b3a2010-08-24 06:29:42 +00002360ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002361 SourceLocation Loc,
2362 bool GNUSyntax,
2363 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002364 typedef DesignatedInitExpr::Designator ASTDesignator;
2365
2366 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002367 SmallVector<ASTDesignator, 32> Designators;
2368 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002369
2370 // Build designators and check array designator expressions.
2371 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2372 const Designator &D = Desig.getDesignator(Idx);
2373 switch (D.getKind()) {
2374 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002375 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002376 D.getFieldLoc()));
2377 break;
2378
2379 case Designator::ArrayDesignator: {
2380 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2381 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002382 if (!Index->isTypeDependent() && !Index->isValueDependent())
2383 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2384 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002385 Invalid = true;
2386 else {
2387 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002388 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002389 D.getRBracketLoc()));
2390 InitExpressions.push_back(Index);
2391 }
2392 break;
2393 }
2394
2395 case Designator::ArrayRangeDesignator: {
2396 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2397 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2398 llvm::APSInt StartValue;
2399 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002400 bool StartDependent = StartIndex->isTypeDependent() ||
2401 StartIndex->isValueDependent();
2402 bool EndDependent = EndIndex->isTypeDependent() ||
2403 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002404 if (!StartDependent)
2405 StartIndex =
2406 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2407 if (!EndDependent)
2408 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2409
2410 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002411 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002412 else {
2413 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002414 if (StartDependent || EndDependent) {
2415 // Nothing to compute.
2416 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002417 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002418 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002419 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002420
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002421 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002422 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002423 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002424 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2425 Invalid = true;
2426 } else {
2427 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002428 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002429 D.getEllipsisLoc(),
2430 D.getRBracketLoc()));
2431 InitExpressions.push_back(StartIndex);
2432 InitExpressions.push_back(EndIndex);
2433 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002434 }
2435 break;
2436 }
2437 }
2438 }
2439
2440 if (Invalid || Init.isInvalid())
2441 return ExprError();
2442
2443 // Clear out the expressions within the designation.
2444 Desig.ClearExprs(*this);
2445
2446 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002447 = DesignatedInitExpr::Create(Context,
2448 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002449 InitExpressions, Loc, GNUSyntax,
2450 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002451
David Blaikie4e4d0842012-03-11 07:00:24 +00002452 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002453 Diag(DIE->getLocStart(), diag::ext_designated_init)
2454 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002455
Douglas Gregor05c13a32009-01-22 00:58:24 +00002456 return Owned(DIE);
2457}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002458
Douglas Gregor20093b42009-12-09 23:02:17 +00002459//===----------------------------------------------------------------------===//
2460// Initialization entity
2461//===----------------------------------------------------------------------===//
2462
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002463InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002464 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002465 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002466{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002467 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2468 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002469 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002470 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002471 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002472 Type = VT->getElementType();
2473 } else {
2474 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2475 assert(CT && "Unexpected type");
2476 Kind = EK_ComplexElement;
2477 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002478 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002479}
2480
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002481InitializedEntity
2482InitializedEntity::InitializeBase(ASTContext &Context,
2483 const CXXBaseSpecifier *Base,
2484 bool IsInheritedVirtualBase) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002485 InitializedEntity Result;
2486 Result.Kind = EK_Base;
Richard Smitha4bb99c2013-06-12 21:51:50 +00002487 Result.Parent = 0;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002488 Result.Base = reinterpret_cast<uintptr_t>(Base);
2489 if (IsInheritedVirtualBase)
2490 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002491
Douglas Gregord6542d82009-12-22 15:35:07 +00002492 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002493 return Result;
2494}
2495
Douglas Gregor99a2e602009-12-16 01:38:02 +00002496DeclarationName InitializedEntity::getName() const {
2497 switch (getKind()) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002498 case EK_Parameter:
2499 case EK_Parameter_CF_Audited: {
John McCallf85e1932011-06-15 23:02:42 +00002500 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2501 return (D ? D->getDeclName() : DeclarationName());
2502 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002503
2504 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002505 case EK_Member:
2506 return VariableOrMember->getDeclName();
2507
Douglas Gregor47736542012-02-15 16:57:26 +00002508 case EK_LambdaCapture:
Bill Wendling2434dcf2013-12-05 05:25:04 +00002509 return DeclarationName(Capture.VarID);
Douglas Gregor47736542012-02-15 16:57:26 +00002510
Douglas Gregor99a2e602009-12-16 01:38:02 +00002511 case EK_Result:
2512 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002513 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002514 case EK_Temporary:
2515 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002516 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002517 case EK_ArrayElement:
2518 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002519 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002520 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002521 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002522 case EK_RelatedResult:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002523 return DeclarationName();
2524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002525
David Blaikie7530c032012-01-17 06:56:22 +00002526 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002527}
2528
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002529DeclaratorDecl *InitializedEntity::getDecl() const {
2530 switch (getKind()) {
2531 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002532 case EK_Member:
2533 return VariableOrMember;
2534
John McCallf85e1932011-06-15 23:02:42 +00002535 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002536 case EK_Parameter_CF_Audited:
John McCallf85e1932011-06-15 23:02:42 +00002537 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2538
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002539 case EK_Result:
2540 case EK_Exception:
2541 case EK_New:
2542 case EK_Temporary:
2543 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002544 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002545 case EK_ArrayElement:
2546 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002547 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002548 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002549 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002550 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002551 case EK_RelatedResult:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002552 return 0;
2553 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002554
David Blaikie7530c032012-01-17 06:56:22 +00002555 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002556}
2557
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002558bool InitializedEntity::allowsNRVO() const {
2559 switch (getKind()) {
2560 case EK_Result:
2561 case EK_Exception:
2562 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002563
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002564 case EK_Variable:
2565 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002566 case EK_Parameter_CF_Audited:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002567 case EK_Member:
2568 case EK_New:
2569 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002570 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002571 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002572 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002573 case EK_ArrayElement:
2574 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002575 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002576 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002577 case EK_LambdaCapture:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002578 case EK_RelatedResult:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002579 break;
2580 }
2581
2582 return false;
2583}
2584
Richard Smith211c8dd2013-06-05 00:46:14 +00002585unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smitha4bb99c2013-06-12 21:51:50 +00002586 assert(getParent() != this);
Richard Smith211c8dd2013-06-05 00:46:14 +00002587 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2588 for (unsigned I = 0; I != Depth; ++I)
2589 OS << "`-";
2590
2591 switch (getKind()) {
2592 case EK_Variable: OS << "Variable"; break;
2593 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002594 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2595 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002596 case EK_Result: OS << "Result"; break;
2597 case EK_Exception: OS << "Exception"; break;
2598 case EK_Member: OS << "Member"; break;
2599 case EK_New: OS << "New"; break;
2600 case EK_Temporary: OS << "Temporary"; break;
2601 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002602 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002603 case EK_Base: OS << "Base"; break;
2604 case EK_Delegating: OS << "Delegating"; break;
2605 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2606 case EK_VectorElement: OS << "VectorElement " << Index; break;
2607 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2608 case EK_BlockElement: OS << "Block"; break;
2609 case EK_LambdaCapture:
2610 OS << "LambdaCapture ";
Bill Wendling2434dcf2013-12-05 05:25:04 +00002611 OS << DeclarationName(Capture.VarID);
Richard Smith211c8dd2013-06-05 00:46:14 +00002612 break;
2613 }
2614
2615 if (Decl *D = getDecl()) {
2616 OS << " ";
2617 cast<NamedDecl>(D)->printQualifiedName(OS);
2618 }
2619
2620 OS << " '" << getType().getAsString() << "'\n";
2621
2622 return Depth + 1;
2623}
2624
2625void InitializedEntity::dump() const {
2626 dumpImpl(llvm::errs());
2627}
2628
Douglas Gregor20093b42009-12-09 23:02:17 +00002629//===----------------------------------------------------------------------===//
2630// Initialization sequence
2631//===----------------------------------------------------------------------===//
2632
2633void InitializationSequence::Step::Destroy() {
2634 switch (Kind) {
2635 case SK_ResolveAddressOfOverloadedFunction:
2636 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002637 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002638 case SK_CastDerivedToBaseLValue:
2639 case SK_BindReference:
2640 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002641 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002642 case SK_UserConversion:
2643 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002644 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002645 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002646 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002647 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002648 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002649 case SK_UnwrapInitList:
2650 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002651 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002652 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002653 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002654 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002655 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002656 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002657 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002658 case SK_PassByIndirectCopyRestore:
2659 case SK_PassByIndirectRestore:
2660 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002661 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002662 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002663 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002664 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002665
Douglas Gregor20093b42009-12-09 23:02:17 +00002666 case SK_ConversionSequence:
Richard Smith13b228d2013-09-21 21:19:19 +00002667 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor20093b42009-12-09 23:02:17 +00002668 delete ICS;
2669 }
2670}
2671
Douglas Gregorb70cf442010-03-26 20:14:36 +00002672bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002673 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002674}
2675
2676bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002677 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002678 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002679
Douglas Gregorb70cf442010-03-26 20:14:36 +00002680 switch (getFailureKind()) {
2681 case FK_TooManyInitsForReference:
2682 case FK_ArrayNeedsInitList:
2683 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002684 case FK_ArrayNeedsInitListOrWideStringLiteral:
2685 case FK_NarrowStringIntoWideCharArray:
2686 case FK_WideStringIntoCharArray:
2687 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002688 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2689 case FK_NonConstLValueReferenceBindingToTemporary:
2690 case FK_NonConstLValueReferenceBindingToUnrelated:
2691 case FK_RValueReferenceBindingToLValue:
2692 case FK_ReferenceInitDropsQualifiers:
2693 case FK_ReferenceInitFailed:
2694 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002695 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002696 case FK_TooManyInitsForScalar:
2697 case FK_ReferenceBindingToInitList:
2698 case FK_InitListBadDestinationType:
2699 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002700 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002701 case FK_ArrayTypeMismatch:
2702 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002703 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002704 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002705 case FK_PlaceholderType:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002706 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002707 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002708
Douglas Gregorb70cf442010-03-26 20:14:36 +00002709 case FK_ReferenceInitOverloadFailed:
2710 case FK_UserConversionOverloadFailed:
2711 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002712 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002713 return FailedOverloadResult == OR_Ambiguous;
2714 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002715
David Blaikie7530c032012-01-17 06:56:22 +00002716 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002717}
2718
Douglas Gregord6e44a32010-04-16 22:09:46 +00002719bool InitializationSequence::isConstructorInitialization() const {
2720 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2721}
2722
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002723void
2724InitializationSequence
2725::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2726 DeclAccessPair Found,
2727 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 Step S;
2729 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2730 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002731 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002732 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002733 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002734 Steps.push_back(S);
2735}
2736
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002737void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002738 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002739 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002740 switch (VK) {
2741 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2742 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2743 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002744 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002745 S.Type = BaseType;
2746 Steps.push_back(S);
2747}
2748
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002749void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002750 bool BindingTemporary) {
2751 Step S;
2752 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2753 S.Type = T;
2754 Steps.push_back(S);
2755}
2756
Douglas Gregor523d46a2010-04-18 07:40:54 +00002757void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2758 Step S;
2759 S.Kind = SK_ExtraneousCopyToTemporary;
2760 S.Type = T;
2761 Steps.push_back(S);
2762}
2763
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002764void
2765InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2766 DeclAccessPair FoundDecl,
2767 QualType T,
2768 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002769 Step S;
2770 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002771 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002772 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002773 S.Function.Function = Function;
2774 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002775 Steps.push_back(S);
2776}
2777
2778void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002779 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002780 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002781 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002782 switch (VK) {
2783 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002784 S.Kind = SK_QualificationConversionRValue;
2785 break;
John McCall5baba9d2010-08-25 10:28:54 +00002786 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002787 S.Kind = SK_QualificationConversionXValue;
2788 break;
John McCall5baba9d2010-08-25 10:28:54 +00002789 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002790 S.Kind = SK_QualificationConversionLValue;
2791 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002792 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002793 S.Type = Ty;
2794 Steps.push_back(S);
2795}
2796
Jordan Rose1fd1e282013-04-11 00:58:58 +00002797void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2798 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2799
2800 Step S;
2801 S.Kind = SK_LValueToRValue;
2802 S.Type = Ty;
2803 Steps.push_back(S);
2804}
2805
Douglas Gregor20093b42009-12-09 23:02:17 +00002806void InitializationSequence::AddConversionSequenceStep(
Richard Smith13b228d2013-09-21 21:19:19 +00002807 const ImplicitConversionSequence &ICS, QualType T,
2808 bool TopLevelOfInitList) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002809 Step S;
Richard Smith13b228d2013-09-21 21:19:19 +00002810 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2811 : SK_ConversionSequence;
Douglas Gregor20093b42009-12-09 23:02:17 +00002812 S.Type = T;
2813 S.ICS = new ImplicitConversionSequence(ICS);
2814 Steps.push_back(S);
2815}
2816
Douglas Gregord87b61f2009-12-10 17:56:55 +00002817void InitializationSequence::AddListInitializationStep(QualType T) {
2818 Step S;
2819 S.Kind = SK_ListInitialization;
2820 S.Type = T;
2821 Steps.push_back(S);
2822}
2823
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002824void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002825InitializationSequence
2826::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2827 AccessSpecifier Access,
2828 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002829 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002830 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002831 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002832 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2833 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002834 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002835 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002836 S.Function.Function = Constructor;
2837 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002838 Steps.push_back(S);
2839}
2840
Douglas Gregor71d17402009-12-15 00:01:57 +00002841void InitializationSequence::AddZeroInitializationStep(QualType T) {
2842 Step S;
2843 S.Kind = SK_ZeroInitialization;
2844 S.Type = T;
2845 Steps.push_back(S);
2846}
2847
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002848void InitializationSequence::AddCAssignmentStep(QualType T) {
2849 Step S;
2850 S.Kind = SK_CAssignment;
2851 S.Type = T;
2852 Steps.push_back(S);
2853}
2854
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002855void InitializationSequence::AddStringInitStep(QualType T) {
2856 Step S;
2857 S.Kind = SK_StringInit;
2858 S.Type = T;
2859 Steps.push_back(S);
2860}
2861
Douglas Gregor569c3162010-08-07 11:51:51 +00002862void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2863 Step S;
2864 S.Kind = SK_ObjCObjectConversion;
2865 S.Type = T;
2866 Steps.push_back(S);
2867}
2868
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002869void InitializationSequence::AddArrayInitStep(QualType T) {
2870 Step S;
2871 S.Kind = SK_ArrayInit;
2872 S.Type = T;
2873 Steps.push_back(S);
2874}
2875
Richard Smith0f163e92012-02-15 22:38:09 +00002876void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2877 Step S;
2878 S.Kind = SK_ParenthesizedArrayInit;
2879 S.Type = T;
2880 Steps.push_back(S);
2881}
2882
John McCallf85e1932011-06-15 23:02:42 +00002883void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2884 bool shouldCopy) {
2885 Step s;
2886 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2887 : SK_PassByIndirectRestore);
2888 s.Type = type;
2889 Steps.push_back(s);
2890}
2891
2892void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2893 Step S;
2894 S.Kind = SK_ProduceObjCObject;
2895 S.Type = T;
2896 Steps.push_back(S);
2897}
2898
Sebastian Redl2b916b82012-01-17 22:49:42 +00002899void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2900 Step S;
2901 S.Kind = SK_StdInitializerList;
2902 S.Type = T;
2903 Steps.push_back(S);
2904}
2905
Guy Benyei21f18c42013-02-07 10:55:47 +00002906void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2907 Step S;
2908 S.Kind = SK_OCLSamplerInit;
2909 S.Type = T;
2910 Steps.push_back(S);
2911}
2912
Guy Benyeie6b9d802013-01-20 12:31:11 +00002913void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2914 Step S;
2915 S.Kind = SK_OCLZeroEvent;
2916 S.Type = T;
2917 Steps.push_back(S);
2918}
2919
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002920void InitializationSequence::RewrapReferenceInitList(QualType T,
2921 InitListExpr *Syntactic) {
2922 assert(Syntactic->getNumInits() == 1 &&
2923 "Can only rewrap trivial init lists.");
2924 Step S;
2925 S.Kind = SK_UnwrapInitList;
2926 S.Type = Syntactic->getInit(0)->getType();
2927 Steps.insert(Steps.begin(), S);
2928
2929 S.Kind = SK_RewrapInitList;
2930 S.Type = T;
2931 S.WrappingSyntacticList = Syntactic;
2932 Steps.push_back(S);
2933}
2934
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002935void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002936 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002937 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002938 this->Failure = Failure;
2939 this->FailedOverloadResult = Result;
2940}
2941
2942//===----------------------------------------------------------------------===//
2943// Attempt initialization
2944//===----------------------------------------------------------------------===//
2945
John McCallf85e1932011-06-15 23:02:42 +00002946static void MaybeProduceObjCObject(Sema &S,
2947 InitializationSequence &Sequence,
2948 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002949 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002950
2951 /// When initializing a parameter, produce the value if it's marked
2952 /// __attribute__((ns_consumed)).
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002953 if (Entity.isParameterKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002954 if (!Entity.isParameterConsumed())
2955 return;
2956
2957 assert(Entity.getType()->isObjCRetainableType() &&
2958 "consuming an object of unretainable type?");
2959 Sequence.AddProduceObjCObjectStep(Entity.getType());
2960
2961 /// When initializing a return value, if the return type is a
2962 /// retainable type, then returns need to immediately retain the
2963 /// object. If an autorelease is required, it will be done at the
2964 /// last instant.
2965 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2966 if (!Entity.getType()->isObjCRetainableType())
2967 return;
2968
2969 Sequence.AddProduceObjCObjectStep(Entity.getType());
2970 }
2971}
2972
Richard Smith7c3e6152013-06-12 22:31:48 +00002973static void TryListInitialization(Sema &S,
2974 const InitializedEntity &Entity,
2975 const InitializationKind &Kind,
2976 InitListExpr *InitList,
2977 InitializationSequence &Sequence);
2978
Richard Smithf4bb8d02012-07-05 08:39:21 +00002979/// \brief When initializing from init list via constructor, handle
2980/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002981///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002982/// \return true if we have handled initialization of an object of type
2983/// std::initializer_list<T>, false otherwise.
2984static bool TryInitializerListConstruction(Sema &S,
2985 InitListExpr *List,
2986 QualType DestType,
2987 InitializationSequence &Sequence) {
2988 QualType E;
2989 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002990 return false;
2991
Richard Smith7c3e6152013-06-12 22:31:48 +00002992 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
2993 Sequence.setIncompleteTypeFailure(E);
2994 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002995 }
Richard Smith7c3e6152013-06-12 22:31:48 +00002996
2997 // Try initializing a temporary array from the init list.
2998 QualType ArrayType = S.Context.getConstantArrayType(
2999 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3000 List->getNumInits()),
3001 clang::ArrayType::Normal, 0);
3002 InitializedEntity HiddenArray =
3003 InitializedEntity::InitializeTemporary(ArrayType);
3004 InitializationKind Kind =
3005 InitializationKind::CreateDirectList(List->getExprLoc());
3006 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3007 if (Sequence)
3008 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003009 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003010}
3011
Sebastian Redl96715b22012-02-04 21:27:39 +00003012static OverloadingResult
3013ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003014 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00003015 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003016 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00003017 OverloadCandidateSet::iterator &Best,
3018 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003019 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003020 CandidateSet.clear();
3021
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003022 for (ArrayRef<NamedDecl *>::iterator
3023 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003024 NamedDecl *D = *Con;
3025 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3026 bool SuppressUserConversions = false;
3027
3028 // Find the constructor (which may be a template).
3029 CXXConstructorDecl *Constructor = 0;
3030 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3031 if (ConstructorTmpl)
3032 Constructor = cast<CXXConstructorDecl>(
3033 ConstructorTmpl->getTemplatedDecl());
3034 else {
3035 Constructor = cast<CXXConstructorDecl>(D);
3036
Richard Smith867521c2013-09-21 21:23:47 +00003037 // C++11 [over.best.ics]p4:
3038 // However, when considering the argument of a constructor or
3039 // user-defined conversion function that is a candidate:
3040 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3041 // in the second step of a class copy-initialization,
3042 // -- by 13.3.1.7 when passing the initializer list as a single
3043 // argument or when the initializer list has exactly one elementand
3044 // a conversion to some class X or reference to (possibly
3045 // cv-qualified) X is considered for the first parameter of a
3046 // constructor of X, or
3047 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3048 // only standard conversion sequences and ellipsis conversion sequences
3049 // are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003050 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003051 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00003052 SuppressUserConversions = true;
3053 }
3054
3055 if (!Constructor->isInvalidDecl() &&
3056 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003057 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003058 if (ConstructorTmpl)
3059 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003060 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003061 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00003062 else {
3063 // C++ [over.match.copy]p1:
3064 // - When initializing a temporary to be bound to the first parameter
3065 // of a constructor that takes a reference to possibly cv-qualified
3066 // T as its first argument, called with a single argument in the
3067 // context of direct-initialization, explicit conversion functions
3068 // are also considered.
3069 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003070 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00003071 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003072 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00003073 SuppressUserConversions,
3074 /*PartialOverloading=*/false,
3075 /*AllowExplicit=*/AllowExplicitConv);
3076 }
Sebastian Redl96715b22012-02-04 21:27:39 +00003077 }
3078 }
3079
3080 // Perform overload resolution and return the result.
3081 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3082}
3083
Sebastian Redl10f04a62011-12-22 14:44:04 +00003084/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3085/// enumerates the constructors of the initialized entity and performs overload
3086/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00003087/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00003088/// class type.
3089static void TryConstructorInitialization(Sema &S,
3090 const InitializedEntity &Entity,
3091 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003092 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003093 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00003094 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003095 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00003096 "InitListSyntax must come with a single initializer list argument.");
3097
Sebastian Redl10f04a62011-12-22 14:44:04 +00003098 // The type we're constructing needs to be complete.
3099 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003100 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00003101 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003102 }
3103
3104 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3105 assert(DestRecordType && "Constructor initialization requires record type");
3106 CXXRecordDecl *DestRecordDecl
3107 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3108
Sebastian Redl96715b22012-02-04 21:27:39 +00003109 // Build the candidate set directly in the initialization sequence
3110 // structure, so that it will persist if we fail.
3111 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3112
3113 // Determine whether we are allowed to call explicit constructors or
3114 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003115 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003116 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00003117
Sebastian Redl10f04a62011-12-22 14:44:04 +00003118 // - Otherwise, if T is a class type, constructors are considered. The
3119 // applicable constructors are enumerated, and the best one is chosen
3120 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00003121 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003122 // The container holding the constructors can under certain conditions
3123 // be changed while iterating (e.g. because of deserialization).
3124 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003125 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00003126
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003127 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003128 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003129 bool AsInitializerList = false;
3130
3131 // C++11 [over.match.list]p1:
3132 // When objects of non-aggregate type T are list-initialized, overload
3133 // resolution selects the constructor in two phases:
3134 // - Initially, the candidate functions are the initializer-list
3135 // constructors of the class T and the argument list consists of the
3136 // initializer list as a single argument.
3137 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003138 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003139 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003140
3141 // If the initializer list has no elements and T has a default constructor,
3142 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003143 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003144 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003145 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003146 CopyInitialization, AllowExplicit,
3147 /*OnlyListConstructor=*/true,
3148 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003149
3150 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003151 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003152 }
3153
3154 // C++11 [over.match.list]p1:
3155 // - If no viable initializer-list constructor is found, overload resolution
3156 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003157 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003158 // elements of the initializer list.
3159 if (Result == OR_No_Viable_Function) {
3160 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003161 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003162 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003163 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003164 /*OnlyListConstructors=*/false,
3165 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003166 }
3167 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003168 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003169 InitializationSequence::FK_ListConstructorOverloadFailed :
3170 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003171 Result);
3172 return;
3173 }
3174
Richard Smithf4bb8d02012-07-05 08:39:21 +00003175 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003176 // If a program calls for the default initialization of an object
3177 // of a const-qualified type T, T shall be a class type with a
3178 // user-provided default constructor.
3179 if (Kind.getKind() == InitializationKind::IK_Default &&
3180 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003181 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003182 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3183 return;
3184 }
3185
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003186 // C++11 [over.match.list]p1:
3187 // In copy-list-initialization, if an explicit constructor is chosen, the
3188 // initializer is ill-formed.
3189 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3190 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3191 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3192 return;
3193 }
3194
Sebastian Redl10f04a62011-12-22 14:44:04 +00003195 // Add the constructor initialization step. Any cv-qualification conversion is
3196 // subsumed by the initialization.
3197 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003198 Sequence.AddConstructorInitializationStep(CtorDecl,
3199 Best->FoundDecl.getAccess(),
3200 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003201 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003202}
3203
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003204static bool
3205ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3206 Expr *Initializer,
3207 QualType &SourceType,
3208 QualType &UnqualifiedSourceType,
3209 QualType UnqualifiedTargetType,
3210 InitializationSequence &Sequence) {
3211 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3212 S.Context.OverloadTy) {
3213 DeclAccessPair Found;
3214 bool HadMultipleCandidates = false;
3215 if (FunctionDecl *Fn
3216 = S.ResolveAddressOfOverloadedFunction(Initializer,
3217 UnqualifiedTargetType,
3218 false, Found,
3219 &HadMultipleCandidates)) {
3220 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3221 HadMultipleCandidates);
3222 SourceType = Fn->getType();
3223 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3224 } else if (!UnqualifiedTargetType->isRecordType()) {
3225 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3226 return true;
3227 }
3228 }
3229 return false;
3230}
3231
3232static void TryReferenceInitializationCore(Sema &S,
3233 const InitializedEntity &Entity,
3234 const InitializationKind &Kind,
3235 Expr *Initializer,
3236 QualType cv1T1, QualType T1,
3237 Qualifiers T1Quals,
3238 QualType cv2T2, QualType T2,
3239 Qualifiers T2Quals,
3240 InitializationSequence &Sequence);
3241
Richard Smithf4bb8d02012-07-05 08:39:21 +00003242static void TryValueInitialization(Sema &S,
3243 const InitializedEntity &Entity,
3244 const InitializationKind &Kind,
3245 InitializationSequence &Sequence,
3246 InitListExpr *InitList = 0);
3247
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003248/// \brief Attempt list initialization of a reference.
3249static void TryReferenceListInitialization(Sema &S,
3250 const InitializedEntity &Entity,
3251 const InitializationKind &Kind,
3252 InitListExpr *InitList,
Richard Smithb6e38082013-06-08 00:02:08 +00003253 InitializationSequence &Sequence) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003254 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003255 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003256 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3257 return;
3258 }
3259
3260 QualType DestType = Entity.getType();
3261 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3262 Qualifiers T1Quals;
3263 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3264
3265 // Reference initialization via an initializer list works thus:
3266 // If the initializer list consists of a single element that is
3267 // reference-related to the referenced type, bind directly to that element
3268 // (possibly creating temporaries).
3269 // Otherwise, initialize a temporary with the initializer list and
3270 // bind to that.
3271 if (InitList->getNumInits() == 1) {
3272 Expr *Initializer = InitList->getInit(0);
3273 QualType cv2T2 = Initializer->getType();
3274 Qualifiers T2Quals;
3275 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3276
3277 // If this fails, creating a temporary wouldn't work either.
3278 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3279 T1, Sequence))
3280 return;
3281
3282 SourceLocation DeclLoc = Initializer->getLocStart();
3283 bool dummy1, dummy2, dummy3;
3284 Sema::ReferenceCompareResult RefRelationship
3285 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3286 dummy2, dummy3);
3287 if (RefRelationship >= Sema::Ref_Related) {
3288 // Try to bind the reference here.
3289 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3290 T1Quals, cv2T2, T2, T2Quals, Sequence);
3291 if (Sequence)
3292 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3293 return;
3294 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003295
3296 // Update the initializer if we've resolved an overloaded function.
3297 if (Sequence.step_begin() != Sequence.step_end())
3298 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003299 }
3300
3301 // Not reference-related. Create a temporary and bind to that.
3302 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3303
3304 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3305 if (Sequence) {
3306 if (DestType->isRValueReferenceType() ||
3307 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3308 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3309 else
3310 Sequence.SetFailed(
3311 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3312 }
3313}
3314
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003315/// \brief Attempt list initialization (C++0x [dcl.init.list])
3316static void TryListInitialization(Sema &S,
3317 const InitializedEntity &Entity,
3318 const InitializationKind &Kind,
3319 InitListExpr *InitList,
3320 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003321 QualType DestType = Entity.getType();
3322
Sebastian Redl14b0c192011-09-24 17:48:00 +00003323 // C++ doesn't allow scalar initialization with more than one argument.
3324 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003325 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003326 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3327 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3328 return;
3329 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003330 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003331 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003332 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003333 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003334 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003335 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003336 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003337 return;
3338 }
3339
Richard Smithf4bb8d02012-07-05 08:39:21 +00003340 // C++11 [dcl.init.list]p3:
3341 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003342 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003343 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003344 // - Otherwise, if the initializer list has no elements and T is a
3345 // class type with a default constructor, the object is
3346 // value-initialized.
3347 if (InitList->getNumInits() == 0) {
3348 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003349 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003350 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3351 return;
3352 }
3353 }
3354
3355 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3356 // an initializer_list object constructed [...]
3357 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3358 return;
3359
3360 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003361 Expr *InitListAsExpr = InitList;
3362 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003363 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003364 } else
3365 Sequence.SetFailed(
3366 InitializationSequence::FK_InitListBadDestinationType);
3367 return;
3368 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003369 }
Richard Smithb390e492013-09-21 21:55:46 +00003370 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3371 InitList->getNumInits() == 1 &&
3372 InitList->getInit(0)->getType()->isRecordType()) {
3373 // - Otherwise, if the initializer list has a single element of type E
3374 // [...references are handled above...], the object or reference is
3375 // initialized from that element; if a narrowing conversion is required
3376 // to convert the element to T, the program is ill-formed.
3377 //
3378 // Per core-24034, this is direct-initialization if we were performing
3379 // direct-list-initialization and copy-initialization otherwise.
3380 // We can't use InitListChecker for this, because it always performs
3381 // copy-initialization. This only matters if we might use an 'explicit'
3382 // conversion operator, so we only need to handle the cases where the source
3383 // is of record type.
3384 InitializationKind SubKind =
3385 Kind.getKind() == InitializationKind::IK_DirectList
3386 ? InitializationKind::CreateDirect(Kind.getLocation(),
3387 InitList->getLBraceLoc(),
3388 InitList->getRBraceLoc())
3389 : Kind;
3390 Expr *SubInit[1] = { InitList->getInit(0) };
3391 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3392 /*TopLevelOfInitList*/true);
3393 if (Sequence)
3394 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3395 return;
3396 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003397
Sebastian Redl14b0c192011-09-24 17:48:00 +00003398 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00003399 DestType, /*VerifyOnly=*/true);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003400 if (CheckInitList.HadError()) {
3401 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3402 return;
3403 }
3404
3405 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003406 Sequence.AddListInitializationStep(DestType);
3407}
Douglas Gregor20093b42009-12-09 23:02:17 +00003408
3409/// \brief Try a reference initialization that involves calling a conversion
3410/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003411static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3412 const InitializedEntity &Entity,
3413 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003414 Expr *Initializer,
3415 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003416 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003417 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003418 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3419 QualType T1 = cv1T1.getUnqualifiedType();
3420 QualType cv2T2 = Initializer->getType();
3421 QualType T2 = cv2T2.getUnqualifiedType();
3422
3423 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003424 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003425 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003426 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003427 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003428 ObjCConversion,
3429 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003430 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003431 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003432 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003433 (void)ObjCLifetimeConversion;
3434
Douglas Gregor20093b42009-12-09 23:02:17 +00003435 // Build the candidate set directly in the initialization sequence
3436 // structure, so that it will persist if we fail.
3437 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3438 CandidateSet.clear();
3439
3440 // Determine whether we are allowed to call explicit constructors or
3441 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003442 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith867521c2013-09-21 21:23:47 +00003443 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3444
Douglas Gregor20093b42009-12-09 23:02:17 +00003445 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003446 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3447 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003448 // The type we're converting to is a class type. Enumerate its constructors
3449 // to see if there is a suitable conversion.
3450 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003451
David Blaikie3bc93e32012-12-19 00:45:41 +00003452 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003453 // The container holding the constructors can under certain conditions
3454 // be changed while iterating (e.g. because of deserialization).
3455 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003456 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00003457 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003458 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3459 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003460 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3461
Douglas Gregor20093b42009-12-09 23:02:17 +00003462 // Find the constructor (which may be a template).
3463 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003464 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003465 if (ConstructorTmpl)
3466 Constructor = cast<CXXConstructorDecl>(
3467 ConstructorTmpl->getTemplatedDecl());
3468 else
John McCall9aa472c2010-03-19 07:35:19 +00003469 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003470
Douglas Gregor20093b42009-12-09 23:02:17 +00003471 if (!Constructor->isInvalidDecl() &&
3472 Constructor->isConvertingConstructor(AllowExplicit)) {
3473 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003474 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003475 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003476 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003477 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003478 else
John McCall9aa472c2010-03-19 07:35:19 +00003479 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003480 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003481 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003482 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003483 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003484 }
John McCall572fc622010-08-17 07:23:57 +00003485 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3486 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003487
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003488 const RecordType *T2RecordType = 0;
3489 if ((T2RecordType = T2->getAs<RecordType>()) &&
3490 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003491 // The type we're converting from is a class type, enumerate its conversion
3492 // functions.
3493 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3494
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003495 std::pair<CXXRecordDecl::conversion_iterator,
3496 CXXRecordDecl::conversion_iterator>
3497 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3498 for (CXXRecordDecl::conversion_iterator
3499 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003500 NamedDecl *D = *I;
3501 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3502 if (isa<UsingShadowDecl>(D))
3503 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504
Douglas Gregor20093b42009-12-09 23:02:17 +00003505 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3506 CXXConversionDecl *Conv;
3507 if (ConvTemplate)
3508 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3509 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003510 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003511
Douglas Gregor20093b42009-12-09 23:02:17 +00003512 // If the conversion function doesn't return a reference type,
3513 // it can't be considered for this conversion unless we're allowed to
3514 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515 // FIXME: Do we need to make sure that we only consider conversion
3516 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003517 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003518 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003519 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3520 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003521 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003522 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003523 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003524 else
John McCall9aa472c2010-03-19 07:35:19 +00003525 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003526 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003527 }
3528 }
3529 }
John McCall572fc622010-08-17 07:23:57 +00003530 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3531 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003532
Douglas Gregor20093b42009-12-09 23:02:17 +00003533 SourceLocation DeclLoc = Initializer->getLocStart();
3534
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003535 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003536 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003537 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003538 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003540
Douglas Gregor20093b42009-12-09 23:02:17 +00003541 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003542 // This is the overload that will be used for this initialization step if we
3543 // use this initialization. Mark it as referenced.
3544 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003545
Eli Friedman03981012009-12-11 02:42:07 +00003546 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003547 if (isa<CXXConversionDecl>(Function))
3548 T2 = Function->getResultType();
3549 else
3550 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003551
3552 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003553 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003554 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003555 T2.getNonLValueExprType(S.Context),
3556 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003557
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003558 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003559 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003560 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003561 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003562 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003563 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003564 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003565
Douglas Gregor20093b42009-12-09 23:02:17 +00003566 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003567 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003568 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003569 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003570 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003571 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003572 NewDerivedToBase, NewObjCConversion,
3573 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003574 if (NewRefRelationship == Sema::Ref_Incompatible) {
3575 // If the type we've converted to is not reference-related to the
3576 // type we're looking for, then there is another conversion step
3577 // we need to perform to produce a temporary of the right type
3578 // that we'll be binding to.
3579 ImplicitConversionSequence ICS;
3580 ICS.setStandard();
3581 ICS.Standard = Best->FinalConversion;
3582 T2 = ICS.Standard.getToType(2);
3583 Sequence.AddConversionSequenceStep(ICS, T2);
3584 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003585 Sequence.AddDerivedToBaseCastStep(
3586 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003587 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003588 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003589 else if (NewObjCConversion)
3590 Sequence.AddObjCObjectConversionStep(
3591 S.Context.getQualifiedType(T1,
3592 T2.getNonReferenceType().getQualifiers()));
3593
Douglas Gregor20093b42009-12-09 23:02:17 +00003594 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003595 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596
Douglas Gregor20093b42009-12-09 23:02:17 +00003597 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3598 return OR_Success;
3599}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003600
Richard Smith83da2e72011-10-19 16:55:56 +00003601static void CheckCXX98CompatAccessibleCopy(Sema &S,
3602 const InitializedEntity &Entity,
3603 Expr *CurInitExpr);
3604
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003605/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3606static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003607 const InitializedEntity &Entity,
3608 const InitializationKind &Kind,
3609 Expr *Initializer,
3610 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003611 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003612 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003613 Qualifiers T1Quals;
3614 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003615 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003616 Qualifiers T2Quals;
3617 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003618
Douglas Gregor20093b42009-12-09 23:02:17 +00003619 // If the initializer is the address of an overloaded function, try
3620 // to resolve the overloaded function. If all goes well, T2 is the
3621 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003622 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3623 T1, Sequence))
3624 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003625
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003626 // Delegate everything else to a subfunction.
3627 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3628 T1Quals, cv2T2, T2, T2Quals, Sequence);
3629}
3630
Jordan Rose1fd1e282013-04-11 00:58:58 +00003631/// Converts the target of reference initialization so that it has the
3632/// appropriate qualifiers and value kind.
3633///
3634/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3635/// \code
3636/// int x;
3637/// const int &r = x;
3638/// \endcode
3639///
3640/// In this case the reference is binding to a bitfield lvalue, which isn't
3641/// valid. Perform a load to create a lifetime-extended temporary instead.
3642/// \code
3643/// const int &r = someStruct.bitfield;
3644/// \endcode
3645static ExprValueKind
3646convertQualifiersAndValueKindIfNecessary(Sema &S,
3647 InitializationSequence &Sequence,
3648 Expr *Initializer,
3649 QualType cv1T1,
3650 Qualifiers T1Quals,
3651 Qualifiers T2Quals,
3652 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003653 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003654 Initializer->refersToVectorElement();
3655
3656 if (IsNonAddressableType) {
3657 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3658 // lvalue reference to a non-volatile const type, or the reference shall be
3659 // an rvalue reference.
3660 //
3661 // If not, we can't make a temporary and bind to that. Give up and allow the
3662 // error to be diagnosed later.
3663 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3664 assert(Initializer->isGLValue());
3665 return Initializer->getValueKind();
3666 }
3667
3668 // Force a load so we can materialize a temporary.
3669 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3670 return VK_RValue;
3671 }
3672
3673 if (T1Quals != T2Quals) {
3674 Sequence.AddQualificationConversionStep(cv1T1,
3675 Initializer->getValueKind());
3676 }
3677
3678 return Initializer->getValueKind();
3679}
3680
3681
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003682/// \brief Reference initialization without resolving overloaded functions.
3683static void TryReferenceInitializationCore(Sema &S,
3684 const InitializedEntity &Entity,
3685 const InitializationKind &Kind,
3686 Expr *Initializer,
3687 QualType cv1T1, QualType T1,
3688 Qualifiers T1Quals,
3689 QualType cv2T2, QualType T2,
3690 Qualifiers T2Quals,
3691 InitializationSequence &Sequence) {
3692 QualType DestType = Entity.getType();
3693 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003694 // Compute some basic properties of the types and the initializer.
3695 bool isLValueRef = DestType->isLValueReferenceType();
3696 bool isRValueRef = !isLValueRef;
3697 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003698 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003699 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003700 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003701 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003702 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003703 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003704
Douglas Gregor20093b42009-12-09 23:02:17 +00003705 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003706 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003707 // "cv2 T2" as follows:
3708 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 // expression
Richard Smith867521c2013-09-21 21:23:47 +00003711 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redl4680bf22010-06-30 18:13:39 +00003712 // there are no function rvalues in C++, rvalue refs to functions are treated
3713 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003714 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003715 bool T1Function = T1->isFunctionType();
3716 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003717 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003718 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003719 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003720 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003721 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003722 // reference-compatible with "cv2 T2," or
3723 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003724 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003725 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003726 // can occur. However, we do pay attention to whether it is a bit-field
3727 // to decide whether we're actually binding to a temporary created from
3728 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003729 if (DerivedToBase)
3730 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003731 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003732 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003733 else if (ObjCConversion)
3734 Sequence.AddObjCObjectConversionStep(
3735 S.Context.getQualifiedType(T1, T2Quals));
3736
Jordan Rose1fd1e282013-04-11 00:58:58 +00003737 ExprValueKind ValueKind =
3738 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3739 cv1T1, T1Quals, T2Quals,
3740 isLValueRef);
3741 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003742 return;
3743 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003744
3745 // - has a class type (i.e., T2 is a class type), where T1 is not
3746 // reference-related to T2, and can be implicitly converted to an
3747 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3748 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003749 // applicable conversion functions (13.3.1.6) and choosing the best
3750 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003751 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith867521c2013-09-21 21:23:47 +00003752 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003753 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3754 (isLValueRef || InitCategory.isRValue())) {
Richard Smith867521c2013-09-21 21:23:47 +00003755 ConvOvlResult = TryRefInitWithConversionFunction(
3756 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00003757 if (ConvOvlResult == OR_Success)
3758 return;
Richard Smith867521c2013-09-21 21:23:47 +00003759 if (ConvOvlResult != OR_No_Viable_Function)
John McCall1d318332010-01-12 00:44:57 +00003760 Sequence.SetOverloadFailure(
Richard Smith867521c2013-09-21 21:23:47 +00003761 InitializationSequence::FK_ReferenceInitOverloadFailed,
3762 ConvOvlResult);
Douglas Gregor20093b42009-12-09 23:02:17 +00003763 }
3764 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003765
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003766 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003767 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003768 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003769 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003770 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3771 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3772 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003773 Sequence.SetOverloadFailure(
3774 InitializationSequence::FK_ReferenceInitOverloadFailed,
3775 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003776 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003777 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003778 ? (RefRelationship == Sema::Ref_Related
3779 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3780 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3781 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003782
Douglas Gregor20093b42009-12-09 23:02:17 +00003783 return;
3784 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003785
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003786 // - If the initializer expression
3787 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3788 // "cv1 T1" is reference-compatible with "cv2 T2"
3789 // Note: functions are handled below.
3790 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003791 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003793 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003794 (InitCategory.isXValue() ||
3795 (InitCategory.isPRValue() && T2->isRecordType()) ||
3796 (InitCategory.isPRValue() && T2->isArrayType()))) {
3797 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3798 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003799 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3800 // compiler the freedom to perform a copy here or bind to the
3801 // object, while C++0x requires that we bind directly to the
3802 // object. Hence, we always bind to the object without making an
3803 // extra copy. However, in C++03 requires that we check for the
3804 // presence of a suitable copy constructor:
3805 //
3806 // The constructor that would be used to make the copy shall
3807 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003808 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003809 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003810 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003811 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003813
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003814 if (DerivedToBase)
3815 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3816 ValueKind);
3817 else if (ObjCConversion)
3818 Sequence.AddObjCObjectConversionStep(
3819 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003820
Jordan Rose1fd1e282013-04-11 00:58:58 +00003821 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3822 Initializer, cv1T1,
3823 T1Quals, T2Quals,
3824 isLValueRef);
3825
3826 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003828 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003829
3830 // - has a class type (i.e., T2 is a class type), where T1 is not
3831 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003832 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3833 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith867521c2013-09-21 21:23:47 +00003834 //
3835 // DR1287 removes the "implicitly" here.
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003836 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003837 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith867521c2013-09-21 21:23:47 +00003838 ConvOvlResult = TryRefInitWithConversionFunction(
3839 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00003840 if (ConvOvlResult)
3841 Sequence.SetOverloadFailure(
Richard Smith867521c2013-09-21 21:23:47 +00003842 InitializationSequence::FK_ReferenceInitOverloadFailed,
3843 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844
Douglas Gregor20093b42009-12-09 23:02:17 +00003845 return;
3846 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003847
Douglas Gregordefa32e2013-03-26 23:59:23 +00003848 if ((RefRelationship == Sema::Ref_Compatible ||
3849 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3850 isRValueRef && InitCategory.isLValue()) {
3851 Sequence.SetFailed(
3852 InitializationSequence::FK_RValueReferenceBindingToLValue);
3853 return;
3854 }
3855
Douglas Gregor20093b42009-12-09 23:02:17 +00003856 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3857 return;
3858 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003859
3860 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003861 // from the initializer expression using the rules for a non-reference
Richard Smith4e47ecb2013-06-13 00:57:57 +00003862 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003863 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003864
John McCall369371c2010-06-04 02:29:22 +00003865 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3866
Richard Smith4e47ecb2013-06-13 00:57:57 +00003867 // FIXME: Why do we use an implicit conversion here rather than trying
3868 // copy-initialization?
John McCallf85e1932011-06-15 23:02:42 +00003869 ImplicitConversionSequence ICS
3870 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith4e47ecb2013-06-13 00:57:57 +00003871 /*SuppressUserConversions=*/false,
3872 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003873 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003874 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3875 /*AllowObjCWritebackConversion=*/false);
3876
3877 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003878 // FIXME: Use the conversion function set stored in ICS to turn
3879 // this into an overloading ambiguity diagnostic. However, we need
3880 // to keep that set as an OverloadCandidateSet rather than as some
3881 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003882 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3883 Sequence.SetOverloadFailure(
3884 InitializationSequence::FK_ReferenceInitOverloadFailed,
3885 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003886 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3887 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003888 else
3889 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003890 return;
John McCallf85e1932011-06-15 23:02:42 +00003891 } else {
3892 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003893 }
3894
3895 // [...] If T1 is reference-related to T2, cv1 must be the
3896 // same cv-qualification as, or greater cv-qualification
3897 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003898 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3899 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003900 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003901 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003902 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3903 return;
3904 }
3905
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003906 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003907 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003908 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003909 InitCategory.isLValue()) {
3910 Sequence.SetFailed(
3911 InitializationSequence::FK_RValueReferenceBindingToLValue);
3912 return;
3913 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003914
Douglas Gregor20093b42009-12-09 23:02:17 +00003915 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3916 return;
3917}
3918
3919/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003920/// (C++ [dcl.init.string], C99 6.7.8).
3921static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003922 const InitializedEntity &Entity,
3923 const InitializationKind &Kind,
3924 Expr *Initializer,
3925 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003926 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003927}
3928
Douglas Gregor71d17402009-12-15 00:01:57 +00003929/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003930static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003931 const InitializedEntity &Entity,
3932 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003933 InitializationSequence &Sequence,
3934 InitListExpr *InitList) {
3935 assert((!InitList || InitList->getNumInits() == 0) &&
3936 "Shouldn't use value-init for non-empty init lists");
3937
Richard Smith1d0c9a82012-02-14 21:14:13 +00003938 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003939 //
3940 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003941 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003942
Douglas Gregor71d17402009-12-15 00:01:57 +00003943 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003944 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945
Douglas Gregor71d17402009-12-15 00:01:57 +00003946 if (const RecordType *RT = T->getAs<RecordType>()) {
3947 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003948 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003949 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003950 // C++98:
3951 // -- if T is a class type (clause 9) with a user-declared constructor
3952 // (12.1), then the default constructor for T is called (and the
3953 // initialization is ill-formed if T has no accessible default
3954 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003955 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003956 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003957 } else {
3958 // C++11:
3959 // -- if T is a class type (clause 9) with either no default constructor
3960 // (12.1 [class.ctor]) or a default constructor that is user-provided
3961 // or deleted, then the object is default-initialized;
3962 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3963 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003964 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003965 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003966
Richard Smith1d0c9a82012-02-14 21:14:13 +00003967 // -- if T is a (possibly cv-qualified) non-union class type without a
3968 // user-provided or deleted default constructor, then the object is
3969 // zero-initialized and, if T has a non-trivial default constructor,
3970 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003971 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3972 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003973 if (NeedZeroInitialization)
3974 Sequence.AddZeroInitializationStep(Entity.getType());
3975
Richard Smithd5bc8672012-12-08 02:01:17 +00003976 // C++03:
3977 // -- if T is a non-union class type without a user-declared constructor,
3978 // then every non-static data member and base class component of T is
3979 // value-initialized;
3980 // [...] A program that calls for [...] value-initialization of an
3981 // entity of reference type is ill-formed.
3982 //
3983 // C++11 doesn't need this handling, because value-initialization does not
3984 // occur recursively there, and the implicit default constructor is
3985 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003986 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003987 ClassDecl->hasUninitializedReferenceMember()) {
3988 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3989 return;
3990 }
3991
Richard Smithf4bb8d02012-07-05 08:39:21 +00003992 // If this is list-value-initialization, pass the empty init list on when
3993 // building the constructor call. This affects the semantics of a few
3994 // things (such as whether an explicit default constructor can be called).
3995 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003996 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003997 bool InitListSyntax = InitList;
3998
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003999 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4000 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00004001 }
4002 }
4003
Douglas Gregord6542d82009-12-22 15:35:07 +00004004 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00004005}
4006
Douglas Gregor99a2e602009-12-16 01:38:02 +00004007/// \brief Attempt default initialization (C++ [dcl.init]p6).
4008static void TryDefaultInitialization(Sema &S,
4009 const InitializedEntity &Entity,
4010 const InitializationKind &Kind,
4011 InitializationSequence &Sequence) {
4012 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004013
Douglas Gregor99a2e602009-12-16 01:38:02 +00004014 // C++ [dcl.init]p6:
4015 // To default-initialize an object of type T means:
4016 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00004017 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4018
Douglas Gregor99a2e602009-12-16 01:38:02 +00004019 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4020 // constructor for T is called (and the initialization is ill-formed if
4021 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00004022 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00004023 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004024 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004025 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004026
Douglas Gregor99a2e602009-12-16 01:38:02 +00004027 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004028
Douglas Gregor99a2e602009-12-16 01:38:02 +00004029 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004030 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00004031 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00004032 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004033 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00004034 return;
4035 }
4036
4037 // If the destination type has a lifetime property, zero-initialize it.
4038 if (DestType.getQualifiers().hasObjCLifetime()) {
4039 Sequence.AddZeroInitializationStep(Entity.getType());
4040 return;
4041 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004042}
4043
Douglas Gregor20093b42009-12-09 23:02:17 +00004044/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4045/// which enumerates all conversion functions and performs overload resolution
4046/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004047static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004048 const InitializedEntity &Entity,
4049 const InitializationKind &Kind,
4050 Expr *Initializer,
Richard Smith13b228d2013-09-21 21:19:19 +00004051 InitializationSequence &Sequence,
4052 bool TopLevelOfInitList) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004053 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004054 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4055 QualType SourceType = Initializer->getType();
4056 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4057 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004058
Douglas Gregor4a520a22009-12-14 17:27:33 +00004059 // Build the candidate set directly in the initialization sequence
4060 // structure, so that it will persist if we fail.
4061 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4062 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063
Douglas Gregor4a520a22009-12-14 17:27:33 +00004064 // Determine whether we are allowed to call explicit constructors or
4065 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00004066 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004067
Douglas Gregor4a520a22009-12-14 17:27:33 +00004068 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4069 // The type we're converting to is a class type. Enumerate its constructors
4070 // to see if there is a suitable conversion.
4071 CXXRecordDecl *DestRecordDecl
4072 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004073
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004074 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004076 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004077 // The container holding the constructors can under certain conditions
4078 // be changed while iterating. To be safe we copy the lookup results
4079 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004080 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004081 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004082 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004083 Con != ConEnd; ++Con) {
4084 NamedDecl *D = *Con;
4085 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004086
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004087 // Find the constructor (which may be a template).
4088 CXXConstructorDecl *Constructor = 0;
4089 FunctionTemplateDecl *ConstructorTmpl
4090 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004091 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004092 Constructor = cast<CXXConstructorDecl>(
4093 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00004094 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004095 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004096
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004097 if (!Constructor->isInvalidDecl() &&
4098 Constructor->isConvertingConstructor(AllowExplicit)) {
4099 if (ConstructorTmpl)
4100 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4101 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004102 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004103 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004104 else
4105 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004106 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004107 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004108 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004109 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004110 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004111 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004112
4113 SourceLocation DeclLoc = Initializer->getLocStart();
4114
Douglas Gregor4a520a22009-12-14 17:27:33 +00004115 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4116 // The type we're converting from is a class type, enumerate its conversion
4117 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004118
Eli Friedman33c2da92009-12-20 22:12:03 +00004119 // We can only enumerate the conversion functions for a complete type; if
4120 // the type isn't complete, simply skip this step.
4121 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4122 CXXRecordDecl *SourceRecordDecl
4123 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004124
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004125 std::pair<CXXRecordDecl::conversion_iterator,
4126 CXXRecordDecl::conversion_iterator>
4127 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4128 for (CXXRecordDecl::conversion_iterator
4129 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00004130 NamedDecl *D = *I;
4131 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4132 if (isa<UsingShadowDecl>(D))
4133 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004134
Eli Friedman33c2da92009-12-20 22:12:03 +00004135 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4136 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00004137 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00004138 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00004139 else
John McCall32daa422010-03-31 01:36:47 +00004140 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004141
Eli Friedman33c2da92009-12-20 22:12:03 +00004142 if (AllowExplicit || !Conv->isExplicit()) {
4143 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00004144 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00004145 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00004146 CandidateSet);
4147 else
John McCall9aa472c2010-03-19 07:35:19 +00004148 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00004149 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00004150 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004151 }
4152 }
4153 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004154
4155 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004156 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004157 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004158 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004159 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004160 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004161 Result);
4162 return;
4163 }
John McCall1d318332010-01-12 00:44:57 +00004164
Douglas Gregor4a520a22009-12-14 17:27:33 +00004165 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004166 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004167 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004168
Douglas Gregor4a520a22009-12-14 17:27:33 +00004169 if (isa<CXXConstructorDecl>(Function)) {
4170 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004171 // subsumed by the initialization. Per DR5, the created temporary is of the
4172 // cv-unqualified type of the destination.
4173 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4174 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004175 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004176 return;
4177 }
4178
4179 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004180 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004181 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004182 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004183 // the resulting temporary object (possible to create an object of
4184 // a base class type). That copy is not a separate conversion, so
4185 // we just make a note of the actual destination type (possibly a
4186 // base class of the type returned by the conversion function) and
4187 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004188 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4189 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004190 return;
4191 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004192
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004193 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4194 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004195
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004196 // If the conversion following the call to the conversion function
4197 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004198 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4199 Best->FinalConversion.Third) {
4200 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004201 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004202 ICS.Standard = Best->FinalConversion;
Richard Smith13b228d2013-09-21 21:19:19 +00004203 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004204 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004205}
4206
Richard Smith87c29322013-06-20 02:18:31 +00004207/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4208/// a function with a pointer return type contains a 'return false;' statement.
4209/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4210/// code using that header.
4211///
4212/// Work around this by treating 'return false;' as zero-initializing the result
4213/// if it's used in a pointer-returning function in a system header.
4214static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4215 const InitializedEntity &Entity,
4216 const Expr *Init) {
4217 return S.getLangOpts().CPlusPlus11 &&
4218 Entity.getKind() == InitializedEntity::EK_Result &&
4219 Entity.getType()->isPointerType() &&
4220 isa<CXXBoolLiteralExpr>(Init) &&
4221 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4222 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4223}
4224
John McCallf85e1932011-06-15 23:02:42 +00004225/// The non-zero enum values here are indexes into diagnostic alternatives.
4226enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4227
4228/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004229static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004230 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004231 // Skip parens.
4232 e = e->IgnoreParens();
4233
4234 // Skip address-of nodes.
4235 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4236 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004237 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4238 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004239
4240 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004241 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4242 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004243 case CK_Dependent:
4244 case CK_BitCast:
4245 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004246 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004247 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004248
4249 case CK_ArrayToPointerDecay:
4250 return IIK_nonscalar;
4251
4252 case CK_NullToPointer:
4253 return IIK_okay;
4254
4255 default:
4256 break;
4257 }
4258
4259 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004260 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004261 // set isWeakAccess to true, to mean that there will be an implicit
4262 // load which requires a cleanup.
4263 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4264 isWeakAccess = true;
4265
John McCallc03fa492011-06-27 23:59:58 +00004266 if (!isAddressOf) return IIK_nonlocal;
4267
John McCallf4b88a42012-03-10 09:33:50 +00004268 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4269 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004270
4271 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004272
4273 // If we have a conditional operator, check both sides.
4274 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004275 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4276 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004277 return iik;
4278
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004279 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004280
4281 // These are never scalar.
4282 } else if (isa<ArraySubscriptExpr>(e)) {
4283 return IIK_nonscalar;
4284
4285 // Otherwise, it needs to be a null pointer constant.
4286 } else {
4287 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4288 ? IIK_okay : IIK_nonlocal);
4289 }
4290
4291 return IIK_nonlocal;
4292}
4293
4294/// Check whether the given expression is a valid operand for an
4295/// indirect copy/restore.
4296static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4297 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004298 bool isWeakAccess = false;
4299 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4300 // If isWeakAccess to true, there will be an implicit
4301 // load which requires a cleanup.
4302 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4303 S.ExprNeedsCleanups = true;
4304
John McCallf85e1932011-06-15 23:02:42 +00004305 if (iik == IIK_okay) return;
4306
4307 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4308 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4309 << src->getSourceRange();
4310}
4311
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004312/// \brief Determine whether we have compatible array types for the
4313/// purposes of GNU by-copy array initialization.
4314static bool hasCompatibleArrayTypes(ASTContext &Context,
4315 const ArrayType *Dest,
4316 const ArrayType *Source) {
4317 // If the source and destination array types are equivalent, we're
4318 // done.
4319 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4320 return true;
4321
4322 // Make sure that the element types are the same.
4323 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4324 return false;
4325
4326 // The only mismatch we allow is when the destination is an
4327 // incomplete array type and the source is a constant array type.
4328 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4329}
4330
John McCallf85e1932011-06-15 23:02:42 +00004331static bool tryObjCWritebackConversion(Sema &S,
4332 InitializationSequence &Sequence,
4333 const InitializedEntity &Entity,
4334 Expr *Initializer) {
4335 bool ArrayDecay = false;
4336 QualType ArgType = Initializer->getType();
4337 QualType ArgPointee;
4338 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4339 ArrayDecay = true;
4340 ArgPointee = ArgArrayType->getElementType();
4341 ArgType = S.Context.getPointerType(ArgPointee);
4342 }
4343
4344 // Handle write-back conversion.
4345 QualType ConvertedArgType;
4346 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4347 ConvertedArgType))
4348 return false;
4349
4350 // We should copy unless we're passing to an argument explicitly
4351 // marked 'out'.
4352 bool ShouldCopy = true;
4353 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4354 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4355
4356 // Do we need an lvalue conversion?
4357 if (ArrayDecay || Initializer->isGLValue()) {
4358 ImplicitConversionSequence ICS;
4359 ICS.setStandard();
4360 ICS.Standard.setAsIdentityConversion();
4361
4362 QualType ResultType;
4363 if (ArrayDecay) {
4364 ICS.Standard.First = ICK_Array_To_Pointer;
4365 ResultType = S.Context.getPointerType(ArgPointee);
4366 } else {
4367 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4368 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4369 }
4370
4371 Sequence.AddConversionSequenceStep(ICS, ResultType);
4372 }
4373
4374 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4375 return true;
4376}
4377
Guy Benyei21f18c42013-02-07 10:55:47 +00004378static bool TryOCLSamplerInitialization(Sema &S,
4379 InitializationSequence &Sequence,
4380 QualType DestType,
4381 Expr *Initializer) {
4382 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4383 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4384 return false;
4385
4386 Sequence.AddOCLSamplerInitStep(DestType);
4387 return true;
4388}
4389
Guy Benyeie6b9d802013-01-20 12:31:11 +00004390//
4391// OpenCL 1.2 spec, s6.12.10
4392//
4393// The event argument can also be used to associate the
4394// async_work_group_copy with a previous async copy allowing
4395// an event to be shared by multiple async copies; otherwise
4396// event should be zero.
4397//
4398static bool TryOCLZeroEventInitialization(Sema &S,
4399 InitializationSequence &Sequence,
4400 QualType DestType,
4401 Expr *Initializer) {
4402 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4403 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4404 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4405 return false;
4406
4407 Sequence.AddOCLZeroEventStep(DestType);
4408 return true;
4409}
4410
Douglas Gregor20093b42009-12-09 23:02:17 +00004411InitializationSequence::InitializationSequence(Sema &S,
4412 const InitializedEntity &Entity,
4413 const InitializationKind &Kind,
Richard Smith13b228d2013-09-21 21:19:19 +00004414 MultiExprArg Args,
4415 bool TopLevelOfInitList)
John McCall5769d612010-02-08 23:07:23 +00004416 : FailedCandidateSet(Kind.getLocation()) {
Richard Smithb390e492013-09-21 21:55:46 +00004417 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4418}
4419
4420void InitializationSequence::InitializeFrom(Sema &S,
4421 const InitializedEntity &Entity,
4422 const InitializationKind &Kind,
4423 MultiExprArg Args,
4424 bool TopLevelOfInitList) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004425 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004426
John McCall76da55d2013-04-16 07:28:30 +00004427 // Eliminate non-overload placeholder types in the arguments. We
4428 // need to do this before checking whether types are dependent
4429 // because lowering a pseudo-object expression might well give us
4430 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004431 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004432 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4433 // FIXME: should we be doing this here?
4434 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4435 if (result.isInvalid()) {
4436 SetFailed(FK_PlaceholderType);
4437 return;
4438 }
4439 Args[I] = result.take();
4440 }
4441
Douglas Gregor20093b42009-12-09 23:02:17 +00004442 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004443 // The semantics of initializers are as follows. The destination type is
4444 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004445 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004447 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004448 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004449
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004450 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004451 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004452 SequenceKind = DependentSequence;
4453 return;
4454 }
4455
Sebastian Redl7491c492011-06-05 13:59:11 +00004456 // Almost everything is a normal sequence.
4457 setSequenceKind(NormalSequence);
4458
Douglas Gregor20093b42009-12-09 23:02:17 +00004459 QualType SourceType;
4460 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004461 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004462 Initializer = Args[0];
4463 if (!isa<InitListExpr>(Initializer))
4464 SourceType = Initializer->getType();
4465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004466
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004467 // - If the initializer is a (non-parenthesized) braced-init-list, the
4468 // object is list-initialized (8.5.4).
4469 if (Kind.getKind() != InitializationKind::IK_Direct) {
4470 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4471 TryListInitialization(S, Entity, Kind, InitList, *this);
4472 return;
4473 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004474 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475
Douglas Gregor20093b42009-12-09 23:02:17 +00004476 // - If the destination type is a reference type, see 8.5.3.
4477 if (DestType->isReferenceType()) {
4478 // C++0x [dcl.init.ref]p1:
4479 // A variable declared to be a T& or T&&, that is, "reference to type T"
4480 // (8.3.2), shall be initialized by an object, or function, of type T or
4481 // by an object that can be converted into a T.
4482 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004483 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004484 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004485 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004486 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004487 return;
4488 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004489
Douglas Gregor20093b42009-12-09 23:02:17 +00004490 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004491 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004492 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004493 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004494 return;
4495 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004496
Douglas Gregor99a2e602009-12-16 01:38:02 +00004497 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004498 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004499 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004500 return;
4501 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004502
John McCallce6c9b72011-02-21 07:22:22 +00004503 // - If the destination type is an array of characters, an array of
4504 // char16_t, an array of char32_t, or an array of wchar_t, and the
4505 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004506 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004507 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004508 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004509 if (Initializer && isa<VariableArrayType>(DestAT)) {
4510 SetFailed(FK_VariableLengthArrayHasInitializer);
4511 return;
4512 }
4513
Hans Wennborg0ff50742013-05-15 11:03:04 +00004514 if (Initializer) {
4515 switch (IsStringInit(Initializer, DestAT, Context)) {
4516 case SIF_None:
4517 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4518 return;
4519 case SIF_NarrowStringIntoWideChar:
4520 SetFailed(FK_NarrowStringIntoWideCharArray);
4521 return;
4522 case SIF_WideStringIntoChar:
4523 SetFailed(FK_WideStringIntoCharArray);
4524 return;
4525 case SIF_IncompatWideStringIntoWideChar:
4526 SetFailed(FK_IncompatWideStringIntoWideChar);
4527 return;
4528 case SIF_Other:
4529 break;
4530 }
John McCallce6c9b72011-02-21 07:22:22 +00004531 }
4532
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004533 // Note: as an GNU C extension, we allow initialization of an
4534 // array from a compound literal that creates an array of the same
4535 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004536 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004537 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4538 Initializer->getType()->isArrayType()) {
4539 const ArrayType *SourceAT
4540 = Context.getAsArrayType(Initializer->getType());
4541 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004542 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004543 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004544 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004545 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004546 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004547 }
Richard Smith0f163e92012-02-15 22:38:09 +00004548 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004549 // Note: as a GNU C++ extension, we allow list-initialization of a
4550 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004551 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004552 Entity.getKind() == InitializedEntity::EK_Member &&
4553 Initializer && isa<InitListExpr>(Initializer)) {
4554 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4555 *this);
4556 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004557 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004558 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004559 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4560 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004561 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004562 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004563
Douglas Gregor20093b42009-12-09 23:02:17 +00004564 return;
4565 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004566
John McCallf85e1932011-06-15 23:02:42 +00004567 // Determine whether we should consider writeback conversions for
4568 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004569 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004570 Entity.isParameterKind();
John McCallf85e1932011-06-15 23:02:42 +00004571
4572 // We're at the end of the line for C: it's either a write-back conversion
4573 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004574 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004575 // If allowed, check whether this is an Objective-C writeback conversion.
4576 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004577 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004578 return;
4579 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004580
4581 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4582 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004583
4584 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4585 return;
4586
John McCallf85e1932011-06-15 23:02:42 +00004587 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004588 AddCAssignmentStep(DestType);
4589 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004590 return;
4591 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004592
David Blaikie4e4d0842012-03-11 07:00:24 +00004593 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004594
Douglas Gregor20093b42009-12-09 23:02:17 +00004595 // - If the destination type is a (possibly cv-qualified) class type:
4596 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004597 // - If the initialization is direct-initialization, or if it is
4598 // copy-initialization where the cv-unqualified version of the
4599 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004600 // class of the destination, constructors are considered. [...]
4601 if (Kind.getKind() == InitializationKind::IK_Direct ||
4602 (Kind.getKind() == InitializationKind::IK_Copy &&
4603 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4604 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004605 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004606 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004607 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004608 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004609 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004610 // used) to a derived class thereof are enumerated as described in
4611 // 13.3.1.4, and the best one is chosen through overload resolution
4612 // (13.3).
4613 else
Richard Smith13b228d2013-09-21 21:19:19 +00004614 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4615 TopLevelOfInitList);
Douglas Gregor20093b42009-12-09 23:02:17 +00004616 return;
4617 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004618
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004619 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004620 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004621 return;
4622 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004623 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004624
4625 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004626 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004627 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith13b228d2013-09-21 21:19:19 +00004628 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4629 TopLevelOfInitList);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004630 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004631 return;
4632 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004633
Douglas Gregor20093b42009-12-09 23:02:17 +00004634 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004635 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004636 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004637 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004638 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004639
4640 ImplicitConversionSequence ICS
4641 = S.TryImplicitConversion(Initializer, Entity.getType(),
4642 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004643 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004644 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004645 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4646 allowObjCWritebackConversion);
4647
4648 if (ICS.isStandard() &&
4649 ICS.Standard.Second == ICK_Writeback_Conversion) {
4650 // Objective-C ARC writeback conversion.
4651
4652 // We should copy unless we're passing to an argument explicitly
4653 // marked 'out'.
4654 bool ShouldCopy = true;
4655 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4656 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4657
4658 // If there was an lvalue adjustment, add it as a separate conversion.
4659 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4660 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4661 ImplicitConversionSequence LvalueICS;
4662 LvalueICS.setStandard();
4663 LvalueICS.Standard.setAsIdentityConversion();
4664 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4665 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004666 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004667 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004668
4669 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004670 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004671 DeclAccessPair dap;
Richard Smith87c29322013-06-20 02:18:31 +00004672 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4673 AddZeroInitializationStep(Entity.getType());
4674 } else if (Initializer->getType() == Context.OverloadTy &&
4675 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4676 false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004677 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004678 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004679 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004680 } else {
Richard Smith13b228d2013-09-21 21:19:19 +00004681 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCall856d3792011-06-16 23:24:51 +00004682
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004683 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004684 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004685}
4686
4687InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004688 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004689 StepEnd = Steps.end();
4690 Step != StepEnd; ++Step)
4691 Step->Destroy();
4692}
4693
4694//===----------------------------------------------------------------------===//
4695// Perform initialization
4696//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004697static Sema::AssignmentAction
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004698getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004699 switch(Entity.getKind()) {
4700 case InitializedEntity::EK_Variable:
4701 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004702 case InitializedEntity::EK_Exception:
4703 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004704 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004705 return Sema::AA_Initializing;
4706
4707 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004708 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004709 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4710 return Sema::AA_Sending;
4711
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004712 return Sema::AA_Passing;
4713
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004714 case InitializedEntity::EK_Parameter_CF_Audited:
4715 if (Entity.getDecl() &&
4716 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4717 return Sema::AA_Sending;
4718
4719 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4720
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004721 case InitializedEntity::EK_Result:
4722 return Sema::AA_Returning;
4723
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004724 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf5200d62013-07-11 19:13:34 +00004725 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004726 // FIXME: Can we tell apart casting vs. converting?
4727 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004729 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004730 case InitializedEntity::EK_ArrayElement:
4731 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004732 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004733 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004734 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004735 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004736 return Sema::AA_Initializing;
4737 }
4738
David Blaikie7530c032012-01-17 06:56:22 +00004739 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004740}
4741
Richard Smith774d8b42013-01-08 00:08:23 +00004742/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004743/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004744static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004745 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004746 case InitializedEntity::EK_ArrayElement:
4747 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004748 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004749 case InitializedEntity::EK_New:
4750 case InitializedEntity::EK_Variable:
4751 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004752 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004753 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004754 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004755 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004756 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004757 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004758 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004759 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004760
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004761 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004762 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004763 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004764 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004765 return true;
4766 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004767
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004768 llvm_unreachable("missed an InitializedEntity kind?");
4769}
4770
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004771/// \brief Whether the given entity, when initialized with an object
4772/// created for that initialization, requires destruction.
4773static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4774 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004775 case InitializedEntity::EK_Result:
4776 case InitializedEntity::EK_New:
4777 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004778 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004779 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004780 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004781 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004782 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004783 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004784
Richard Smith774d8b42013-01-08 00:08:23 +00004785 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004786 case InitializedEntity::EK_Variable:
4787 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004788 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004789 case InitializedEntity::EK_Temporary:
4790 case InitializedEntity::EK_ArrayElement:
4791 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004792 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004793 case InitializedEntity::EK_RelatedResult:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004794 return true;
4795 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004796
4797 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004798}
4799
Richard Smith83da2e72011-10-19 16:55:56 +00004800/// \brief Look for copy and move constructors and constructor templates, for
4801/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4802static void LookupCopyAndMoveConstructors(Sema &S,
4803 OverloadCandidateSet &CandidateSet,
4804 CXXRecordDecl *Class,
4805 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004806 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004807 // The container holding the constructors can under certain conditions
4808 // be changed while iterating (e.g. because of deserialization).
4809 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004810 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004811 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004812 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4813 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004814 CXXConstructorDecl *Constructor = 0;
4815
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004816 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004817 // Handle copy/moveconstructors, only.
4818 if (!Constructor || Constructor->isInvalidDecl() ||
4819 !Constructor->isCopyOrMoveConstructor() ||
4820 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4821 continue;
4822
4823 DeclAccessPair FoundDecl
4824 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4825 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004826 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004827 continue;
4828 }
4829
4830 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004831 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004832 if (ConstructorTmpl->isInvalidDecl())
4833 continue;
4834
4835 Constructor = cast<CXXConstructorDecl>(
4836 ConstructorTmpl->getTemplatedDecl());
4837 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4838 continue;
4839
4840 // FIXME: Do we need to limit this to copy-constructor-like
4841 // candidates?
4842 DeclAccessPair FoundDecl
4843 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4844 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004845 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004846 }
4847}
4848
4849/// \brief Get the location at which initialization diagnostics should appear.
4850static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4851 Expr *Initializer) {
4852 switch (Entity.getKind()) {
4853 case InitializedEntity::EK_Result:
4854 return Entity.getReturnLoc();
4855
4856 case InitializedEntity::EK_Exception:
4857 return Entity.getThrowLoc();
4858
4859 case InitializedEntity::EK_Variable:
4860 return Entity.getDecl()->getLocation();
4861
Douglas Gregor47736542012-02-15 16:57:26 +00004862 case InitializedEntity::EK_LambdaCapture:
4863 return Entity.getCaptureLoc();
4864
Richard Smith83da2e72011-10-19 16:55:56 +00004865 case InitializedEntity::EK_ArrayElement:
4866 case InitializedEntity::EK_Member:
4867 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004868 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith83da2e72011-10-19 16:55:56 +00004869 case InitializedEntity::EK_Temporary:
4870 case InitializedEntity::EK_New:
4871 case InitializedEntity::EK_Base:
4872 case InitializedEntity::EK_Delegating:
4873 case InitializedEntity::EK_VectorElement:
4874 case InitializedEntity::EK_ComplexElement:
4875 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004876 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004877 case InitializedEntity::EK_RelatedResult:
Richard Smith83da2e72011-10-19 16:55:56 +00004878 return Initializer->getLocStart();
4879 }
4880 llvm_unreachable("missed an InitializedEntity kind?");
4881}
4882
Douglas Gregor523d46a2010-04-18 07:40:54 +00004883/// \brief Make a (potentially elidable) temporary copy of the object
4884/// provided by the given initializer by calling the appropriate copy
4885/// constructor.
4886///
4887/// \param S The Sema object used for type-checking.
4888///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004889/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004890/// the type of the initializer expression or a superclass thereof.
4891///
James Dennett1dfbd922012-06-14 21:40:34 +00004892/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004893///
4894/// \param CurInit The initializer expression.
4895///
4896/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4897/// is permitted in C++03 (but not C++0x) when binding a reference to
4898/// an rvalue.
4899///
4900/// \returns An expression that copies the initializer expression into
4901/// a temporary object, or an error expression if a copy could not be
4902/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004903static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004904 QualType T,
4905 const InitializedEntity &Entity,
4906 ExprResult CurInit,
4907 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004908 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004909 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004910 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004911 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004912 Class = cast<CXXRecordDecl>(Record->getDecl());
4913 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004914 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004915
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004916 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004917 // When certain criteria are met, an implementation is allowed to
4918 // omit the copy/move construction of a class object, even if the
4919 // copy/move constructor and/or destructor for the object have
4920 // side effects. [...]
4921 // - when a temporary class object that has not been bound to a
4922 // reference (12.2) would be copied/moved to a class object
4923 // with the same cv-unqualified type, the copy/move operation
4924 // can be omitted by constructing the temporary object
4925 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004926 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004927 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004928 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004929 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004930 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004931 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004932 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004933
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004934 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004935 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004936 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004937
Douglas Gregorcc15f012011-01-21 19:38:21 +00004938 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004939 // Only consider constructors and constructor templates. Per
4940 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4941 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004942 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004943 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004944
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004945 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4946
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004947 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004948 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004949 case OR_Success:
4950 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004951
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004952 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004953 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4954 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4955 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004956 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004957 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004958 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004959 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004960 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004961 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004962
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004963 case OR_Ambiguous:
4964 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004965 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004966 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004967 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004968 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004969
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004970 case OR_Deleted:
4971 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004972 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004973 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004974 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004975 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004976 }
4977
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004978 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004979 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004980 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004981
Anders Carlsson9a68a672010-04-21 18:47:17 +00004982 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004983 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004984
4985 if (IsExtraneousCopy) {
4986 // If this is a totally extraneous copy for C++03 reference
4987 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004988 // expression. We don't generate an (elided) copy operation here
4989 // because doing so would require us to pass down a flag to avoid
4990 // infinite recursion, where each step adds another extraneous,
4991 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004992
Douglas Gregor2559a702010-04-18 07:57:34 +00004993 // Instantiate the default arguments of any extra parameters in
4994 // the selected copy constructor, as if we were going to create a
4995 // proper call to the copy constructor.
4996 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4997 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4998 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004999 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00005000 break;
5001
5002 // Build the default argument expression; we don't actually care
5003 // if this succeeds or not, because this routine will complain
5004 // if there was a problem.
5005 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5006 }
5007
Douglas Gregor523d46a2010-04-18 07:40:54 +00005008 return S.Owned(CurInitExpr);
5009 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005010
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005011 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00005012 // constructor call (we might have derived-to-base conversions, or
5013 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005014 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005015 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005016
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005017 // Actually perform the constructor call.
5018 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005019 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005020 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005021 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005022 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005023 CXXConstructExpr::CK_Complete,
5024 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005025
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005026 // If we're supposed to bind temporaries, do so.
5027 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5028 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005029 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005030}
Douglas Gregor20093b42009-12-09 23:02:17 +00005031
Richard Smith83da2e72011-10-19 16:55:56 +00005032/// \brief Check whether elidable copy construction for binding a reference to
5033/// a temporary would have succeeded if we were building in C++98 mode, for
5034/// -Wc++98-compat.
5035static void CheckCXX98CompatAccessibleCopy(Sema &S,
5036 const InitializedEntity &Entity,
5037 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00005038 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00005039
5040 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5041 if (!Record)
5042 return;
5043
5044 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5045 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
5046 == DiagnosticsEngine::Ignored)
5047 return;
5048
5049 // Find constructors which would have been considered.
5050 OverloadCandidateSet CandidateSet(Loc);
5051 LookupCopyAndMoveConstructors(
5052 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5053
5054 // Perform overload resolution.
5055 OverloadCandidateSet::iterator Best;
5056 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5057
5058 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5059 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5060 << CurInitExpr->getSourceRange();
5061
5062 switch (OR) {
5063 case OR_Success:
5064 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00005065 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00005066 // FIXME: Check default arguments as far as that's possible.
5067 break;
5068
5069 case OR_No_Viable_Function:
5070 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005071 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005072 break;
5073
5074 case OR_Ambiguous:
5075 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005076 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005077 break;
5078
5079 case OR_Deleted:
5080 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005081 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00005082 break;
5083 }
5084}
5085
Douglas Gregora41a8c52010-04-22 00:20:18 +00005086void InitializationSequence::PrintInitLocationNote(Sema &S,
5087 const InitializedEntity &Entity) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005088 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregora41a8c52010-04-22 00:20:18 +00005089 if (Entity.getDecl()->getLocation().isInvalid())
5090 return;
5091
5092 if (Entity.getDecl()->getDeclName())
5093 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5094 << Entity.getDecl()->getDeclName();
5095 else
5096 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5097 }
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005098 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5099 Entity.getMethodDecl())
5100 S.Diag(Entity.getMethodDecl()->getLocation(),
5101 diag::note_method_return_type_change)
5102 << Entity.getMethodDecl()->getDeclName();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005103}
5104
Sebastian Redl3b802322011-07-14 19:07:55 +00005105static bool isReferenceBinding(const InitializationSequence::Step &s) {
5106 return s.Kind == InitializationSequence::SK_BindReference ||
5107 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5108}
5109
Jordan Rose2624b812013-05-06 16:48:12 +00005110/// Returns true if the parameters describe a constructor initialization of
5111/// an explicit temporary object, e.g. "Point(x, y)".
5112static bool isExplicitTemporary(const InitializedEntity &Entity,
5113 const InitializationKind &Kind,
5114 unsigned NumArgs) {
5115 switch (Entity.getKind()) {
5116 case InitializedEntity::EK_Temporary:
5117 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005118 case InitializedEntity::EK_RelatedResult:
Jordan Rose2624b812013-05-06 16:48:12 +00005119 break;
5120 default:
5121 return false;
5122 }
5123
5124 switch (Kind.getKind()) {
5125 case InitializationKind::IK_DirectList:
5126 return true;
5127 // FIXME: Hack to work around cast weirdness.
5128 case InitializationKind::IK_Direct:
5129 case InitializationKind::IK_Value:
5130 return NumArgs != 1;
5131 default:
5132 return false;
5133 }
5134}
5135
Sebastian Redl10f04a62011-12-22 14:44:04 +00005136static ExprResult
5137PerformConstructorInitialization(Sema &S,
5138 const InitializedEntity &Entity,
5139 const InitializationKind &Kind,
5140 MultiExprArg Args,
5141 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005142 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005143 bool IsListInitialization,
5144 SourceLocation LBraceLoc,
5145 SourceLocation RBraceLoc) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005146 unsigned NumArgs = Args.size();
5147 CXXConstructorDecl *Constructor
5148 = cast<CXXConstructorDecl>(Step.Function.Function);
5149 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5150
5151 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005152 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005153 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5154 ? Kind.getEqualLoc()
5155 : Kind.getLocation();
5156
5157 if (Kind.getKind() == InitializationKind::IK_Default) {
5158 // Force even a trivial, implicit default constructor to be
5159 // semantically checked. We do this explicitly because we don't build
5160 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00005161 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00005162 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00005163 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005164 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5165 }
5166
5167 ExprResult CurInit = S.Owned((Expr *)0);
5168
Douglas Gregored878af2012-02-24 23:56:31 +00005169 // C++ [over.match.copy]p1:
5170 // - When initializing a temporary to be bound to the first parameter
5171 // of a constructor that takes a reference to possibly cv-qualified
5172 // T as its first argument, called with a single argument in the
5173 // context of direct-initialization, explicit conversion functions
5174 // are also considered.
5175 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5176 Args.size() == 1 &&
5177 Constructor->isCopyOrMoveConstructor();
5178
Sebastian Redl10f04a62011-12-22 14:44:04 +00005179 // Determine the arguments required to actually perform the constructor
5180 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005181 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00005182 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00005183 AllowExplicitConv,
5184 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005185 return ExprError();
5186
5187
Jordan Rose2624b812013-05-06 16:48:12 +00005188 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005189 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00005190 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005191 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5192 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005193
5194 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5195 if (!TSInfo)
5196 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella1245a542013-09-07 05:49:53 +00005197 SourceRange ParenOrBraceRange =
5198 (Kind.getKind() == InitializationKind::IK_DirectList)
5199 ? SourceRange(LBraceLoc, RBraceLoc)
5200 : Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005201
Richard Smithc83c2302012-12-19 01:39:02 +00005202 CurInit = S.Owned(
5203 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5204 TSInfo, ConstructorArgs,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005205 ParenOrBraceRange,
Richard Smithc83c2302012-12-19 01:39:02 +00005206 HadMultipleCandidates,
Enea Zaffanella14dcaa92013-09-07 11:22:02 +00005207 IsListInitialization,
Richard Smithc83c2302012-12-19 01:39:02 +00005208 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00005209 } else {
5210 CXXConstructExpr::ConstructionKind ConstructKind =
5211 CXXConstructExpr::CK_Complete;
5212
5213 if (Entity.getKind() == InitializedEntity::EK_Base) {
5214 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5215 CXXConstructExpr::CK_VirtualBase :
5216 CXXConstructExpr::CK_NonVirtualBase;
5217 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5218 ConstructKind = CXXConstructExpr::CK_Delegating;
5219 }
5220
5221 // Only get the parenthesis range if it is a direct construction.
5222 SourceRange parenRange =
5223 Kind.getKind() == InitializationKind::IK_Direct ?
5224 Kind.getParenRange() : SourceRange();
5225
5226 // If the entity allows NRVO, mark the construction as elidable
5227 // unconditionally.
5228 if (Entity.allowsNRVO())
5229 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5230 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005231 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005232 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005233 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005234 ConstructorInitRequiresZeroInit,
5235 ConstructKind,
5236 parenRange);
5237 else
5238 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5239 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005240 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005241 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005242 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005243 ConstructorInitRequiresZeroInit,
5244 ConstructKind,
5245 parenRange);
5246 }
5247 if (CurInit.isInvalid())
5248 return ExprError();
5249
5250 // Only check access if all of that succeeded.
5251 S.CheckConstructorAccess(Loc, Constructor, Entity,
5252 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005253 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5254 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005255
5256 if (shouldBindAsTemporary(Entity))
Richard Smith7c3e6152013-06-12 22:31:48 +00005257 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redl10f04a62011-12-22 14:44:04 +00005258
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005259 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005260}
5261
Richard Smith36d02af2012-06-04 22:27:30 +00005262/// Determine whether the specified InitializedEntity definitely has a lifetime
5263/// longer than the current full-expression. Conservatively returns false if
5264/// it's unclear.
5265static bool
5266InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5267 const InitializedEntity *Top = &Entity;
5268 while (Top->getParent())
5269 Top = Top->getParent();
5270
5271 switch (Top->getKind()) {
5272 case InitializedEntity::EK_Variable:
5273 case InitializedEntity::EK_Result:
5274 case InitializedEntity::EK_Exception:
5275 case InitializedEntity::EK_Member:
5276 case InitializedEntity::EK_New:
5277 case InitializedEntity::EK_Base:
5278 case InitializedEntity::EK_Delegating:
5279 return true;
5280
5281 case InitializedEntity::EK_ArrayElement:
5282 case InitializedEntity::EK_VectorElement:
5283 case InitializedEntity::EK_BlockElement:
5284 case InitializedEntity::EK_ComplexElement:
5285 // Could not determine what the full initialization is. Assume it might not
5286 // outlive the full-expression.
5287 return false;
5288
5289 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005290 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith36d02af2012-06-04 22:27:30 +00005291 case InitializedEntity::EK_Temporary:
5292 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005293 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005294 case InitializedEntity::EK_RelatedResult:
Richard Smith36d02af2012-06-04 22:27:30 +00005295 // The entity being initialized might not outlive the full-expression.
5296 return false;
5297 }
5298
5299 llvm_unreachable("unknown entity kind");
5300}
5301
Richard Smith211c8dd2013-06-05 00:46:14 +00005302/// Determine the declaration which an initialized entity ultimately refers to,
5303/// for the purpose of lifetime-extending a temporary bound to a reference in
5304/// the initialization of \p Entity.
5305static const ValueDecl *
5306getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5307 const ValueDecl *FallbackDecl = 0) {
5308 // C++11 [class.temporary]p5:
5309 switch (Entity.getKind()) {
5310 case InitializedEntity::EK_Variable:
5311 // The temporary [...] persists for the lifetime of the reference
5312 return Entity.getDecl();
5313
5314 case InitializedEntity::EK_Member:
5315 // For subobjects, we look at the complete object.
5316 if (Entity.getParent())
5317 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5318 Entity.getDecl());
5319
5320 // except:
5321 // -- A temporary bound to a reference member in a constructor's
5322 // ctor-initializer persists until the constructor exits.
5323 return Entity.getDecl();
5324
5325 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005326 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith211c8dd2013-06-05 00:46:14 +00005327 // -- A temporary bound to a reference parameter in a function call
5328 // persists until the completion of the full-expression containing
5329 // the call.
5330 case InitializedEntity::EK_Result:
5331 // -- The lifetime of a temporary bound to the returned value in a
5332 // function return statement is not extended; the temporary is
5333 // destroyed at the end of the full-expression in the return statement.
5334 case InitializedEntity::EK_New:
5335 // -- A temporary bound to a reference in a new-initializer persists
5336 // until the completion of the full-expression containing the
5337 // new-initializer.
5338 return 0;
5339
5340 case InitializedEntity::EK_Temporary:
5341 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005342 case InitializedEntity::EK_RelatedResult:
Richard Smith211c8dd2013-06-05 00:46:14 +00005343 // We don't yet know the storage duration of the surrounding temporary.
5344 // Assume it's got full-expression duration for now, it will patch up our
5345 // storage duration if that's not correct.
5346 return 0;
5347
5348 case InitializedEntity::EK_ArrayElement:
5349 // For subobjects, we look at the complete object.
5350 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5351 FallbackDecl);
5352
5353 case InitializedEntity::EK_Base:
5354 case InitializedEntity::EK_Delegating:
5355 // We can reach this case for aggregate initialization in a constructor:
5356 // struct A { int &&r; };
5357 // struct B : A { B() : A{0} {} };
5358 // In this case, use the innermost field decl as the context.
5359 return FallbackDecl;
5360
5361 case InitializedEntity::EK_BlockElement:
5362 case InitializedEntity::EK_LambdaCapture:
5363 case InitializedEntity::EK_Exception:
5364 case InitializedEntity::EK_VectorElement:
5365 case InitializedEntity::EK_ComplexElement:
Richard Smithd6b69872013-06-15 00:30:29 +00005366 return 0;
Richard Smith211c8dd2013-06-05 00:46:14 +00005367 }
Benjamin Kramer6f773e82013-06-05 15:37:50 +00005368 llvm_unreachable("unknown entity kind");
Richard Smith211c8dd2013-06-05 00:46:14 +00005369}
5370
5371static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5372
5373/// Update a glvalue expression that is used as the initializer of a reference
5374/// to note that its lifetime is extended.
Richard Smithd6b69872013-06-15 00:30:29 +00005375/// \return \c true if any temporary had its lifetime extended.
5376static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005377 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5378 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5379 // This is just redundant braces around an initializer. Step over it.
5380 Init = ILE->getInit(0);
5381 }
5382 }
5383
Richard Smithd6b69872013-06-15 00:30:29 +00005384 // Walk past any constructs which we can lifetime-extend across.
5385 Expr *Old;
5386 do {
5387 Old = Init;
5388
5389 // Step over any subobject adjustments; we may have a materialized
5390 // temporary inside them.
5391 SmallVector<const Expr *, 2> CommaLHSs;
5392 SmallVector<SubobjectAdjustment, 2> Adjustments;
5393 Init = const_cast<Expr *>(
5394 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5395
5396 // Per current approach for DR1376, look through casts to reference type
5397 // when performing lifetime extension.
5398 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5399 if (CE->getSubExpr()->isGLValue())
5400 Init = CE->getSubExpr();
5401
5402 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5403 // It's unclear if binding a reference to that xvalue extends the array
5404 // temporary.
5405 } while (Init != Old);
5406
Richard Smith211c8dd2013-06-05 00:46:14 +00005407 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5408 // Update the storage duration of the materialized temporary.
5409 // FIXME: Rebuild the expression instead of mutating it.
5410 ME->setExtendingDecl(ExtendingD);
5411 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
Richard Smithd6b69872013-06-15 00:30:29 +00005412 return true;
Richard Smith211c8dd2013-06-05 00:46:14 +00005413 }
Richard Smithd6b69872013-06-15 00:30:29 +00005414
5415 return false;
Richard Smith211c8dd2013-06-05 00:46:14 +00005416}
5417
5418/// Update a prvalue expression that is going to be materialized as a
5419/// lifetime-extended temporary.
5420static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5421 // Dig out the expression which constructs the extended temporary.
5422 SmallVector<const Expr *, 2> CommaLHSs;
5423 SmallVector<SubobjectAdjustment, 2> Adjustments;
5424 Init = const_cast<Expr *>(
5425 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5426
Richard Smith8a07cd32013-06-12 20:42:33 +00005427 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5428 Init = BTE->getSubExpr();
5429
Richard Smith7c3e6152013-06-12 22:31:48 +00005430 if (CXXStdInitializerListExpr *ILE =
Richard Smithd6b69872013-06-15 00:30:29 +00005431 dyn_cast<CXXStdInitializerListExpr>(Init)) {
5432 performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5433 return;
5434 }
Richard Smith7c3e6152013-06-12 22:31:48 +00005435
Richard Smith211c8dd2013-06-05 00:46:14 +00005436 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith7c3e6152013-06-12 22:31:48 +00005437 if (ILE->getType()->isArrayType()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005438 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5439 performLifetimeExtension(ILE->getInit(I), ExtendingD);
5440 return;
5441 }
5442
Richard Smith7c3e6152013-06-12 22:31:48 +00005443 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005444 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5445
5446 // If we lifetime-extend a braced initializer which is initializing an
5447 // aggregate, and that aggregate contains reference members which are
5448 // bound to temporaries, those temporaries are also lifetime-extended.
5449 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5450 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5451 performReferenceExtension(ILE->getInit(0), ExtendingD);
5452 else {
5453 unsigned Index = 0;
5454 for (RecordDecl::field_iterator I = RD->field_begin(),
5455 E = RD->field_end();
5456 I != E; ++I) {
Richard Smith3c3af142013-07-01 06:08:20 +00005457 if (Index >= ILE->getNumInits())
5458 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005459 if (I->isUnnamedBitfield())
5460 continue;
Richard Smith5771aab2013-06-27 22:54:33 +00005461 Expr *SubInit = ILE->getInit(Index);
Richard Smith211c8dd2013-06-05 00:46:14 +00005462 if (I->getType()->isReferenceType())
Richard Smith5771aab2013-06-27 22:54:33 +00005463 performReferenceExtension(SubInit, ExtendingD);
5464 else if (isa<InitListExpr>(SubInit) ||
5465 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smith211c8dd2013-06-05 00:46:14 +00005466 // This may be either aggregate-initialization of a member or
5467 // initialization of a std::initializer_list object. Either way,
5468 // we should recursively lifetime-extend that initializer.
Richard Smith5771aab2013-06-27 22:54:33 +00005469 performLifetimeExtension(SubInit, ExtendingD);
Richard Smith211c8dd2013-06-05 00:46:14 +00005470 ++Index;
5471 }
5472 }
5473 }
5474 }
5475}
5476
Richard Smith7c3e6152013-06-12 22:31:48 +00005477static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5478 const Expr *Init, bool IsInitializerList,
5479 const ValueDecl *ExtendingDecl) {
5480 // Warn if a field lifetime-extends a temporary.
5481 if (isa<FieldDecl>(ExtendingDecl)) {
5482 if (IsInitializerList) {
5483 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5484 << /*at end of constructor*/true;
5485 return;
5486 }
5487
5488 bool IsSubobjectMember = false;
5489 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5490 Ent = Ent->getParent()) {
5491 if (Ent->getKind() != InitializedEntity::EK_Base) {
5492 IsSubobjectMember = true;
5493 break;
5494 }
5495 }
5496 S.Diag(Init->getExprLoc(),
5497 diag::warn_bind_ref_member_to_temporary)
5498 << ExtendingDecl << Init->getSourceRange()
5499 << IsSubobjectMember << IsInitializerList;
5500 if (IsSubobjectMember)
5501 S.Diag(ExtendingDecl->getLocation(),
5502 diag::note_ref_subobject_of_member_declared_here);
5503 else
5504 S.Diag(ExtendingDecl->getLocation(),
5505 diag::note_ref_or_ptr_member_declared_here)
5506 << /*is pointer*/false;
5507 }
5508}
5509
Richard Smith13b228d2013-09-21 21:19:19 +00005510static void DiagnoseNarrowingInInitList(Sema &S,
5511 const ImplicitConversionSequence &ICS,
5512 QualType PreNarrowingType,
5513 QualType EntityType,
5514 const Expr *PostInit);
5515
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005516ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005517InitializationSequence::Perform(Sema &S,
5518 const InitializedEntity &Entity,
5519 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005520 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005521 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005522 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005523 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005524 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005525 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005526
Sebastian Redl7491c492011-06-05 13:59:11 +00005527 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005528 // If the declaration is a non-dependent, incomplete array type
5529 // that has an initializer, then its type will be completed once
5530 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005531 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005532 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005533 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005534 if (const IncompleteArrayType *ArrayT
5535 = S.Context.getAsIncompleteArrayType(DeclType)) {
5536 // FIXME: We don't currently have the ability to accurately
5537 // compute the length of an initializer list without
5538 // performing full type-checking of the initializer list
5539 // (since we have to determine where braces are implicitly
5540 // introduced and such). So, we fall back to making the array
5541 // type a dependently-sized array type with no specified
5542 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005543 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005544 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005545
Douglas Gregord87b61f2009-12-10 17:56:55 +00005546 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005547 if (DeclaratorDecl *DD = Entity.getDecl()) {
5548 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5549 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005550 if (IncompleteArrayTypeLoc ArrayLoc =
5551 TL.getAs<IncompleteArrayTypeLoc>())
5552 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005553 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005554 }
5555
5556 *ResultType
5557 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5558 /*NumElts=*/0,
5559 ArrayT->getSizeModifier(),
5560 ArrayT->getIndexTypeCVRQualifiers(),
5561 Brackets);
5562 }
5563
5564 }
5565 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005566 if (Kind.getKind() == InitializationKind::IK_Direct &&
5567 !Kind.isExplicitCast()) {
5568 // Rebuild the ParenListExpr.
5569 SourceRange ParenRange = Kind.getParenRange();
5570 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005571 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005572 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005573 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005574 Kind.isExplicitCast() ||
5575 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005576 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005577 }
5578
Sebastian Redl7491c492011-06-05 13:59:11 +00005579 // No steps means no initialization.
5580 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005581 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005582
Richard Smith80ad52f2013-01-02 11:42:31 +00005583 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005584 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005585 !Entity.isParameterKind()) {
Richard Smith03544fc2012-04-19 06:58:00 +00005586 // Produce a C++98 compatibility warning if we are initializing a reference
5587 // from an initializer list. For parameters, we produce a better warning
5588 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005589 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005590 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5591 << Init->getSourceRange();
5592 }
5593
Richard Smith36d02af2012-06-04 22:27:30 +00005594 // Diagnose cases where we initialize a pointer to an array temporary, and the
5595 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005596 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005597 Entity.getType()->isPointerType() &&
5598 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005599 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005600 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5601 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5602 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5603 << Init->getSourceRange();
5604 }
5605
Douglas Gregord6542d82009-12-22 15:35:07 +00005606 QualType DestType = Entity.getType().getNonReferenceType();
5607 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005608 // the same as Entity.getDecl()->getType() in cases involving type merging,
5609 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005610 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005611 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005612 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005613
John McCall60d7b3a2010-08-24 06:29:42 +00005614 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005615
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005616 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005617 // grab the only argument out the Args and place it into the "current"
5618 // initializer.
5619 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005620 case SK_ResolveAddressOfOverloadedFunction:
5621 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005622 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005623 case SK_CastDerivedToBaseLValue:
5624 case SK_BindReference:
5625 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005626 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005627 case SK_UserConversion:
5628 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005629 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005630 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005631 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005632 case SK_ConversionSequence:
Richard Smith13b228d2013-09-21 21:19:19 +00005633 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005634 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005635 case SK_UnwrapInitList:
5636 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005637 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005638 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005639 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005640 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005641 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005642 case SK_PassByIndirectCopyRestore:
5643 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005644 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005645 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005646 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005647 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005648 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005649 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005650 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005651 break;
John McCallf6a16482010-12-04 03:47:34 +00005652 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005653
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005654 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005655 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005656 case SK_ZeroInitialization:
5657 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005658 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005659
5660 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005661 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005662 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005663 for (step_iterator Step = step_begin(), StepEnd = step_end();
5664 Step != StepEnd; ++Step) {
5665 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005666 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005667
John Wiegley429bb272011-04-08 18:41:53 +00005668 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005669
Douglas Gregor20093b42009-12-09 23:02:17 +00005670 switch (Step->Kind) {
5671 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005672 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005673 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005674 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005675 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5676 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005677 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005678 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005679 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005680 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005681
Douglas Gregor20093b42009-12-09 23:02:17 +00005682 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005683 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005684 case SK_CastDerivedToBaseLValue: {
5685 // We have a derived-to-base cast that produces either an rvalue or an
5686 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005687
John McCallf871d0c2010-08-07 06:22:56 +00005688 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005689
Douglas Gregor20093b42009-12-09 23:02:17 +00005690 // Casts to inaccessible base classes are allowed with C-style casts.
5691 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5692 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005693 CurInit.get()->getLocStart(),
5694 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005695 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005696 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005697
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005698 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5699 QualType T = SourceType;
5700 if (const PointerType *Pointer = T->getAs<PointerType>())
5701 T = Pointer->getPointeeType();
5702 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005703 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005704 cast<CXXRecordDecl>(RecordTy->getDecl()));
5705 }
5706
John McCall5baba9d2010-08-25 10:28:54 +00005707 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005708 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005709 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005710 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005711 VK_XValue :
5712 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005713 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5714 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005715 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005716 CurInit.get(),
5717 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005718 break;
5719 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005720
Douglas Gregor20093b42009-12-09 23:02:17 +00005721 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005722 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5723 if (CurInit.get()->refersToBitField()) {
5724 // We don't necessarily have an unambiguous source bit-field.
5725 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005726 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005727 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005728 << (BitField ? BitField->getDeclName() : DeclarationName())
5729 << (BitField != NULL)
John Wiegley429bb272011-04-08 18:41:53 +00005730 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005731 if (BitField)
5732 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5733
John McCallf312b1e2010-08-26 23:41:50 +00005734 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005735 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005736
John Wiegley429bb272011-04-08 18:41:53 +00005737 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005738 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005739 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5740 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005741 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005742 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005743 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005744 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005745
Douglas Gregor20093b42009-12-09 23:02:17 +00005746 // Reference binding does not have any corresponding ASTs.
5747
5748 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005749 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005750 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005751
Richard Smithd6b69872013-06-15 00:30:29 +00005752 // Even though we didn't materialize a temporary, the binding may still
5753 // extend the lifetime of a temporary. This happens if we bind a reference
5754 // to the result of a cast to reference type.
5755 if (const ValueDecl *ExtendingDecl =
5756 getDeclForTemporaryLifetimeExtension(Entity)) {
5757 if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5758 warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5759 ExtendingDecl);
5760 }
5761
Douglas Gregor20093b42009-12-09 23:02:17 +00005762 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005763
Richard Smith211c8dd2013-06-05 00:46:14 +00005764 case SK_BindReferenceToTemporary: {
Jordan Rose1fd1e282013-04-11 00:58:58 +00005765 // Make sure the "temporary" is actually an rvalue.
5766 assert(CurInit.get()->isRValue() && "not a temporary");
5767
Douglas Gregor20093b42009-12-09 23:02:17 +00005768 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005769 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005770 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005771
Richard Smith211c8dd2013-06-05 00:46:14 +00005772 // Maybe lifetime-extend the temporary's subobjects to match the
5773 // entity's lifetime.
5774 const ValueDecl *ExtendingDecl =
5775 getDeclForTemporaryLifetimeExtension(Entity);
Richard Smitha4bb99c2013-06-12 21:51:50 +00005776 if (ExtendingDecl) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005777 performLifetimeExtension(CurInit.get(), ExtendingDecl);
Richard Smith7c3e6152013-06-12 22:31:48 +00005778 warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
Richard Smitha4bb99c2013-06-12 21:51:50 +00005779 }
5780
Douglas Gregor03e80032011-06-21 17:03:29 +00005781 // Materialize the temporary into memory.
Richard Smith8a07cd32013-06-12 20:42:33 +00005782 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smith211c8dd2013-06-05 00:46:14 +00005783 Entity.getType().getNonReferenceType(), CurInit.get(),
5784 Entity.getType()->isLValueReferenceType(), ExtendingDecl);
Douglas Gregord7b23162011-06-22 16:12:01 +00005785
5786 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith8a07cd32013-06-12 20:42:33 +00005787 // need cleanups. Likewise if we're extending this temporary to automatic
5788 // storage duration -- we need to register its cleanup during the
5789 // full-expression's cleanups.
5790 if ((S.getLangOpts().ObjCAutoRefCount &&
5791 MTE->getType()->isObjCLifetimeType()) ||
5792 (MTE->getStorageDuration() == SD_Automatic &&
5793 MTE->getType().isDestructedType()))
Douglas Gregord7b23162011-06-22 16:12:01 +00005794 S.ExprNeedsCleanups = true;
Richard Smith8a07cd32013-06-12 20:42:33 +00005795
5796 CurInit = S.Owned(MTE);
Douglas Gregor20093b42009-12-09 23:02:17 +00005797 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005798 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005799
Douglas Gregor523d46a2010-04-18 07:40:54 +00005800 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005801 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005802 /*IsExtraneousCopy=*/true);
5803 break;
5804
Douglas Gregor20093b42009-12-09 23:02:17 +00005805 case SK_UserConversion: {
5806 // We have a user-defined conversion that invokes either a constructor
5807 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005808 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005809 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005810 FunctionDecl *Fn = Step->Function.Function;
5811 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005812 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005813 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005814 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005815 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005816 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005817 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005818 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005819
Douglas Gregor20093b42009-12-09 23:02:17 +00005820 // Determine the arguments required to actually perform the constructor
5821 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005822 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005823 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005824 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005825 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005826 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005827
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005828 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005829 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005830 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005831 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005832 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005833 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005834 CXXConstructExpr::CK_Complete,
5835 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005836 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005837 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005838
Anders Carlsson9a68a672010-04-21 18:47:17 +00005839 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005840 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005841 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5842 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005843
John McCall2de56d12010-08-25 11:45:40 +00005844 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005845 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5846 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5847 S.IsDerivedFrom(SourceType, Class))
5848 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005849
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005850 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005851 } else {
5852 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005853 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005854 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005855 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005856 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5857 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005858
5859 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005860 // derived-to-base conversion? I believe the answer is "no", because
5861 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005862 ExprResult CurInitExprRes =
5863 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5864 FoundFn, Conversion);
5865 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005866 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005867 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005868
Douglas Gregor20093b42009-12-09 23:02:17 +00005869 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005870 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5871 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005872 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005873 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005874
John McCall2de56d12010-08-25 11:45:40 +00005875 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005876
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005877 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005878 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005879
Sebastian Redl3b802322011-07-14 19:07:55 +00005880 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005881 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5882
5883 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005884 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005885 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005886 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005887 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005888 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005889 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005890 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005891 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5892 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005893 }
5894 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005895
John McCallf871d0c2010-08-07 06:22:56 +00005896 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005897 CurInit.get()->getType(),
5898 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005899 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005900 if (MaybeBindToTemp)
5901 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005902 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005903 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005904 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005905 break;
5906 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005907
Douglas Gregor20093b42009-12-09 23:02:17 +00005908 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005909 case SK_QualificationConversionXValue:
5910 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005911 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005912 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005913 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005914 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005915 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005916 VK_XValue :
5917 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005918 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005919 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005920 }
5921
Jordan Rose1fd1e282013-04-11 00:58:58 +00005922 case SK_LValueToRValue: {
5923 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5924 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5925 CK_LValueToRValue,
5926 CurInit.take(),
5927 /*BasePath=*/0,
5928 VK_RValue));
5929 break;
5930 }
5931
Richard Smith13b228d2013-09-21 21:19:19 +00005932 case SK_ConversionSequence:
5933 case SK_ConversionSequenceNoNarrowing: {
5934 Sema::CheckedConversionKind CCK
John McCallf85e1932011-06-15 23:02:42 +00005935 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5936 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005937 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005938 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005939 ExprResult CurInitExprRes =
5940 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005941 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005942 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005943 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005944 CurInit = CurInitExprRes;
Richard Smith13b228d2013-09-21 21:19:19 +00005945
5946 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5947 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5948 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5949 CurInit.get());
Douglas Gregor20093b42009-12-09 23:02:17 +00005950 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005951 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005952
Douglas Gregord87b61f2009-12-10 17:56:55 +00005953 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005954 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smith7c3e6152013-06-12 22:31:48 +00005955 // If we're not initializing the top-level entity, we need to create an
5956 // InitializeTemporary entity for our target type.
5957 QualType Ty = Step->Type;
5958 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005959 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005960 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5961 InitListChecker PerformInitList(S, InitEntity,
Richard Smith40cba902013-06-06 11:41:05 +00005962 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005963 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005964 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005965
Richard Smith7c3e6152013-06-12 22:31:48 +00005966 // Hack: We must update *ResultType if available in order to set the
5967 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5968 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5969 if (ResultType &&
5970 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005971 if ((*ResultType)->isRValueReferenceType())
5972 Ty = S.Context.getRValueReferenceType(Ty);
5973 else if ((*ResultType)->isLValueReferenceType())
5974 Ty = S.Context.getLValueReferenceType(Ty,
5975 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5976 *ResultType = Ty;
5977 }
5978
5979 InitListExpr *StructuredInitList =
5980 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005981 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005982 CurInit = shouldBindAsTemporary(InitEntity)
5983 ? S.MaybeBindToTemporary(StructuredInitList)
5984 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005985 break;
5986 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005987
Sebastian Redl10f04a62011-12-22 14:44:04 +00005988 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005989 // When an initializer list is passed for a parameter of type "reference
5990 // to object", we don't get an EK_Temporary entity, but instead an
5991 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005992 // FIXME: This is a hack. What we really should do is create a user
5993 // conversion step for this case, but this makes it considerably more
5994 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005995 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5996 Entity.getType().getNonReferenceType());
5997 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005998 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005999 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00006000 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6001 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00006002 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00006003 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6004 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006005 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00006006 ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00006007 /*IsListInitialization*/ true,
6008 InitList->getLBraceLoc(),
6009 InitList->getRBraceLoc());
Sebastian Redl10f04a62011-12-22 14:44:04 +00006010 break;
6011 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006012
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006013 case SK_UnwrapInitList:
6014 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
6015 break;
6016
6017 case SK_RewrapInitList: {
6018 Expr *E = CurInit.take();
6019 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6020 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00006021 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006022 ILE->setSyntacticForm(Syntactic);
6023 ILE->setType(E->getType());
6024 ILE->setValueKind(E->getValueKind());
6025 CurInit = S.Owned(ILE);
6026 break;
6027 }
6028
Sebastian Redlbac5cf42012-02-19 12:27:56 +00006029 case SK_ConstructorInitialization: {
6030 // When an initializer list is passed for a parameter of type "reference
6031 // to object", we don't get an EK_Temporary entity, but instead an
6032 // EK_Parameter entity with reference type.
6033 // FIXME: This is a hack. What we really should do is create a user
6034 // conversion step for this case, but this makes it considerably more
6035 // complicated. For now, this will do.
6036 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6037 Entity.getType().getNonReferenceType());
6038 bool UseTemporary = Entity.getType()->isReferenceType();
6039 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6040 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006041 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00006042 ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00006043 /*IsListInitialization*/ false,
6044 /*LBraceLoc*/ SourceLocation(),
6045 /*RBraceLoc*/ SourceLocation());
Douglas Gregor51c56d62009-12-14 20:49:26 +00006046 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00006047 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006048
Douglas Gregor71d17402009-12-15 00:01:57 +00006049 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00006050 step_iterator NextStep = Step;
6051 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006052 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00006053 (NextStep->Kind == SK_ConstructorInitialization ||
6054 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00006055 // The need for zero-initialization is recorded directly into
6056 // the call to the object's constructor within the next step.
6057 ConstructorInitRequiresZeroInit = true;
6058 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006059 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00006060 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00006061 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6062 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006063 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00006064 Kind.getRange().getBegin());
6065
6066 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
6067 TSInfo->getType().getNonLValueExprType(S.Context),
6068 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00006069 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00006070 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00006071 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00006072 }
Douglas Gregor71d17402009-12-15 00:01:57 +00006073 break;
6074 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006075
6076 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00006077 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006078 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006079 Sema::AssignConvertType ConvTy =
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00006080 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6081 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley429bb272011-04-08 18:41:53 +00006082 if (Result.isInvalid())
6083 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006084 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00006085
6086 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006087 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00006088 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006089 Entity.isParameterKind() &&
John Wiegley429bb272011-04-08 18:41:53 +00006090 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00006091 == Sema::Compatible)
6092 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00006093 if (CurInitExprRes.isInvalid())
6094 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006095 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00006096
Douglas Gregora41a8c52010-04-22 00:20:18 +00006097 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006098 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6099 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00006100 CurInit.get(),
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00006101 getAssignmentAction(Entity, true),
Douglas Gregora41a8c52010-04-22 00:20:18 +00006102 &Complained)) {
6103 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00006104 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00006105 } else if (Complained)
6106 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006107 break;
6108 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006109
6110 case SK_StringInit: {
6111 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00006112 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00006113 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006114 break;
6115 }
Douglas Gregor569c3162010-08-07 11:51:51 +00006116
6117 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00006118 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00006119 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00006120 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00006121 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006122
6123 case SK_ArrayInit:
6124 // Okay: we checked everything before creating this step. Note that
6125 // this is a GNU extension.
6126 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00006127 << Step->Type << CurInit.get()->getType()
6128 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006129
6130 // If the destination type is an incomplete array type, update the
6131 // type accordingly.
6132 if (ResultType) {
6133 if (const IncompleteArrayType *IncompleteDest
6134 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6135 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00006136 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006137 *ResultType = S.Context.getConstantArrayType(
6138 IncompleteDest->getElementType(),
6139 ConstantSource->getSize(),
6140 ArrayType::Normal, 0);
6141 }
6142 }
6143 }
John McCallf85e1932011-06-15 23:02:42 +00006144 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006145
Richard Smith0f163e92012-02-15 22:38:09 +00006146 case SK_ParenthesizedArrayInit:
6147 // Okay: we checked everything before creating this step. Note that
6148 // this is a GNU extension.
6149 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6150 << CurInit.get()->getSourceRange();
6151 break;
6152
John McCallf85e1932011-06-15 23:02:42 +00006153 case SK_PassByIndirectCopyRestore:
6154 case SK_PassByIndirectRestore:
6155 checkIndirectCopyRestoreSource(S, CurInit.get());
6156 CurInit = S.Owned(new (S.Context)
6157 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6158 Step->Kind == SK_PassByIndirectCopyRestore));
6159 break;
6160
6161 case SK_ProduceObjCObject:
6162 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00006163 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00006164 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006165 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006166
6167 case SK_StdInitializerList: {
Richard Smith7c3e6152013-06-12 22:31:48 +00006168 S.Diag(CurInit.get()->getExprLoc(),
6169 diag::warn_cxx98_compat_initializer_list_init)
6170 << CurInit.get()->getSourceRange();
Sebastian Redl28357452012-03-05 19:35:43 +00006171
Richard Smith7c3e6152013-06-12 22:31:48 +00006172 // Maybe lifetime-extend the array temporary's subobjects to match the
6173 // entity's lifetime.
6174 const ValueDecl *ExtendingDecl =
6175 getDeclForTemporaryLifetimeExtension(Entity);
6176 if (ExtendingDecl) {
6177 performLifetimeExtension(CurInit.get(), ExtendingDecl);
6178 warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
Sebastian Redl28357452012-03-05 19:35:43 +00006179 }
6180
Richard Smith7c3e6152013-06-12 22:31:48 +00006181 // Materialize the temporary into memory.
6182 MaterializeTemporaryExpr *MTE = new (S.Context)
6183 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6184 /*lvalue reference*/ false, ExtendingDecl);
6185
6186 // Wrap it in a construction of a std::initializer_list<T>.
6187 CurInit = S.Owned(
6188 new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6189
6190 // Bind the result, in case the library has given initializer_list a
6191 // non-trivial destructor.
6192 if (shouldBindAsTemporary(Entity))
6193 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redl2b916b82012-01-17 22:49:42 +00006194 break;
6195 }
Richard Smith7c3e6152013-06-12 22:31:48 +00006196
Guy Benyei21f18c42013-02-07 10:55:47 +00006197 case SK_OCLSamplerInit: {
6198 assert(Step->Type->isSamplerT() &&
6199 "Sampler initialization on non sampler type.");
6200
6201 QualType SourceType = CurInit.get()->getType();
Guy Benyei21f18c42013-02-07 10:55:47 +00006202
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006203 if (Entity.isParameterKind()) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006204 if (!SourceType->isSamplerT())
6205 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6206 << SourceType;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006207 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006208 llvm_unreachable("Invalid EntityKind!");
6209 }
6210
6211 break;
6212 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00006213 case SK_OCLZeroEvent: {
6214 assert(Step->Type->isEventT() &&
6215 "Event initialization on non event type.");
6216
6217 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6218 CK_ZeroToOCLEvent,
6219 CurInit.get()->getValueKind());
6220 break;
6221 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006222 }
6223 }
John McCall15d7d122010-11-11 03:21:53 +00006224
6225 // Diagnose non-fatal problems with the completed initialization.
6226 if (Entity.getKind() == InitializedEntity::EK_Member &&
6227 cast<FieldDecl>(Entity.getDecl())->isBitField())
6228 S.CheckBitFieldInitialization(Kind.getLocation(),
6229 cast<FieldDecl>(Entity.getDecl()),
6230 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006231
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006232 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00006233}
6234
Richard Smithd5bc8672012-12-08 02:01:17 +00006235/// Somewhere within T there is an uninitialized reference subobject.
6236/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00006237static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6238 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006239 if (T->isReferenceType()) {
6240 S.Diag(Loc, diag::err_reference_without_init)
6241 << T.getNonReferenceType();
6242 return true;
6243 }
6244
6245 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6246 if (!RD || !RD->hasUninitializedReferenceMember())
6247 return false;
6248
6249 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6250 FE = RD->field_end(); FI != FE; ++FI) {
6251 if (FI->isUnnamedBitfield())
6252 continue;
6253
6254 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6255 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6256 return true;
6257 }
6258 }
6259
6260 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6261 BE = RD->bases_end();
6262 BI != BE; ++BI) {
6263 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6264 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6265 return true;
6266 }
6267 }
6268
6269 return false;
6270}
6271
6272
Douglas Gregor20093b42009-12-09 23:02:17 +00006273//===----------------------------------------------------------------------===//
6274// Diagnose initialization failures
6275//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00006276
6277/// Emit notes associated with an initialization that failed due to a
6278/// "simple" conversion failure.
6279static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6280 Expr *op) {
6281 QualType destType = entity.getType();
6282 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6283 op->getType()->isObjCObjectPointerType()) {
6284
6285 // Emit a possible note about the conversion failing because the
6286 // operand is a message send with a related result type.
6287 S.EmitRelatedResultTypeNote(op);
6288
6289 // Emit a possible note about a return failing because we're
6290 // expecting a related result type.
6291 if (entity.getKind() == InitializedEntity::EK_Result)
6292 S.EmitRelatedResultTypeNoteForReturn(destType);
6293 }
6294}
6295
Bill Wendling2ca3db42013-11-22 00:01:44 +00006296static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6297 InitListExpr *InitList) {
6298 QualType DestType = Entity.getType();
6299
6300 QualType E;
6301 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6302 QualType ArrayType = S.Context.getConstantArrayType(
6303 E.withConst(),
6304 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6305 InitList->getNumInits()),
6306 clang::ArrayType::Normal, 0);
6307 InitializedEntity HiddenArray =
6308 InitializedEntity::InitializeTemporary(ArrayType);
6309 return diagnoseListInit(S, HiddenArray, InitList);
6310 }
6311
6312 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6313 /*VerifyOnly=*/false);
6314 assert(DiagnoseInitList.HadError() &&
6315 "Inconsistent init list check result.");
6316}
6317
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006318bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00006319 const InitializedEntity &Entity,
6320 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006321 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00006322 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00006323 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006324
Douglas Gregord6542d82009-12-22 15:35:07 +00006325 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00006326 switch (Failure) {
6327 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006328 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006329 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006330 // Dig out the reference subobject which is uninitialized and diagnose it.
6331 // If this is value-initialization, this could be nested some way within
6332 // the target type.
6333 assert(Kind.getKind() == InitializationKind::IK_Value ||
6334 DestType->isReferenceType());
6335 bool Diagnosed =
6336 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6337 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6338 (void)Diagnosed;
6339 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006340 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006341 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00006342 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006343
Douglas Gregor20093b42009-12-09 23:02:17 +00006344 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00006345 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00006346 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00006347 case FK_ArrayNeedsInitListOrStringLiteral:
6348 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6349 break;
6350 case FK_ArrayNeedsInitListOrWideStringLiteral:
6351 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6352 break;
6353 case FK_NarrowStringIntoWideCharArray:
6354 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6355 break;
6356 case FK_WideStringIntoCharArray:
6357 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6358 break;
6359 case FK_IncompatWideStringIntoWideChar:
6360 S.Diag(Kind.getLocation(),
6361 diag::err_array_init_incompat_wide_string_into_wchar);
6362 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006363 case FK_ArrayTypeMismatch:
6364 case FK_NonConstantArrayInit:
Bill Wendling2ca3db42013-11-22 00:01:44 +00006365 S.Diag(Kind.getLocation(),
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006366 (Failure == FK_ArrayTypeMismatch
6367 ? diag::err_array_init_different_type
6368 : diag::err_array_init_non_constant_array))
6369 << DestType.getNonReferenceType()
6370 << Args[0]->getType()
6371 << Args[0]->getSourceRange();
6372 break;
6373
John McCall73076432012-01-05 00:13:19 +00006374 case FK_VariableLengthArrayHasInitializer:
6375 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6376 << Args[0]->getSourceRange();
6377 break;
6378
John McCall6bb80172010-03-30 21:47:33 +00006379 case FK_AddressOfOverloadFailed: {
6380 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006381 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00006382 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00006383 true,
6384 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00006385 break;
John McCall6bb80172010-03-30 21:47:33 +00006386 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006387
Douglas Gregor20093b42009-12-09 23:02:17 +00006388 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00006389 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00006390 switch (FailedOverloadResult) {
6391 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006392 if (Failure == FK_UserConversionOverloadFailed)
6393 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6394 << Args[0]->getType() << DestType
6395 << Args[0]->getSourceRange();
6396 else
6397 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6398 << DestType << Args[0]->getType()
6399 << Args[0]->getSourceRange();
6400
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006401 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006402 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006403
Douglas Gregor20093b42009-12-09 23:02:17 +00006404 case OR_No_Viable_Function:
Larisse Voufo288f76a2013-06-27 03:36:30 +00006405 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo7419d012013-06-27 01:50:25 +00006406 DestType.getNonReferenceType(),
6407 diag::err_typecheck_nonviable_condition_incomplete,
6408 Args[0]->getType(), Args[0]->getSourceRange()))
6409 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6410 << Args[0]->getType() << Args[0]->getSourceRange()
6411 << DestType.getNonReferenceType();
6412
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006413 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006414 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006415
Douglas Gregor20093b42009-12-09 23:02:17 +00006416 case OR_Deleted: {
6417 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6418 << Args[0]->getType() << DestType.getNonReferenceType()
6419 << Args[0]->getSourceRange();
6420 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006421 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006422 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6423 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00006424 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00006425 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00006426 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006427 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00006428 }
6429 break;
6430 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006431
Douglas Gregor20093b42009-12-09 23:02:17 +00006432 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006433 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00006434 }
6435 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006436
Douglas Gregor20093b42009-12-09 23:02:17 +00006437 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006438 if (isa<InitListExpr>(Args[0])) {
6439 S.Diag(Kind.getLocation(),
6440 diag::err_lvalue_reference_bind_to_initlist)
6441 << DestType.getNonReferenceType().isVolatileQualified()
6442 << DestType.getNonReferenceType()
6443 << Args[0]->getSourceRange();
6444 break;
6445 }
6446 // Intentional fallthrough
6447
Douglas Gregor20093b42009-12-09 23:02:17 +00006448 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006449 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00006450 Failure == FK_NonConstLValueReferenceBindingToTemporary
6451 ? diag::err_lvalue_reference_bind_to_temporary
6452 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00006453 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00006454 << DestType.getNonReferenceType()
6455 << Args[0]->getType()
6456 << Args[0]->getSourceRange();
6457 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006458
Douglas Gregor20093b42009-12-09 23:02:17 +00006459 case FK_RValueReferenceBindingToLValue:
6460 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00006461 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00006462 << Args[0]->getSourceRange();
6463 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006464
Douglas Gregor20093b42009-12-09 23:02:17 +00006465 case FK_ReferenceInitDropsQualifiers:
6466 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6467 << DestType.getNonReferenceType()
6468 << Args[0]->getType()
6469 << Args[0]->getSourceRange();
6470 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006471
Douglas Gregor20093b42009-12-09 23:02:17 +00006472 case FK_ReferenceInitFailed:
6473 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6474 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006475 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006476 << Args[0]->getType()
6477 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006478 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006479 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006480
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006481 case FK_ConversionFailed: {
6482 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006483 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006484 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006485 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006486 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006487 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006488 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006489 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6490 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006491 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006492 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006493 }
John Wiegley429bb272011-04-08 18:41:53 +00006494
6495 case FK_ConversionFromPropertyFailed:
6496 // No-op. This error has already been reported.
6497 break;
6498
Douglas Gregord87b61f2009-12-10 17:56:55 +00006499 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006500 SourceRange R;
6501
6502 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006503 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006504 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006505 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006506 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006507
Douglas Gregor19311e72010-09-08 21:40:08 +00006508 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6509 if (Kind.isCStyleOrFunctionalCast())
6510 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6511 << R;
6512 else
6513 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6514 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006515 break;
6516 }
6517
6518 case FK_ReferenceBindingToInitList:
6519 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6520 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6521 break;
6522
6523 case FK_InitListBadDestinationType:
6524 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6525 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6526 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006527
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006528 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006529 case FK_ConstructorOverloadFailed: {
6530 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006531 if (Args.size())
6532 ArgsRange = SourceRange(Args.front()->getLocStart(),
6533 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006534
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006535 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006536 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006537 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006538 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006539 }
6540
Douglas Gregor51c56d62009-12-14 20:49:26 +00006541 // FIXME: Using "DestType" for the entity we're printing is probably
6542 // bad.
6543 switch (FailedOverloadResult) {
6544 case OR_Ambiguous:
6545 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6546 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006547 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006548 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006549
Douglas Gregor51c56d62009-12-14 20:49:26 +00006550 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006551 if (Kind.getKind() == InitializationKind::IK_Default &&
6552 (Entity.getKind() == InitializedEntity::EK_Base ||
6553 Entity.getKind() == InitializedEntity::EK_Member) &&
6554 isa<CXXConstructorDecl>(S.CurContext)) {
6555 // This is implicit default initialization of a member or
6556 // base within a constructor. If no viable function was
6557 // found, notify the user that she needs to explicitly
6558 // initialize this base/member.
6559 CXXConstructorDecl *Constructor
6560 = cast<CXXConstructorDecl>(S.CurContext);
6561 if (Entity.getKind() == InitializedEntity::EK_Base) {
6562 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006563 << (Constructor->getInheritedConstructor() ? 2 :
6564 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006565 << S.Context.getTypeDeclType(Constructor->getParent())
6566 << /*base=*/0
6567 << Entity.getType();
6568
6569 RecordDecl *BaseDecl
6570 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6571 ->getDecl();
6572 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6573 << S.Context.getTagDeclType(BaseDecl);
6574 } else {
6575 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006576 << (Constructor->getInheritedConstructor() ? 2 :
6577 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006578 << S.Context.getTypeDeclType(Constructor->getParent())
6579 << /*member=*/1
6580 << Entity.getName();
6581 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6582
6583 if (const RecordType *Record
6584 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006585 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006586 diag::note_previous_decl)
6587 << S.Context.getTagDeclType(Record->getDecl());
6588 }
6589 break;
6590 }
6591
Douglas Gregor51c56d62009-12-14 20:49:26 +00006592 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6593 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006594 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006595 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006596
Douglas Gregor51c56d62009-12-14 20:49:26 +00006597 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006598 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006599 OverloadingResult Ovl
6600 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006601 if (Ovl != OR_Deleted) {
6602 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6603 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006604 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006605 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006606 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006607
6608 // If this is a defaulted or implicitly-declared function, then
6609 // it was implicitly deleted. Make it clear that the deletion was
6610 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006611 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006612 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006613 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006614 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006615 else
6616 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6617 << true << DestType << ArgsRange;
6618
6619 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006620 break;
6621 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006622
Douglas Gregor51c56d62009-12-14 20:49:26 +00006623 case OR_Success:
6624 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006625 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006626 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006627 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006628
Douglas Gregor99a2e602009-12-16 01:38:02 +00006629 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006630 if (Entity.getKind() == InitializedEntity::EK_Member &&
6631 isa<CXXConstructorDecl>(S.CurContext)) {
6632 // This is implicit default-initialization of a const member in
6633 // a constructor. Complain that it needs to be explicitly
6634 // initialized.
6635 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6636 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006637 << (Constructor->getInheritedConstructor() ? 2 :
6638 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006639 << S.Context.getTypeDeclType(Constructor->getParent())
6640 << /*const=*/1
6641 << Entity.getName();
6642 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6643 << Entity.getName();
6644 } else {
6645 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6646 << DestType << (bool)DestType->getAs<RecordType>();
6647 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006648 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006649
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006650 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006651 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006652 diag::err_init_incomplete_type);
6653 break;
6654
Sebastian Redl14b0c192011-09-24 17:48:00 +00006655 case FK_ListInitializationFailed: {
6656 // Run the init list checker again to emit diagnostics.
Bill Wendling2ca3db42013-11-22 00:01:44 +00006657 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6658 diagnoseListInit(S, Entity, InitList);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006659 break;
6660 }
John McCall5acb0c92011-10-17 18:40:02 +00006661
6662 case FK_PlaceholderType: {
6663 // FIXME: Already diagnosed!
6664 break;
6665 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006666
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006667 case FK_ExplicitConstructor: {
6668 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6669 << Args[0]->getSourceRange();
6670 OverloadCandidateSet::iterator Best;
6671 OverloadingResult Ovl
6672 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006673 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006674 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6675 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6676 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6677 break;
6678 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006679 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006680
Douglas Gregora41a8c52010-04-22 00:20:18 +00006681 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006682 return true;
6683}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006684
Chris Lattner5f9e2722011-07-23 10:55:15 +00006685void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006686 switch (SequenceKind) {
6687 case FailedSequence: {
6688 OS << "Failed sequence: ";
6689 switch (Failure) {
6690 case FK_TooManyInitsForReference:
6691 OS << "too many initializers for reference";
6692 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006693
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006694 case FK_ArrayNeedsInitList:
6695 OS << "array requires initializer list";
6696 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006697
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006698 case FK_ArrayNeedsInitListOrStringLiteral:
6699 OS << "array requires initializer list or string literal";
6700 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006701
Hans Wennborg0ff50742013-05-15 11:03:04 +00006702 case FK_ArrayNeedsInitListOrWideStringLiteral:
6703 OS << "array requires initializer list or wide string literal";
6704 break;
6705
6706 case FK_NarrowStringIntoWideCharArray:
6707 OS << "narrow string into wide char array";
6708 break;
6709
6710 case FK_WideStringIntoCharArray:
6711 OS << "wide string into char array";
6712 break;
6713
6714 case FK_IncompatWideStringIntoWideChar:
6715 OS << "incompatible wide string into wide char array";
6716 break;
6717
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006718 case FK_ArrayTypeMismatch:
6719 OS << "array type mismatch";
6720 break;
6721
6722 case FK_NonConstantArrayInit:
6723 OS << "non-constant array initializer";
6724 break;
6725
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006726 case FK_AddressOfOverloadFailed:
6727 OS << "address of overloaded function failed";
6728 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006729
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006730 case FK_ReferenceInitOverloadFailed:
6731 OS << "overload resolution for reference initialization failed";
6732 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006733
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006734 case FK_NonConstLValueReferenceBindingToTemporary:
6735 OS << "non-const lvalue reference bound to temporary";
6736 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006737
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006738 case FK_NonConstLValueReferenceBindingToUnrelated:
6739 OS << "non-const lvalue reference bound to unrelated type";
6740 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006741
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006742 case FK_RValueReferenceBindingToLValue:
6743 OS << "rvalue reference bound to an lvalue";
6744 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006745
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006746 case FK_ReferenceInitDropsQualifiers:
6747 OS << "reference initialization drops qualifiers";
6748 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006749
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006750 case FK_ReferenceInitFailed:
6751 OS << "reference initialization failed";
6752 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006753
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006754 case FK_ConversionFailed:
6755 OS << "conversion failed";
6756 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006757
John Wiegley429bb272011-04-08 18:41:53 +00006758 case FK_ConversionFromPropertyFailed:
6759 OS << "conversion from property failed";
6760 break;
6761
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006762 case FK_TooManyInitsForScalar:
6763 OS << "too many initializers for scalar";
6764 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006765
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006766 case FK_ReferenceBindingToInitList:
6767 OS << "referencing binding to initializer list";
6768 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006769
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006770 case FK_InitListBadDestinationType:
6771 OS << "initializer list for non-aggregate, non-scalar type";
6772 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006773
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006774 case FK_UserConversionOverloadFailed:
6775 OS << "overloading failed for user-defined conversion";
6776 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006777
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006778 case FK_ConstructorOverloadFailed:
6779 OS << "constructor overloading failed";
6780 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006781
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006782 case FK_DefaultInitOfConst:
6783 OS << "default initialization of a const variable";
6784 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006785
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006786 case FK_Incomplete:
6787 OS << "initialization of incomplete type";
6788 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006789
6790 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006791 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006792 break;
6793
John McCall73076432012-01-05 00:13:19 +00006794 case FK_VariableLengthArrayHasInitializer:
6795 OS << "variable length array has an initializer";
6796 break;
6797
John McCall5acb0c92011-10-17 18:40:02 +00006798 case FK_PlaceholderType:
6799 OS << "initializer expression isn't contextually valid";
6800 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006801
6802 case FK_ListConstructorOverloadFailed:
6803 OS << "list constructor overloading failed";
6804 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006805
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006806 case FK_ExplicitConstructor:
6807 OS << "list copy initialization chose explicit constructor";
6808 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006809 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006810 OS << '\n';
6811 return;
6812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006813
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006814 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006815 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006816 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006817
Sebastian Redl7491c492011-06-05 13:59:11 +00006818 case NormalSequence:
6819 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006820 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006822
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006823 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6824 if (S != step_begin()) {
6825 OS << " -> ";
6826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006827
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006828 switch (S->Kind) {
6829 case SK_ResolveAddressOfOverloadedFunction:
6830 OS << "resolve address of overloaded function";
6831 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006832
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006833 case SK_CastDerivedToBaseRValue:
6834 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6835 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006836
Sebastian Redl906082e2010-07-20 04:20:21 +00006837 case SK_CastDerivedToBaseXValue:
6838 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6839 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006840
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006841 case SK_CastDerivedToBaseLValue:
6842 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6843 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006844
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006845 case SK_BindReference:
6846 OS << "bind reference to lvalue";
6847 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006848
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006849 case SK_BindReferenceToTemporary:
6850 OS << "bind reference to a temporary";
6851 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006852
Douglas Gregor523d46a2010-04-18 07:40:54 +00006853 case SK_ExtraneousCopyToTemporary:
6854 OS << "extraneous C++03 copy to temporary";
6855 break;
6856
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006857 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006858 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006859 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006860
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006861 case SK_QualificationConversionRValue:
6862 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006863 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006864
Sebastian Redl906082e2010-07-20 04:20:21 +00006865 case SK_QualificationConversionXValue:
6866 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006867 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006868
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006869 case SK_QualificationConversionLValue:
6870 OS << "qualification conversion (lvalue)";
6871 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006872
Jordan Rose1fd1e282013-04-11 00:58:58 +00006873 case SK_LValueToRValue:
6874 OS << "load (lvalue to rvalue)";
6875 break;
6876
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006877 case SK_ConversionSequence:
6878 OS << "implicit conversion sequence (";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +00006879 S->ICS->dump(); // FIXME: use OS
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006880 OS << ")";
6881 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006882
Richard Smith13b228d2013-09-21 21:19:19 +00006883 case SK_ConversionSequenceNoNarrowing:
6884 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +00006885 S->ICS->dump(); // FIXME: use OS
Richard Smith13b228d2013-09-21 21:19:19 +00006886 OS << ")";
6887 break;
6888
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006889 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006890 OS << "list aggregate initialization";
6891 break;
6892
6893 case SK_ListConstructorCall:
6894 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006895 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006896
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006897 case SK_UnwrapInitList:
6898 OS << "unwrap reference initializer list";
6899 break;
6900
6901 case SK_RewrapInitList:
6902 OS << "rewrap reference initializer list";
6903 break;
6904
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006905 case SK_ConstructorInitialization:
6906 OS << "constructor initialization";
6907 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006908
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006909 case SK_ZeroInitialization:
6910 OS << "zero initialization";
6911 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006912
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006913 case SK_CAssignment:
6914 OS << "C assignment";
6915 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006916
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006917 case SK_StringInit:
6918 OS << "string initialization";
6919 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006920
6921 case SK_ObjCObjectConversion:
6922 OS << "Objective-C object conversion";
6923 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006924
6925 case SK_ArrayInit:
6926 OS << "array initialization";
6927 break;
John McCallf85e1932011-06-15 23:02:42 +00006928
Richard Smith0f163e92012-02-15 22:38:09 +00006929 case SK_ParenthesizedArrayInit:
6930 OS << "parenthesized array initialization";
6931 break;
6932
John McCallf85e1932011-06-15 23:02:42 +00006933 case SK_PassByIndirectCopyRestore:
6934 OS << "pass by indirect copy and restore";
6935 break;
6936
6937 case SK_PassByIndirectRestore:
6938 OS << "pass by indirect restore";
6939 break;
6940
6941 case SK_ProduceObjCObject:
6942 OS << "Objective-C object retension";
6943 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006944
6945 case SK_StdInitializerList:
6946 OS << "std::initializer_list from initializer list";
6947 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006948
Guy Benyei21f18c42013-02-07 10:55:47 +00006949 case SK_OCLSamplerInit:
6950 OS << "OpenCL sampler_t from integer constant";
6951 break;
6952
Guy Benyeie6b9d802013-01-20 12:31:11 +00006953 case SK_OCLZeroEvent:
6954 OS << "OpenCL event_t from zero";
6955 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006956 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006957
6958 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006959 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006960
6961 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006962}
6963
6964void InitializationSequence::dump() const {
6965 dump(llvm::errs());
6966}
6967
Richard Smith13b228d2013-09-21 21:19:19 +00006968static void DiagnoseNarrowingInInitList(Sema &S,
6969 const ImplicitConversionSequence &ICS,
6970 QualType PreNarrowingType,
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006971 QualType EntityType,
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006972 const Expr *PostInit) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006973 const StandardConversionSequence *SCS = 0;
6974 switch (ICS.getKind()) {
6975 case ImplicitConversionSequence::StandardConversion:
6976 SCS = &ICS.Standard;
6977 break;
6978 case ImplicitConversionSequence::UserDefinedConversion:
6979 SCS = &ICS.UserDefined.After;
6980 break;
6981 case ImplicitConversionSequence::AmbiguousConversion:
6982 case ImplicitConversionSequence::EllipsisConversion:
6983 case ImplicitConversionSequence::BadConversion:
6984 return;
6985 }
6986
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006987 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6988 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006989 QualType ConstantType;
6990 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6991 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006992 case NK_Not_Narrowing:
6993 // No narrowing occurred.
6994 return;
6995
6996 case NK_Type_Narrowing:
6997 // This was a floating-to-integer conversion, which is always considered a
6998 // narrowing conversion even if the value is a constant and can be
6999 // represented exactly as an integer.
7000 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007001 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7002 ? diag::warn_init_list_type_narrowing
7003 : diag::ext_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007004 << PostInit->getSourceRange()
7005 << PreNarrowingType.getLocalUnqualifiedType()
7006 << EntityType.getLocalUnqualifiedType();
7007 break;
7008
7009 case NK_Constant_Narrowing:
7010 // A constant value was narrowed.
7011 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007012 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7013 ? diag::warn_init_list_constant_narrowing
7014 : diag::ext_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007015 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00007016 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00007017 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007018 break;
7019
7020 case NK_Variable_Narrowing:
7021 // A variable's value may have been narrowed.
7022 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007023 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7024 ? diag::warn_init_list_variable_narrowing
7025 : diag::ext_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007026 << PostInit->getSourceRange()
7027 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00007028 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007029 break;
7030 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007031
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007032 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007033 llvm::raw_svector_ostream OS(StaticCast);
7034 OS << "static_cast<";
7035 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7036 // It's important to use the typedef's name if there is one so that the
7037 // fixit doesn't break code using types like int64_t.
7038 //
7039 // FIXME: This will break if the typedef requires qualification. But
7040 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00007041 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007042 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00007043 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007044 else {
7045 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7046 // with a broken cast.
7047 return;
7048 }
7049 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007050 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
7051 << PostInit->getSourceRange()
7052 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007053 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007054 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007055}
7056
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007057//===----------------------------------------------------------------------===//
7058// Initialization helper functions
7059//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00007060bool
7061Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7062 ExprResult Init) {
7063 if (Init.isInvalid())
7064 return false;
7065
7066 Expr *InitE = Init.get();
7067 assert(InitE && "No initialization expression");
7068
Douglas Gregor3c394c52012-07-31 22:15:04 +00007069 InitializationKind Kind
7070 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007071 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00007072 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00007073}
7074
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007075ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007076Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7077 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007078 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00007079 bool TopLevelOfInitList,
7080 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007081 if (Init.isInvalid())
7082 return ExprError();
7083
John McCall15d7d122010-11-11 03:21:53 +00007084 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007085 assert(InitE && "No initialization expression?");
7086
7087 if (EqualLoc.isInvalid())
7088 EqualLoc = InitE->getLocStart();
7089
7090 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00007091 EqualLoc,
7092 AllowExplicit);
Richard Smith13b228d2013-09-21 21:19:19 +00007093 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007094 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007095
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007096 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007097
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007098 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007099}