blob: a33724a29701ff99c21d61c638882dc7174f4ad0 [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"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070020#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#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);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070073 if (!SL)
Hans Wennborg0ff50742013-05-15 11:03:04 +000074 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
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700316 static ExprResult PerformEmptyInit(Sema &SemaRef,
317 SourceLocation Loc,
318 const InitializedEntity &Entity,
319 bool VerifyOnly);
320 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000321 const InitializedEntity &ParentEntity,
322 InitListExpr *ILE, bool &RequiresSecondPass);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700323 void FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000324 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000325 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
326 Expr *InitExpr, FieldDecl *Field,
327 bool TopLevelObject);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700328 void CheckEmptyInitializable(const InitializedEntity &Entity,
329 SourceLocation Loc);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000330
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000331public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000332 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smith40cba902013-06-06 11:41:05 +0000333 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000334 bool HadError() { return hadError; }
335
336 // @brief Retrieves the fully-structured initializer list used for
337 // semantic analysis and code generation.
338 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
339};
Chris Lattner8b419b92009-02-24 22:48:58 +0000340} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000341
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700342ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
343 SourceLocation Loc,
344 const InitializedEntity &Entity,
345 bool VerifyOnly) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000346 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
347 true);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700348 MultiExprArg SubInit;
349 Expr *InitExpr;
350 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
351
352 // C++ [dcl.init.aggr]p7:
353 // If there are fewer initializer-clauses in the list than there are
354 // members in the aggregate, then each member not explicitly initialized
355 // ...
356 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
357 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
358 if (EmptyInitList) {
359 // C++1y / DR1070:
360 // shall be initialized [...] from an empty initializer list.
361 //
362 // We apply the resolution of this DR to C++11 but not C++98, since C++98
363 // does not have useful semantics for initialization from an init list.
364 // We treat this as copy-initialization, because aggregate initialization
365 // always performs copy-initialization on its elements.
366 //
367 // Only do this if we're initializing a class type, to avoid filling in
368 // the initializer list where possible.
369 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
370 InitListExpr(SemaRef.Context, Loc, None, Loc);
371 InitExpr->setType(SemaRef.Context.VoidTy);
372 SubInit = InitExpr;
373 Kind = InitializationKind::CreateCopy(Loc, Loc);
374 } else {
375 // C++03:
376 // shall be value-initialized.
377 }
378
379 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
380 // libstdc++4.6 marks the vector default constructor as explicit in
381 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
382 // stlport does so too. Look for std::__debug for libstdc++, and for
383 // std:: for stlport. This is effectively a compiler-side implementation of
384 // LWG2193.
385 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
386 InitializationSequence::FK_ExplicitConstructor) {
387 OverloadCandidateSet::iterator Best;
388 OverloadingResult O =
389 InitSeq.getFailedCandidateSet()
390 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
391 (void)O;
392 assert(O == OR_Success && "Inconsistent overload resolution");
393 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
394 CXXRecordDecl *R = CtorDecl->getParent();
395
396 if (CtorDecl->getMinRequiredArguments() == 0 &&
397 CtorDecl->isExplicit() && R->getDeclName() &&
398 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
399
400
401 bool IsInStd = false;
402 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
403 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
404 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
405 IsInStd = true;
406 }
407
408 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
409 .Cases("basic_string", "deque", "forward_list", true)
410 .Cases("list", "map", "multimap", "multiset", true)
411 .Cases("priority_queue", "queue", "set", "stack", true)
412 .Cases("unordered_map", "unordered_set", "vector", true)
413 .Default(false)) {
414 InitSeq.InitializeFrom(
415 SemaRef, Entity,
416 InitializationKind::CreateValue(Loc, Loc, Loc, true),
417 MultiExprArg(), /*TopLevelOfInitList=*/false);
418 // Emit a warning for this. System header warnings aren't shown
419 // by default, but people working on system headers should see it.
420 if (!VerifyOnly) {
421 SemaRef.Diag(CtorDecl->getLocation(),
422 diag::warn_invalid_initializer_from_system_header);
423 SemaRef.Diag(Entity.getDecl()->getLocation(),
424 diag::note_used_in_initialization_here);
425 }
426 }
427 }
428 }
429 if (!InitSeq) {
430 if (!VerifyOnly) {
431 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
432 if (Entity.getKind() == InitializedEntity::EK_Member)
433 SemaRef.Diag(Entity.getDecl()->getLocation(),
434 diag::note_in_omitted_aggregate_initializer)
435 << /*field*/1 << Entity.getDecl();
436 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
437 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
438 << /*array element*/0 << Entity.getElementIndex();
439 }
440 return ExprError();
441 }
442
443 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
444 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
445}
446
447void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
448 SourceLocation Loc) {
449 assert(VerifyOnly &&
450 "CheckEmptyInitializable is only inteded for verification mode.");
451 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000452 hadError = true;
453}
454
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700455void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000456 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000457 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000458 bool &RequiresSecondPass) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700459 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000460 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000461 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000462 = InitializedEntity::InitializeMember(Field, &ParentEntity);
463 if (Init >= NumInits || !ILE->getInit(Init)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700464 // C++1y [dcl.init.aggr]p7:
465 // If there are fewer initializer-clauses in the list than there are
466 // members in the aggregate, then each member not explicitly initialized
467 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smithc3bf52c2013-04-20 22:23:05 +0000468 if (Field->hasInClassInitializer()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700469 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, Loc, Field);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000470 if (Init < NumInits)
471 ILE->setInit(Init, DIE);
472 else {
473 ILE->updateInit(SemaRef.Context, Init, DIE);
474 RequiresSecondPass = true;
475 }
476 return;
477 }
478
Douglas Gregord6d37de2009-12-22 00:05:34 +0000479 if (Field->getType()->isReferenceType()) {
480 // C++ [dcl.init.aggr]p9:
481 // If an incomplete or empty initializer-list leaves a
482 // member of reference type uninitialized, the program is
483 // ill-formed.
484 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
485 << Field->getType()
486 << ILE->getSyntacticForm()->getSourceRange();
487 SemaRef.Diag(Field->getLocation(),
488 diag::note_uninit_reference_member);
489 hadError = true;
490 return;
491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000492
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700493 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
494 /*VerifyOnly*/false);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000495 if (MemberInit.isInvalid()) {
496 hadError = true;
497 return;
498 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000499
Douglas Gregord6d37de2009-12-22 00:05:34 +0000500 if (hadError) {
501 // Do nothing
502 } else if (Init < NumInits) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700503 ILE->setInit(Init, MemberInit.getAs<Expr>());
504 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
505 // Empty initialization requires a constructor call, so
Douglas Gregord6d37de2009-12-22 00:05:34 +0000506 // extend the initializer list to include the constructor
507 // call and make a note that we'll need to take another pass
508 // through the initializer list.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700509 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000510 RequiresSecondPass = true;
511 }
512 } else if (InitListExpr *InnerILE
513 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700514 FillInEmptyInitializations(MemberEntity, InnerILE,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000515 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000516}
517
Douglas Gregor4c678342009-01-28 21:54:33 +0000518/// Recursively replaces NULL values within the given initializer list
519/// with expressions that perform value-initialization of the
520/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000521void
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700522InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000523 InitListExpr *ILE,
524 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000525 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000526 "Should not have void type");
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Ted Kremenek6217b802009-07-29 21:53:49 +0000528 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000529 const RecordDecl *RDecl = RType->getDecl();
530 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700531 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Douglas Gregord6d37de2009-12-22 00:05:34 +0000532 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000533 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
534 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700535 for (auto *Field : RDecl->fields()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000536 if (Field->hasInClassInitializer()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700537 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000538 break;
539 }
540 }
541 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000542 unsigned Init = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700543 for (auto *Field : RDecl->fields()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000544 if (Field->isUnnamedBitfield())
545 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000546
Douglas Gregord6d37de2009-12-22 00:05:34 +0000547 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000548 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000549
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700550 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000551 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000552 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000553
Douglas Gregord6d37de2009-12-22 00:05:34 +0000554 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000555
Douglas Gregord6d37de2009-12-22 00:05:34 +0000556 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000557 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000558 break;
559 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000560 }
561
562 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000563 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000564
565 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000567 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000568 unsigned NumInits = ILE->getNumInits();
569 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000570 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000571 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000572 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
573 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000575 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000576 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000577 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000578 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000580 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000581 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000582 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Douglas Gregor87fd7032009-02-02 17:43:21 +0000584 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000585 if (hadError)
586 return;
587
Anders Carlssond3d824d2010-01-23 04:34:47 +0000588 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
589 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000590 ElementEntity.setElementIndex(Init);
591
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700592 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000593 if (!InitExpr && !ILE->hasArrayFiller()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700594 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
595 ElementEntity,
596 /*VerifyOnly*/false);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000597 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000598 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000599 return;
600 }
601
602 if (hadError) {
603 // Do nothing
604 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000605 // For arrays, just set the expression used for value-initialization
606 // of the "holes" in the array.
607 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700608 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000609 else
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700610 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000611 } else {
612 // For arrays, just set the expression used for value-initialization
613 // of the rest of elements and exit.
614 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700615 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000616 return;
617 }
618
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700619 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
620 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000621 // extend the initializer list to include the constructor
622 // call and make a note that we'll need to take another pass
623 // through the initializer list.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700624 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000625 RequiresSecondPass = true;
626 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000627 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000628 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000629 = dyn_cast_or_null<InitListExpr>(InitExpr))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700630 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000631 }
632}
633
Chris Lattner68355a52009-01-29 05:10:57 +0000634
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000635InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000636 InitListExpr *IL, QualType &T,
Richard Smith40cba902013-06-06 11:41:05 +0000637 bool VerifyOnly)
638 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000639 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000640
Richard Smithb9bf3122013-09-20 20:10:22 +0000641 FullyStructuredList =
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700642 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smithb9bf3122013-09-20 20:10:22 +0000643 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000644 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000645
Sebastian Redl14b0c192011-09-24 17:48:00 +0000646 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000647 bool RequiresSecondPass = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700648 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000649 if (RequiresSecondPass && !hadError)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700650 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000651 RequiresSecondPass);
652 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000653}
654
655int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000656 // FIXME: use a proper constant
657 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000658 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000659 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000660 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
661 }
662 return maxElements;
663}
664
665int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000666 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000667 int InitializableMembers = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700668 for (const auto *Field : structDecl->fields())
Douglas Gregord61db332011-10-10 17:22:13 +0000669 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000670 ++InitializableMembers;
Stephen Hines651f13c2014-04-23 16:59:28 -0700671
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000672 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000673 return std::min(InitializableMembers, 1);
674 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000675}
676
Richard Smithb9bf3122013-09-20 20:10:22 +0000677/// Check whether the range of the initializer \p ParentIList from element
678/// \p Index onwards can be used to initialize an object of type \p T. Update
679/// \p Index to indicate how many elements of the list were consumed.
680///
681/// This also fills in \p StructuredList, from element \p StructuredIndex
682/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000683void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000684 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000685 QualType T, unsigned &Index,
686 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000687 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000688 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Steve Naroff0cca7492008-05-01 22:18:59 +0000690 if (T->isArrayType())
691 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000692 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000693 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000694 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000695 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000696 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000697 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000698
Eli Friedman402256f2008-05-25 13:49:22 +0000699 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000700 if (!VerifyOnly)
701 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
702 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000703 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000704 hadError = true;
705 return;
706 }
707
Douglas Gregor4c678342009-01-28 21:54:33 +0000708 // Build a structured initializer list corresponding to this subobject.
709 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000710 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
711 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000712 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000713 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000714 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000715
Douglas Gregor4c678342009-01-28 21:54:33 +0000716 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000717 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000718 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000719 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000720 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000721 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000722
Richard Smith40cba902013-06-06 11:41:05 +0000723 if (!VerifyOnly) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000724 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000725
Sebastian Redlc2235182011-10-16 18:19:28 +0000726 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000727 // Update the structured sub-object initializer so that it's ending
728 // range corresponds with the end of the last initializer it used.
729 if (EndIndex < ParentIList->getNumInits()) {
730 SourceLocation EndLoc
731 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
732 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
733 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000734
Sebastian Redlc2235182011-10-16 18:19:28 +0000735 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000736 if (T->isArrayType() || T->isRecordType()) {
737 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smith40cba902013-06-06 11:41:05 +0000738 diag::warn_missing_braces)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700739 << StructuredSubobjectInitList->getSourceRange()
740 << FixItHint::CreateInsertion(
741 StructuredSubobjectInitList->getLocStart(), "{")
742 << FixItHint::CreateInsertion(
743 SemaRef.getLocForEndOfToken(
744 StructuredSubobjectInitList->getLocEnd()),
745 "}");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000746 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000747 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000748}
749
Richard Smithb9bf3122013-09-20 20:10:22 +0000750/// Check whether the initializer \p IList (that was written with explicit
751/// braces) can be used to initialize an object of type \p T.
752///
753/// This also fills in \p StructuredList with the fully-braced, desugared
754/// form of the initialization.
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000755void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000756 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000757 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000758 bool TopLevelObject) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000759 if (!VerifyOnly) {
760 SyntacticToSemantic[IList] = StructuredList;
761 StructuredList->setSyntacticForm(IList);
762 }
Richard Smithb9bf3122013-09-20 20:10:22 +0000763
764 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000765 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000766 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000767 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000768 QualType ExprTy = T;
769 if (!ExprTy->isArrayType())
770 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000771 IList->setType(ExprTy);
772 StructuredList->setType(ExprTy);
773 }
Eli Friedman638e1442008-05-25 13:22:35 +0000774 if (hadError)
775 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000776
Eli Friedman638e1442008-05-25 13:22:35 +0000777 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000778 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000779 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000780 if (SemaRef.getLangOpts().CPlusPlus ||
781 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000782 IList->getType()->isVectorType())) {
783 hadError = true;
784 }
785 return;
786 }
787
Eli Friedmane5408582009-05-29 20:20:05 +0000788 if (StructuredIndex == 1 &&
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000789 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
790 SIF_None) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000791 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000792 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000793 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000794 hadError = true;
795 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000796 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000797 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000798 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000799 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000800 // Don't complain for incomplete types, since we'll get an error
801 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000802 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000803 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000804 CurrentObjectType->isArrayType()? 0 :
805 CurrentObjectType->isVectorType()? 1 :
806 CurrentObjectType->isScalarType()? 2 :
807 CurrentObjectType->isUnionType()? 3 :
808 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000809
810 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000811 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000812 DK = diag::err_excess_initializers;
813 hadError = true;
814 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000815 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000816 DK = diag::err_excess_initializers;
817 hadError = true;
818 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000819
Chris Lattner08202542009-02-24 22:50:46 +0000820 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000821 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000822 }
823 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000824
Sebastian Redl14b0c192011-09-24 17:48:00 +0000825 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
826 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000827 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000828 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000829 << FixItHint::CreateRemoval(IList->getLocStart())
830 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000831}
832
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000833void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000834 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000835 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000836 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000837 unsigned &Index,
838 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000839 unsigned &StructuredIndex,
840 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000841 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
842 // Explicitly braced initializer for complex type can be real+imaginary
843 // parts.
844 CheckComplexType(Entity, IList, DeclType, Index,
845 StructuredList, StructuredIndex);
846 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000847 CheckScalarType(Entity, IList, DeclType, Index,
848 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000849 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000850 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000851 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000852 } else if (DeclType->isRecordType()) {
853 assert(DeclType->isAggregateType() &&
854 "non-aggregate records should be handed in CheckSubElementType");
855 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
856 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
857 SubobjectIsDesignatorContext, Index,
858 StructuredList, StructuredIndex,
859 TopLevelObject);
860 } else if (DeclType->isArrayType()) {
861 llvm::APSInt Zero(
862 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
863 false);
864 CheckArrayType(Entity, IList, DeclType, Zero,
865 SubobjectIsDesignatorContext, Index,
866 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000867 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
868 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000869 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000870 if (!VerifyOnly)
871 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
872 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000873 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000874 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000875 CheckReferenceType(Entity, IList, DeclType, Index,
876 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000877 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000878 if (!VerifyOnly)
879 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
880 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000881 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000882 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000883 if (!VerifyOnly)
884 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
885 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000886 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000887 }
888}
889
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000890void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000891 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000892 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000893 unsigned &Index,
894 InitListExpr *StructuredList,
895 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000896 Expr *expr = IList->getInit(Index);
Richard Smith6242a452013-05-31 02:56:17 +0000897
898 if (ElemType->isReferenceType())
899 return CheckReferenceType(Entity, IList, ElemType, Index,
900 StructuredList, StructuredIndex);
901
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000902 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000903 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smithb9bf3122013-09-20 20:10:22 +0000904 InitListExpr *InnerStructuredList
Richard Smith20599392012-07-07 08:35:56 +0000905 = getStructuredSubobjectInit(IList, Index, ElemType,
906 StructuredList, StructuredIndex,
907 SubInitList->getSourceRange());
Richard Smithb9bf3122013-09-20 20:10:22 +0000908 CheckExplicitInitList(Entity, SubInitList, ElemType,
909 InnerStructuredList);
Richard Smith20599392012-07-07 08:35:56 +0000910 ++StructuredIndex;
911 ++Index;
912 return;
913 }
914 assert(SemaRef.getLangOpts().CPlusPlus &&
915 "non-aggregate records are only possible in C++");
916 // C++ initialization is handled later.
917 }
918
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000919 // FIXME: Need to handle atomic aggregate types with implicit init lists.
920 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCallfef8b342011-02-21 07:57:55 +0000921 return CheckScalarType(Entity, IList, ElemType, Index,
922 StructuredList, StructuredIndex);
Anders Carlssond28b4282009-08-27 17:18:13 +0000923
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000924 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
925 ElemType->isArrayType()) && "Unexpected type");
926
John McCallfef8b342011-02-21 07:57:55 +0000927 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
928 // arrayType can be incomplete if we're initializing a flexible
929 // array member. There's nothing we can do with the completed
930 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000931
Hans Wennborg0ff50742013-05-15 11:03:04 +0000932 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000933 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000934 CheckStringInit(expr, ElemType, arrayType, SemaRef);
935 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000936 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000937 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000938 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000939 }
John McCallfef8b342011-02-21 07:57:55 +0000940
941 // Fall through for subaggregate initialization.
942
David Blaikie4e4d0842012-03-11 07:00:24 +0000943 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000944 // C++ [dcl.init.aggr]p12:
945 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000946 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000947 // an initializer-list. If the initializer can initialize a
948 // member, the member is initialized. [...]
949
950 // FIXME: Better EqualLoc?
951 InitializationKind Kind =
952 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000953 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000954
955 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000956 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000957 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000958 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000959 if (Result.isInvalid())
960 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000961
Sebastian Redl14b0c192011-09-24 17:48:00 +0000962 UpdateStructuredListElement(StructuredList, StructuredIndex,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700963 Result.getAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000964 }
John McCallfef8b342011-02-21 07:57:55 +0000965 ++Index;
966 return;
967 }
968
969 // Fall through for subaggregate initialization
970 } else {
971 // C99 6.7.8p13:
972 //
973 // The initializer for a structure or union object that has
974 // automatic storage duration shall be either an initializer
975 // list as described below, or a single expression that has
976 // compatible structure or union type. In the latter case, the
977 // initial value of the object, including unnamed members, is
978 // that of the expression.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700979 ExprResult ExprRes = expr;
John McCallfef8b342011-02-21 07:57:55 +0000980 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000981 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
982 !VerifyOnly)
Eli Friedman08f0bbc2013-09-17 04:07:04 +0000983 != Sema::Incompatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000984 if (ExprRes.isInvalid())
985 hadError = true;
986 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700987 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000988 if (ExprRes.isInvalid())
989 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000990 }
991 UpdateStructuredListElement(StructuredList, StructuredIndex,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700992 ExprRes.getAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000993 ++Index;
994 return;
995 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700996 ExprRes.get();
John McCallfef8b342011-02-21 07:57:55 +0000997 // Fall through for subaggregate initialization
998 }
999
1000 // C++ [dcl.init.aggr]p12:
1001 //
1002 // [...] Otherwise, if the member is itself a non-empty
1003 // subaggregate, brace elision is assumed and the initializer is
1004 // considered for the initialization of the first member of
1005 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +00001006 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00001007 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +00001008 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1009 StructuredIndex);
1010 ++StructuredIndex;
1011 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001012 if (!VerifyOnly) {
1013 // We cannot initialize this element, so let
1014 // PerformCopyInitialization produce the appropriate diagnostic.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001015 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001016 /*TopLevelOfInitList=*/true);
1017 }
John McCallfef8b342011-02-21 07:57:55 +00001018 hadError = true;
1019 ++Index;
1020 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001021 }
Eli Friedmanb85f7072008-05-19 19:16:24 +00001022}
1023
Eli Friedman0c706c22011-09-19 23:17:44 +00001024void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1025 InitListExpr *IList, QualType DeclType,
1026 unsigned &Index,
1027 InitListExpr *StructuredList,
1028 unsigned &StructuredIndex) {
1029 assert(Index == 0 && "Index in explicit init list must be zero");
1030
1031 // As an extension, clang supports complex initializers, which initialize
1032 // a complex number component-wise. When an explicit initializer list for
1033 // a complex number contains two two initializers, this extension kicks in:
1034 // it exepcts the initializer list to contain two elements convertible to
1035 // the element type of the complex type. The first element initializes
1036 // the real part, and the second element intitializes the imaginary part.
1037
1038 if (IList->getNumInits() != 2)
1039 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1040 StructuredIndex);
1041
1042 // This is an extension in C. (The builtin _Complex type does not exist
1043 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +00001044 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +00001045 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1046 << IList->getSourceRange();
1047
1048 // Initialize the complex number.
1049 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1050 InitializedEntity ElementEntity =
1051 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1052
1053 for (unsigned i = 0; i < 2; ++i) {
1054 ElementEntity.setElementIndex(Index);
1055 CheckSubElementType(ElementEntity, IList, elementType, Index,
1056 StructuredList, StructuredIndex);
1057 }
1058}
1059
1060
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001061void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001062 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001063 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001064 InitListExpr *StructuredList,
1065 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +00001066 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +00001067 if (!VerifyOnly)
1068 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001069 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +00001070 diag::warn_cxx98_compat_empty_scalar_initializer :
1071 diag::err_empty_scalar_initializer)
1072 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +00001073 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +00001074 ++Index;
1075 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +00001076 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001077 }
John McCallb934c2d2010-11-11 00:46:36 +00001078
1079 Expr *expr = IList->getInit(Index);
1080 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001081 // FIXME: This is invalid, and accepting it causes overload resolution
1082 // to pick the wrong overload in some corner cases.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001083 if (!VerifyOnly)
1084 SemaRef.Diag(SubIList->getLocStart(),
Stephen Hines651f13c2014-04-23 16:59:28 -07001085 diag::ext_many_braces_around_scalar_init)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001086 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001087
1088 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1089 StructuredIndex);
1090 return;
1091 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001092 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001093 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001094 diag::err_designator_for_scalar_init)
1095 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001096 hadError = true;
1097 ++Index;
1098 ++StructuredIndex;
1099 return;
1100 }
1101
Sebastian Redl14b0c192011-09-24 17:48:00 +00001102 if (VerifyOnly) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001103 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redl14b0c192011-09-24 17:48:00 +00001104 hadError = true;
1105 ++Index;
1106 return;
1107 }
1108
John McCallb934c2d2010-11-11 00:46:36 +00001109 ExprResult Result =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001110 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001111 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001112
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001113 Expr *ResultExpr = nullptr;
John McCallb934c2d2010-11-11 00:46:36 +00001114
1115 if (Result.isInvalid())
1116 hadError = true; // types weren't compatible.
1117 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001118 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001119
John McCallb934c2d2010-11-11 00:46:36 +00001120 if (ResultExpr != expr) {
1121 // The type was promoted, update initializer list.
1122 IList->setInit(Index, ResultExpr);
1123 }
1124 }
1125 if (hadError)
1126 ++StructuredIndex;
1127 else
1128 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1129 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001130}
1131
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001132void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1133 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001134 unsigned &Index,
1135 InitListExpr *StructuredList,
1136 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001137 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001138 // FIXME: It would be wonderful if we could point at the actual member. In
1139 // general, it would be useful to pass location information down the stack,
1140 // so that we know the location (or decl) of the "current object" being
1141 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001142 if (!VerifyOnly)
1143 SemaRef.Diag(IList->getLocStart(),
1144 diag::err_init_reference_member_uninitialized)
1145 << DeclType
1146 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001147 hadError = true;
1148 ++Index;
1149 ++StructuredIndex;
1150 return;
1151 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001152
1153 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001154 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001155 if (!VerifyOnly)
1156 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1157 << DeclType << IList->getSourceRange();
1158 hadError = true;
1159 ++Index;
1160 ++StructuredIndex;
1161 return;
1162 }
1163
1164 if (VerifyOnly) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001165 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redl14b0c192011-09-24 17:48:00 +00001166 hadError = true;
1167 ++Index;
1168 return;
1169 }
1170
1171 ExprResult Result =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001172 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1173 /*TopLevelOfInitList=*/true);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001174
1175 if (Result.isInvalid())
1176 hadError = true;
1177
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001178 expr = Result.getAs<Expr>();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001179 IList->setInit(Index, expr);
1180
1181 if (hadError)
1182 ++StructuredIndex;
1183 else
1184 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1185 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001186}
1187
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001188void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001189 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001190 unsigned &Index,
1191 InitListExpr *StructuredList,
1192 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001193 const VectorType *VT = DeclType->getAs<VectorType>();
1194 unsigned maxElements = VT->getNumElements();
1195 unsigned numEltsInit = 0;
1196 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001197
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001198 if (Index >= IList->getNumInits()) {
1199 // Make sure the element type can be value-initialized.
1200 if (VerifyOnly)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001201 CheckEmptyInitializable(
1202 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1203 IList->getLocEnd());
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001204 return;
1205 }
1206
David Blaikie4e4d0842012-03-11 07:00:24 +00001207 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001208 // If the initializing element is a vector, try to copy-initialize
1209 // instead of breaking it apart (which is doomed to failure anyway).
1210 Expr *Init = IList->getInit(Index);
1211 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001212 if (VerifyOnly) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001213 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redl14b0c192011-09-24 17:48:00 +00001214 hadError = true;
1215 ++Index;
1216 return;
1217 }
1218
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001219 ExprResult Result =
1220 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1221 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001222
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001223 Expr *ResultExpr = nullptr;
John McCall20e047a2010-10-30 00:11:39 +00001224 if (Result.isInvalid())
1225 hadError = true; // types weren't compatible.
1226 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001227 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001228
John McCall20e047a2010-10-30 00:11:39 +00001229 if (ResultExpr != Init) {
1230 // The type was promoted, update initializer list.
1231 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001232 }
1233 }
John McCall20e047a2010-10-30 00:11:39 +00001234 if (hadError)
1235 ++StructuredIndex;
1236 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001237 UpdateStructuredListElement(StructuredList, StructuredIndex,
1238 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001239 ++Index;
1240 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001241 }
Mike Stump1eb44332009-09-09 15:08:12 +00001242
John McCall20e047a2010-10-30 00:11:39 +00001243 InitializedEntity ElementEntity =
1244 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001245
John McCall20e047a2010-10-30 00:11:39 +00001246 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1247 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001248 if (Index >= IList->getNumInits()) {
1249 if (VerifyOnly)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001250 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall20e047a2010-10-30 00:11:39 +00001251 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001252 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001253
John McCall20e047a2010-10-30 00:11:39 +00001254 ElementEntity.setElementIndex(Index);
1255 CheckSubElementType(ElementEntity, IList, elementType, Index,
1256 StructuredList, StructuredIndex);
1257 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001258
1259 if (VerifyOnly)
1260 return;
1261
1262 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1263 const VectorType *T = Entity.getType()->getAs<VectorType>();
1264 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1265 T->getVectorKind() == VectorType::NeonPolyVector)) {
1266 // The ability to use vector initializer lists is a GNU vector extension
1267 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1268 // endian machines it works fine, however on big endian machines it
1269 // exhibits surprising behaviour:
1270 //
1271 // uint32x2_t x = {42, 64};
1272 // return vget_lane_u32(x, 0); // Will return 64.
1273 //
1274 // Because of this, explicitly call out that it is non-portable.
1275 //
1276 SemaRef.Diag(IList->getLocStart(),
1277 diag::warn_neon_vector_initializer_non_portable);
1278
1279 const char *typeCode;
1280 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1281
1282 if (elementType->isFloatingType())
1283 typeCode = "f";
1284 else if (elementType->isSignedIntegerType())
1285 typeCode = "s";
1286 else if (elementType->isUnsignedIntegerType())
1287 typeCode = "u";
1288 else
1289 llvm_unreachable("Invalid element type!");
1290
1291 SemaRef.Diag(IList->getLocStart(),
1292 SemaRef.Context.getTypeSize(VT) > 64 ?
1293 diag::note_neon_vector_initializer_non_portable_q :
1294 diag::note_neon_vector_initializer_non_portable)
1295 << typeCode << typeSize;
1296 }
1297
John McCall20e047a2010-10-30 00:11:39 +00001298 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001299 }
John McCall20e047a2010-10-30 00:11:39 +00001300
1301 InitializedEntity ElementEntity =
1302 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001303
John McCall20e047a2010-10-30 00:11:39 +00001304 // OpenCL initializers allows vectors to be constructed from vectors.
1305 for (unsigned i = 0; i < maxElements; ++i) {
1306 // Don't attempt to go past the end of the init list
1307 if (Index >= IList->getNumInits())
1308 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001309
John McCall20e047a2010-10-30 00:11:39 +00001310 ElementEntity.setElementIndex(Index);
1311
1312 QualType IType = IList->getInit(Index)->getType();
1313 if (!IType->isVectorType()) {
1314 CheckSubElementType(ElementEntity, IList, elementType, Index,
1315 StructuredList, StructuredIndex);
1316 ++numEltsInit;
1317 } else {
1318 QualType VecType;
1319 const VectorType *IVT = IType->getAs<VectorType>();
1320 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001321
John McCall20e047a2010-10-30 00:11:39 +00001322 if (IType->isExtVectorType())
1323 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1324 else
1325 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001326 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001327 CheckSubElementType(ElementEntity, IList, VecType, Index,
1328 StructuredList, StructuredIndex);
1329 numEltsInit += numIElts;
1330 }
1331 }
1332
1333 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001334 if (numEltsInit != maxElements) {
1335 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001336 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001337 diag::err_vector_incorrect_num_initializers)
1338 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1339 hadError = true;
1340 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001341}
1342
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001343void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001344 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001345 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001346 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001347 unsigned &Index,
1348 InitListExpr *StructuredList,
1349 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001350 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1351
Steve Naroff0cca7492008-05-01 22:18:59 +00001352 // Check for the special-case of initializing an array with a string.
1353 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001354 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1355 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001356 // We place the string literal directly into the resulting
1357 // initializer list. This is the only place where the structure
1358 // of the structured initializer list doesn't match exactly,
1359 // because doing so would involve allocating one character
1360 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001361 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001362 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1363 UpdateStructuredListElement(StructuredList, StructuredIndex,
1364 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001365 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1366 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001367 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001368 return;
1369 }
1370 }
John McCallce6c9b72011-02-21 07:22:22 +00001371 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001372 // Check for VLAs; in standard C it would be possible to check this
1373 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1374 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001375 if (!VerifyOnly)
1376 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1377 diag::err_variable_object_no_init)
1378 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001379 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001380 ++Index;
1381 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001382 return;
1383 }
1384
Douglas Gregor05c13a32009-01-22 00:58:24 +00001385 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001386 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1387 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001388 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001389 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001390 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001391 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001392 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001393 maxElementsKnown = true;
1394 }
1395
John McCallce6c9b72011-02-21 07:22:22 +00001396 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001397 while (Index < IList->getNumInits()) {
1398 Expr *Init = IList->getInit(Index);
1399 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001400 // If we're not the subobject that matches up with the '{' for
1401 // the designator, we shouldn't be handling the
1402 // designator. Return immediately.
1403 if (!SubobjectIsDesignatorContext)
1404 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001405
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 // Handle this designated initializer. elementIndex will be
1407 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001408 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001409 DeclType, nullptr, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001410 StructuredList, StructuredIndex, true,
1411 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001412 hadError = true;
1413 continue;
1414 }
1415
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001416 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001417 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001418 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001419 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001420 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001421
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001422 // If the array is of incomplete type, keep track of the number of
1423 // elements in the initializer.
1424 if (!maxElementsKnown && elementIndex > maxElements)
1425 maxElements = elementIndex;
1426
Douglas Gregor05c13a32009-01-22 00:58:24 +00001427 continue;
1428 }
1429
1430 // If we know the maximum number of elements, and we've already
1431 // hit it, stop consuming elements in the initializer list.
1432 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001433 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001434
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001435 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001436 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001437 Entity);
1438 // Check this element.
1439 CheckSubElementType(ElementEntity, IList, elementType, Index,
1440 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001441 ++elementIndex;
1442
1443 // If the array is of incomplete type, keep track of the number of
1444 // elements in the initializer.
1445 if (!maxElementsKnown && elementIndex > maxElements)
1446 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001447 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001448 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001449 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001450 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001451 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001452 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001453 // Sizing an array implicitly to zero is not allowed by ISO C,
1454 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001455 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001456 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001457 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001458
Mike Stump1eb44332009-09-09 15:08:12 +00001459 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001460 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001461 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001462 if (!hadError && VerifyOnly) {
1463 // Check if there are any members of the array that get value-initialized.
1464 // If so, check if doing that is possible.
1465 // FIXME: This needs to detect holes left by designated initializers too.
1466 if (maxElementsKnown && elementIndex < maxElements)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001467 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1468 SemaRef.Context, 0, Entity),
1469 IList->getLocEnd());
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001470 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001471}
1472
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001473bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1474 Expr *InitExpr,
1475 FieldDecl *Field,
1476 bool TopLevelObject) {
1477 // Handle GNU flexible array initializers.
1478 unsigned FlexArrayDiag;
1479 if (isa<InitListExpr>(InitExpr) &&
1480 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1481 // Empty flexible array init always allowed as an extension
1482 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001483 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001484 // Disallow flexible array init in C++; it is not required for gcc
1485 // compatibility, and it needs work to IRGen correctly in general.
1486 FlexArrayDiag = diag::err_flexible_array_init;
1487 } else if (!TopLevelObject) {
1488 // Disallow flexible array init on non-top-level object
1489 FlexArrayDiag = diag::err_flexible_array_init;
1490 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1491 // Disallow flexible array init on anything which is not a variable.
1492 FlexArrayDiag = diag::err_flexible_array_init;
1493 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1494 // Disallow flexible array init on local variables.
1495 FlexArrayDiag = diag::err_flexible_array_init;
1496 } else {
1497 // Allow other cases.
1498 FlexArrayDiag = diag::ext_flexible_array_init;
1499 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001500
1501 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001502 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001503 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001504 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001505 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1506 << Field;
1507 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001508
1509 return FlexArrayDiag != diag::ext_flexible_array_init;
1510}
1511
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001512void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001513 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001514 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001515 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001516 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001517 unsigned &Index,
1518 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001519 unsigned &StructuredIndex,
1520 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001521 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Eli Friedmanb85f7072008-05-19 19:16:24 +00001523 // If the record is invalid, some of it's members are invalid. To avoid
1524 // confusion, we forgo checking the intializer for the entire record.
1525 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001526 // Assume it was supposed to consume a single initializer.
1527 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001528 hadError = true;
1529 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001530 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001531
1532 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001533 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001534
1535 // If there's a default initializer, use it.
1536 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1537 if (VerifyOnly)
1538 return;
1539 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1540 Field != FieldEnd; ++Field) {
1541 if (Field->hasInClassInitializer()) {
1542 StructuredList->setInitializedFieldInUnion(*Field);
1543 // FIXME: Actually build a CXXDefaultInitExpr?
1544 return;
1545 }
1546 }
1547 }
1548
1549 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001550 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1551 Field != FieldEnd; ++Field) {
1552 if (Field->getDeclName()) {
1553 if (VerifyOnly)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001554 CheckEmptyInitializable(
1555 InitializedEntity::InitializeMember(*Field, &Entity),
1556 IList->getLocEnd());
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001557 else
David Blaikie581deb32012-06-06 20:45:41 +00001558 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001559 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001560 }
1561 }
1562 return;
1563 }
1564
Douglas Gregor05c13a32009-01-22 00:58:24 +00001565 // If structDecl is a forward declaration, this loop won't do
1566 // anything except look at designated initializers; That's okay,
1567 // because an error should get printed out elsewhere. It might be
1568 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001569 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001570 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001571 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001572 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001573 while (Index < IList->getNumInits()) {
1574 Expr *Init = IList->getInit(Index);
1575
1576 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001577 // If we're not the subobject that matches up with the '{' for
1578 // the designator, we shouldn't be handling the
1579 // designator. Return immediately.
1580 if (!SubobjectIsDesignatorContext)
1581 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001582
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001583 // Handle this designated initializer. Field will be updated to
1584 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001585 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001586 DeclType, &Field, nullptr, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001587 StructuredList, StructuredIndex,
1588 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001589 hadError = true;
1590
Douglas Gregordfb5e592009-02-12 19:00:39 +00001591 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001592
1593 // Disable check for missing fields when designators are used.
1594 // This matches gcc behaviour.
1595 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001596 continue;
1597 }
1598
1599 if (Field == FieldEnd) {
1600 // We've run out of fields. We're done.
1601 break;
1602 }
1603
Douglas Gregordfb5e592009-02-12 19:00:39 +00001604 // We've already initialized a member of a union. We're done.
1605 if (InitializedSomething && DeclType->isUnionType())
1606 break;
1607
Douglas Gregor44b43212008-12-11 16:49:14 +00001608 // If we've hit the flexible array member at the end, we're done.
1609 if (Field->getType()->isIncompleteArrayType())
1610 break;
1611
Douglas Gregor0bb76892009-01-29 16:53:55 +00001612 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001613 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001614 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001615 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001616 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001617
Douglas Gregor54001c12011-06-29 21:51:31 +00001618 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001619 bool InvalidUse;
1620 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001621 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001622 else
David Blaikie581deb32012-06-06 20:45:41 +00001623 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001624 IList->getInit(Index)->getLocStart());
1625 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001626 ++Index;
1627 ++Field;
1628 hadError = true;
1629 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001630 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001631
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001632 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001633 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001634 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1635 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001636 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001637
Sebastian Redl14b0c192011-09-24 17:48:00 +00001638 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001639 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001640 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001641 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001642
1643 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001644 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001645
John McCall80639de2010-03-11 19:32:38 +00001646 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001647 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1648 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1649 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001650 // It is possible we have one or more unnamed bitfields remaining.
1651 // Find first (if any) named field and emit warning.
1652 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1653 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001654 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001655 SemaRef.Diag(IList->getSourceRange().getEnd(),
Stephen Hines651f13c2014-04-23 16:59:28 -07001656 diag::warn_missing_field_initializers) << *it;
John McCall80639de2010-03-11 19:32:38 +00001657 break;
1658 }
1659 }
1660 }
1661
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001662 // Check that any remaining fields can be value-initialized.
1663 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1664 !Field->getType()->isIncompleteArrayType()) {
1665 // FIXME: Should check for holes left by designated initializers too.
1666 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001667 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001668 CheckEmptyInitializable(
1669 InitializedEntity::InitializeMember(*Field, &Entity),
1670 IList->getLocEnd());
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001671 }
1672 }
1673
Mike Stump1eb44332009-09-09 15:08:12 +00001674 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001675 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001676 return;
1677
David Blaikie581deb32012-06-06 20:45:41 +00001678 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001679 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001680 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001681 ++Index;
1682 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001683 }
1684
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001685 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001686 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001687
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001688 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001689 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001690 StructuredList, StructuredIndex);
1691 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001692 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001693 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001694}
Steve Naroff0cca7492008-05-01 22:18:59 +00001695
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001696/// \brief Expand a field designator that refers to a member of an
1697/// anonymous struct or union into a series of field designators that
1698/// refers to the field within the appropriate subobject.
1699///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001700static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001701 DesignatedInitExpr *DIE,
1702 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001703 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001704 typedef DesignatedInitExpr::Designator Designator;
1705
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001706 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001707 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001708 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1709 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1710 if (PI + 1 == PE)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001711 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001712 DIE->getDesignator(DesigIdx)->getDotLoc(),
1713 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1714 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001715 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1716 SourceLocation(), SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001717 assert(isa<FieldDecl>(*PI));
1718 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001719 }
1720
1721 // Expand the current designator into the set of replacement
1722 // designators, so we have a full subobject path down to where the
1723 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001724 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001725 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001726}
Mike Stump1eb44332009-09-09 15:08:12 +00001727
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001728/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001729/// corresponds to FieldName.
1730static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1731 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001732 if (!FieldName)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001733 return nullptr;
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001734
Francois Picheta0e27f02010-12-22 03:46:10 +00001735 assert(AnonField->isAnonymousStructOrUnion());
1736 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001737 while (IndirectFieldDecl *IF =
1738 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001739 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001740 return IF;
1741 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001742 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001743 return nullptr;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001744}
1745
Sebastian Redl14b0c192011-09-24 17:48:00 +00001746static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1747 DesignatedInitExpr *DIE) {
1748 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1749 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1750 for (unsigned I = 0; I < NumIndexExprs; ++I)
1751 IndexExprs[I] = DIE->getSubExpr(I + 1);
1752 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001753 DIE->size(), IndexExprs,
1754 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001755 DIE->usesGNUSyntax(), DIE->getInit());
1756}
1757
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001758namespace {
1759
1760// Callback to only accept typo corrections that are for field members of
1761// the given struct or union.
1762class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1763 public:
1764 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1765 : Record(RD) {}
1766
Stephen Hines651f13c2014-04-23 16:59:28 -07001767 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001768 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1769 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1770 }
1771
1772 private:
1773 RecordDecl *Record;
1774};
1775
1776}
1777
Douglas Gregor05c13a32009-01-22 00:58:24 +00001778/// @brief Check the well-formedness of a C99 designated initializer.
1779///
1780/// Determines whether the designated initializer @p DIE, which
1781/// resides at the given @p Index within the initializer list @p
1782/// IList, is well-formed for a current object of type @p DeclType
1783/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001784/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001785/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001786///
1787/// @param IList The initializer list in which this designated
1788/// initializer occurs.
1789///
Douglas Gregor71199712009-04-15 04:56:10 +00001790/// @param DIE The designated initializer expression.
1791///
1792/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001793///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001794/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001795/// into which the designation in @p DIE should refer.
1796///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001797/// @param NextField If non-NULL and the first designator in @p DIE is
1798/// a field, this will be set to the field declaration corresponding
1799/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001800///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001801/// @param NextElementIndex If non-NULL and the first designator in @p
1802/// DIE is an array designator or GNU array-range designator, this
1803/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001804///
1805/// @param Index Index into @p IList where the designated initializer
1806/// @p DIE occurs.
1807///
Douglas Gregor4c678342009-01-28 21:54:33 +00001808/// @param StructuredList The initializer list expression that
1809/// describes all of the subobject initializers in the order they'll
1810/// actually be initialized.
1811///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001812/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001813bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001814InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001815 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001816 DesignatedInitExpr *DIE,
1817 unsigned DesigIdx,
1818 QualType &CurrentObjectType,
1819 RecordDecl::field_iterator *NextField,
1820 llvm::APSInt *NextElementIndex,
1821 unsigned &Index,
1822 InitListExpr *StructuredList,
1823 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001824 bool FinishSubobjectInit,
1825 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001826 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001827 // Check the actual initialization for the designated object type.
1828 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001829
1830 // Temporarily remove the designator expression from the
1831 // initializer list that the child calls see, so that we don't try
1832 // to re-process the designator.
1833 unsigned OldIndex = Index;
1834 IList->setInit(OldIndex, DIE->getInit());
1835
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001836 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001837 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001838
1839 // Restore the designated initializer expression in the syntactic
1840 // form of the initializer list.
1841 if (IList->getInit(OldIndex) != DIE->getInit())
1842 DIE->setInit(IList->getInit(OldIndex));
1843 IList->setInit(OldIndex, DIE);
1844
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001845 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001846 }
1847
Douglas Gregor71199712009-04-15 04:56:10 +00001848 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001849 bool IsFirstDesignator = (DesigIdx == 0);
1850 if (!VerifyOnly) {
1851 assert((IsFirstDesignator || StructuredList) &&
1852 "Need a non-designated initializer list to start from");
1853
1854 // Determine the structural initializer list that corresponds to the
1855 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001856 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001857 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1858 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001859 SourceRange(D->getLocStart(),
1860 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001861 assert(StructuredList && "Expected a structured initializer list");
1862 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001863
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001864 if (D->isFieldDesignator()) {
1865 // C99 6.7.8p7:
1866 //
1867 // If a designator has the form
1868 //
1869 // . identifier
1870 //
1871 // then the current object (defined below) shall have
1872 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001873 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001874 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001875 if (!RT) {
1876 SourceLocation Loc = D->getDotLoc();
1877 if (Loc.isInvalid())
1878 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001879 if (!VerifyOnly)
1880 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001881 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001882 ++Index;
1883 return true;
1884 }
1885
Douglas Gregor4c678342009-01-28 21:54:33 +00001886 // Note: we perform a linear search of the fields here, despite
1887 // the fact that we have a faster lookup method, because we always
1888 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001889 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001890 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001891 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001892 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001893 Field = RT->getDecl()->field_begin(),
1894 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001895 for (; Field != FieldEnd; ++Field) {
1896 if (Field->isUnnamedBitfield())
1897 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001898
Francois Picheta0e27f02010-12-22 03:46:10 +00001899 // If we find a field representing an anonymous field, look in the
1900 // IndirectFieldDecl that follow for the designated initializer.
1901 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1902 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001903 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001904 // In verify mode, don't modify the original.
1905 if (VerifyOnly)
1906 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001907 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1908 D = DIE->getDesignator(DesigIdx);
1909 break;
1910 }
1911 }
David Blaikie581deb32012-06-06 20:45:41 +00001912 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001913 break;
1914 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001915 break;
1916
1917 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001918 }
1919
Douglas Gregor4c678342009-01-28 21:54:33 +00001920 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001921 if (VerifyOnly) {
1922 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001923 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001924 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001925
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001926 // There was no normal field in the struct with the designated
1927 // name. Perform another lookup for this name, which may find
1928 // something that we can't designate (e.g., a member function),
1929 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001930 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001931 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001932 FieldDecl *ReplacementField = nullptr;
David Blaikie3bc93e32012-12-19 00:45:41 +00001933 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001934 // Name lookup didn't find anything. Determine whether this
1935 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001936 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smith2d670972013-08-17 00:46:16 +00001937 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1938 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001939 Sema::LookupMemberName, /*Scope=*/ nullptr, /*SS=*/ nullptr,
1940 Validator, Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smith2d670972013-08-17 00:46:16 +00001941 SemaRef.diagnoseTypo(
1942 Corrected,
1943 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1944 << FieldName << CurrentObjectType);
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001945 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramera41ee492011-09-25 02:41:26 +00001946 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001947 } else {
1948 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1949 << FieldName << CurrentObjectType;
1950 ++Index;
1951 return true;
1952 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001953 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001954
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001955 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001956 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001957 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001958 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001959 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001960 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001961 ++Index;
1962 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001963 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001964
Francois Picheta0e27f02010-12-22 03:46:10 +00001965 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001966 // The replacement field comes from typo correction; find it
1967 // in the list of fields.
1968 FieldIndex = 0;
1969 Field = RT->getDecl()->field_begin();
1970 for (; Field != FieldEnd; ++Field) {
1971 if (Field->isUnnamedBitfield())
1972 continue;
1973
David Blaikie581deb32012-06-06 20:45:41 +00001974 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001975 Field->getIdentifier() == ReplacementField->getIdentifier())
1976 break;
1977
1978 ++FieldIndex;
1979 }
1980 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001981 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001982
1983 // All of the fields of a union are located at the same place in
1984 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001985 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001986 FieldIndex = 0;
Matthew Curtis4e499522013-10-03 12:14:24 +00001987 if (!VerifyOnly) {
1988 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1989 if (CurrentField && CurrentField != *Field) {
1990 assert(StructuredList->getNumInits() == 1
1991 && "A union should never have more than one initializer!");
1992
1993 // we're about to throw away an initializer, emit warning
1994 SemaRef.Diag(D->getFieldLoc(),
1995 diag::warn_initializer_overrides)
1996 << D->getSourceRange();
1997 Expr *ExistingInit = StructuredList->getInit(0);
1998 SemaRef.Diag(ExistingInit->getLocStart(),
1999 diag::note_previous_initializer)
2000 << /*FIXME:has side effects=*/0
2001 << ExistingInit->getSourceRange();
2002
2003 // remove existing initializer
2004 StructuredList->resizeInits(SemaRef.Context, 0);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002005 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis4e499522013-10-03 12:14:24 +00002006 }
2007
David Blaikie581deb32012-06-06 20:45:41 +00002008 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis4e499522013-10-03 12:14:24 +00002009 }
Douglas Gregor0bb76892009-01-29 16:53:55 +00002010 }
Douglas Gregor4c678342009-01-28 21:54:33 +00002011
Douglas Gregor54001c12011-06-29 21:51:31 +00002012 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002013 bool InvalidUse;
2014 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00002015 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00002016 else
David Blaikie581deb32012-06-06 20:45:41 +00002017 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00002018 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00002019 ++Index;
2020 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002021 }
Douglas Gregor54001c12011-06-29 21:51:31 +00002022
Sebastian Redl14b0c192011-09-24 17:48:00 +00002023 if (!VerifyOnly) {
2024 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00002025 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Sebastian Redl14b0c192011-09-24 17:48:00 +00002027 // Make sure that our non-designated initializer list has space
2028 // for a subobject corresponding to this field.
2029 if (FieldIndex >= StructuredList->getNumInits())
2030 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2031 }
Douglas Gregor4c678342009-01-28 21:54:33 +00002032
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002033 // This designator names a flexible array member.
2034 if (Field->getType()->isIncompleteArrayType()) {
2035 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00002036 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002037 // We can't designate an object within the flexible array
2038 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00002039 if (!VerifyOnly) {
2040 DesignatedInitExpr::Designator *NextD
2041 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00002042 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002043 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00002044 << SourceRange(NextD->getLocStart(),
2045 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00002046 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00002047 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002048 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002049 Invalid = true;
2050 }
2051
Chris Lattner9046c222010-10-10 17:49:49 +00002052 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2053 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002054 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002055 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002056 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002057 diag::err_flexible_array_init_needs_braces)
2058 << DIE->getInit()->getSourceRange();
2059 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00002060 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002061 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002062 Invalid = true;
2063 }
2064
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00002065 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00002066 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00002067 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002068 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002069
2070 if (Invalid) {
2071 ++Index;
2072 return true;
2073 }
2074
2075 // Initialize the array.
2076 bool prevHadError = hadError;
2077 unsigned newStructuredIndex = FieldIndex;
2078 unsigned OldIndex = Index;
2079 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002080
2081 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00002082 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002083 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002084 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002085
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002086 IList->setInit(OldIndex, DIE);
2087 if (hadError && !prevHadError) {
2088 ++Field;
2089 ++FieldIndex;
2090 if (NextField)
2091 *NextField = Field;
2092 StructuredIndex = FieldIndex;
2093 return true;
2094 }
2095 } else {
2096 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00002097 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002098 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002099
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002100 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00002101 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002102 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002103 FieldType, nullptr, nullptr, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002104 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002105 true, false))
2106 return true;
2107 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002108
2109 // Find the position of the next field to be initialized in this
2110 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002111 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00002112 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002113
2114 // If this the first designator, our caller will continue checking
2115 // the rest of this struct/class/union subobject.
2116 if (IsFirstDesignator) {
2117 if (NextField)
2118 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00002119 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002120 return false;
2121 }
2122
Douglas Gregor34e79462009-01-28 23:36:17 +00002123 if (!FinishSubobjectInit)
2124 return false;
2125
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002126 // We've already initialized something in the union; we're done.
2127 if (RT->getDecl()->isUnion())
2128 return hadError;
2129
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002130 // Check the remaining fields within this class/struct/union subobject.
2131 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002132
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002133 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002134 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002135 return hadError && !prevHadError;
2136 }
2137
2138 // C99 6.7.8p6:
2139 //
2140 // If a designator has the form
2141 //
2142 // [ constant-expression ]
2143 //
2144 // then the current object (defined below) shall have array
2145 // type and the expression shall be an integer constant
2146 // expression. If the array is of unknown size, any
2147 // nonnegative value is valid.
2148 //
2149 // Additionally, cope with the GNU extension that permits
2150 // designators of the form
2151 //
2152 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002153 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002154 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002155 if (!VerifyOnly)
2156 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2157 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002158 ++Index;
2159 return true;
2160 }
2161
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002162 Expr *IndexExpr = nullptr;
Douglas Gregor34e79462009-01-28 23:36:17 +00002163 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2164 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002165 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002166 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002167 DesignatedEndIndex = DesignatedStartIndex;
2168 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002169 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002170
Mike Stump1eb44332009-09-09 15:08:12 +00002171 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002172 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002173 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002174 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002175 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002176
Chris Lattnere0fd8322011-02-19 22:28:58 +00002177 // Codegen can't handle evaluating array range designators that have side
2178 // effects, because we replicate the AST value for each initialized element.
2179 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2180 // elements with something that has a side effect, so codegen can emit an
2181 // "error unsupported" error instead of miscompiling the app.
2182 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002183 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002184 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002185 }
2186
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002187 if (isa<ConstantArrayType>(AT)) {
2188 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002189 DesignatedStartIndex
2190 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002191 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002192 DesignatedEndIndex
2193 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002194 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2195 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002196 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002197 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002198 diag::err_array_designator_too_large)
2199 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2200 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002201 ++Index;
2202 return true;
2203 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002204 } else {
2205 // Make sure the bit-widths and signedness match.
2206 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002207 DesignatedEndIndex
2208 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002209 else if (DesignatedStartIndex.getBitWidth() <
2210 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002211 DesignatedStartIndex
2212 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002213 DesignatedStartIndex.setIsUnsigned(true);
2214 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002215 }
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Eli Friedman188ddb12013-06-11 21:48:11 +00002217 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2218 // We're modifying a string literal init; we have to decompose the string
2219 // so we can modify the individual characters.
2220 ASTContext &Context = SemaRef.Context;
2221 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2222
2223 // Compute the character type
2224 QualType CharTy = AT->getElementType();
2225
2226 // Compute the type of the integer literals.
2227 QualType PromotedCharTy = CharTy;
2228 if (CharTy->isPromotableIntegerType())
2229 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2230 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2231
2232 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2233 // Get the length of the string.
2234 uint64_t StrLen = SL->getLength();
2235 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2236 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2237 StructuredList->resizeInits(Context, StrLen);
2238
2239 // Build a literal for each character in the string, and put them into
2240 // the init list.
2241 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2242 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2243 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002244 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002245 if (CharTy != PromotedCharTy)
2246 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002247 Init, nullptr, VK_RValue);
Eli Friedman188ddb12013-06-11 21:48:11 +00002248 StructuredList->updateInit(Context, i, Init);
2249 }
2250 } else {
2251 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2252 std::string Str;
2253 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2254
2255 // Get the length of the string.
2256 uint64_t StrLen = Str.size();
2257 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2258 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2259 StructuredList->resizeInits(Context, StrLen);
2260
2261 // Build a literal for each character in the string, and put them into
2262 // the init list.
2263 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2264 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2265 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002266 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002267 if (CharTy != PromotedCharTy)
2268 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002269 Init, nullptr, VK_RValue);
Eli Friedman188ddb12013-06-11 21:48:11 +00002270 StructuredList->updateInit(Context, i, Init);
2271 }
2272 }
2273 }
2274
Douglas Gregor4c678342009-01-28 21:54:33 +00002275 // Make sure that our non-designated initializer list has space
2276 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002277 if (!VerifyOnly &&
2278 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002279 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002280 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002281
Douglas Gregor34e79462009-01-28 23:36:17 +00002282 // Repeatedly perform subobject initializations in the range
2283 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002284
Douglas Gregor34e79462009-01-28 23:36:17 +00002285 // Move to the next designator
2286 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2287 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002288
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002289 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002290 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002291
Douglas Gregor34e79462009-01-28 23:36:17 +00002292 while (DesignatedStartIndex <= DesignatedEndIndex) {
2293 // Recurse to check later designated subobjects.
2294 QualType ElementType = AT->getElementType();
2295 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002296
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002297 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002298 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002299 ElementType, nullptr, nullptr, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002300 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002301 (DesignatedStartIndex == DesignatedEndIndex),
2302 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002303 return true;
2304
2305 // Move to the next index in the array that we'll be initializing.
2306 ++DesignatedStartIndex;
2307 ElementIndex = DesignatedStartIndex.getZExtValue();
2308 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002309
2310 // If this the first designator, our caller will continue checking
2311 // the rest of this array subobject.
2312 if (IsFirstDesignator) {
2313 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002314 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002315 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002316 return false;
2317 }
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Douglas Gregor34e79462009-01-28 23:36:17 +00002319 if (!FinishSubobjectInit)
2320 return false;
2321
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002322 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002323 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002324 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002325 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002326 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002327 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002328}
2329
Douglas Gregor4c678342009-01-28 21:54:33 +00002330// Get the structured initializer list for a subobject of type
2331// @p CurrentObjectType.
2332InitListExpr *
2333InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2334 QualType CurrentObjectType,
2335 InitListExpr *StructuredList,
2336 unsigned StructuredIndex,
2337 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002338 if (VerifyOnly)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002339 return nullptr; // No structured list in verification-only mode.
2340 Expr *ExistingInit = nullptr;
Douglas Gregor4c678342009-01-28 21:54:33 +00002341 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002342 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002343 else if (StructuredIndex < StructuredList->getNumInits())
2344 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Douglas Gregor4c678342009-01-28 21:54:33 +00002346 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2347 return Result;
2348
2349 if (ExistingInit) {
2350 // We are creating an initializer list that initializes the
2351 // subobjects of the current object, but there was already an
2352 // initialization that completely initialized the current
2353 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002354 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002355 // struct X { int a, b; };
2356 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002357 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002358 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2359 // designated initializer re-initializes the whole
2360 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002361 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002362 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002363 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002364 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002365 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002366 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002367 << ExistingInit->getSourceRange();
2368 }
2369
Mike Stump1eb44332009-09-09 15:08:12 +00002370 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002371 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002372 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002373 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002374
Eli Friedman5c89c392012-02-23 02:25:10 +00002375 QualType ResultType = CurrentObjectType;
2376 if (!ResultType->isArrayType())
2377 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2378 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002379
Douglas Gregorfa219202009-03-20 23:58:33 +00002380 // Pre-allocate storage for the structured initializer list.
2381 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002382 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002383 bool GotNumInits = false;
2384 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002385 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002386 GotNumInits = true;
2387 } else if (Index < IList->getNumInits()) {
2388 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002389 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002390 GotNumInits = true;
2391 }
Douglas Gregor08457732009-03-21 18:13:52 +00002392 }
2393
Mike Stump1eb44332009-09-09 15:08:12 +00002394 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002395 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2396 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2397 NumElements = CAType->getSize().getZExtValue();
2398 // Simple heuristic so that we don't allocate a very large
2399 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002400 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002401 NumElements = 0;
2402 }
John McCall183700f2009-09-21 23:43:11 +00002403 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002404 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002405 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002406 RecordDecl *RDecl = RType->getDecl();
2407 if (RDecl->isUnion())
2408 NumElements = 1;
2409 else
Stephen Hines651f13c2014-04-23 16:59:28 -07002410 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002411 }
2412
Ted Kremenek709210f2010-04-13 23:39:13 +00002413 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002414
Douglas Gregor4c678342009-01-28 21:54:33 +00002415 // Link this new initializer list into the structured initializer
2416 // lists.
2417 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002418 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002419 else {
2420 Result->setSyntacticForm(IList);
2421 SyntacticToSemantic[IList] = Result;
2422 }
2423
2424 return Result;
2425}
2426
2427/// Update the initializer at index @p StructuredIndex within the
2428/// structured initializer list to the value @p expr.
2429void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2430 unsigned &StructuredIndex,
2431 Expr *expr) {
2432 // No structured initializer list to update
2433 if (!StructuredList)
2434 return;
2435
Ted Kremenek709210f2010-04-13 23:39:13 +00002436 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2437 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002438 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002439 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002440 diag::warn_initializer_overrides)
2441 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002442 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002443 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002444 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002445 << PrevInit->getSourceRange();
2446 }
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Douglas Gregor4c678342009-01-28 21:54:33 +00002448 ++StructuredIndex;
2449}
2450
Douglas Gregor05c13a32009-01-22 00:58:24 +00002451/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002452/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002453/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002454/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002455/// failure. Returns the index expression, possibly with an implicit cast
2456/// added, on success. If everything went okay, Value will receive the
2457/// value of the constant expression.
2458static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002459CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002460 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002461
2462 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002463 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2464 if (Result.isInvalid())
2465 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002466
Chris Lattner3bf68932009-04-25 21:59:05 +00002467 if (Value.isSigned() && Value.isNegative())
2468 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002469 << Value.toString(10) << Index->getSourceRange();
2470
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002471 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002472 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002473}
2474
John McCall60d7b3a2010-08-24 06:29:42 +00002475ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002476 SourceLocation Loc,
2477 bool GNUSyntax,
2478 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002479 typedef DesignatedInitExpr::Designator ASTDesignator;
2480
2481 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002482 SmallVector<ASTDesignator, 32> Designators;
2483 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002484
2485 // Build designators and check array designator expressions.
2486 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2487 const Designator &D = Desig.getDesignator(Idx);
2488 switch (D.getKind()) {
2489 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002490 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002491 D.getFieldLoc()));
2492 break;
2493
2494 case Designator::ArrayDesignator: {
2495 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2496 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002497 if (!Index->isTypeDependent() && !Index->isValueDependent())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002498 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smith282e7e62012-02-04 09:53:13 +00002499 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002500 Invalid = true;
2501 else {
2502 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002503 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002504 D.getRBracketLoc()));
2505 InitExpressions.push_back(Index);
2506 }
2507 break;
2508 }
2509
2510 case Designator::ArrayRangeDesignator: {
2511 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2512 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2513 llvm::APSInt StartValue;
2514 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002515 bool StartDependent = StartIndex->isTypeDependent() ||
2516 StartIndex->isValueDependent();
2517 bool EndDependent = EndIndex->isTypeDependent() ||
2518 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002519 if (!StartDependent)
2520 StartIndex =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002521 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smith282e7e62012-02-04 09:53:13 +00002522 if (!EndDependent)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002523 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smith282e7e62012-02-04 09:53:13 +00002524
2525 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002526 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002527 else {
2528 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002529 if (StartDependent || EndDependent) {
2530 // Nothing to compute.
2531 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002532 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002533 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002534 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002535
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002536 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002537 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002538 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002539 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2540 Invalid = true;
2541 } else {
2542 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002543 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002544 D.getEllipsisLoc(),
2545 D.getRBracketLoc()));
2546 InitExpressions.push_back(StartIndex);
2547 InitExpressions.push_back(EndIndex);
2548 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002549 }
2550 break;
2551 }
2552 }
2553 }
2554
2555 if (Invalid || Init.isInvalid())
2556 return ExprError();
2557
2558 // Clear out the expressions within the designation.
2559 Desig.ClearExprs(*this);
2560
2561 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002562 = DesignatedInitExpr::Create(Context,
2563 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002564 InitExpressions, Loc, GNUSyntax,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002565 Init.getAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002566
David Blaikie4e4d0842012-03-11 07:00:24 +00002567 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002568 Diag(DIE->getLocStart(), diag::ext_designated_init)
2569 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002570
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002571 return DIE;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002572}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002573
Douglas Gregor20093b42009-12-09 23:02:17 +00002574//===----------------------------------------------------------------------===//
2575// Initialization entity
2576//===----------------------------------------------------------------------===//
2577
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002578InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002579 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002580 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002581{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002582 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2583 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002584 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002585 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002586 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002587 Type = VT->getElementType();
2588 } else {
2589 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2590 assert(CT && "Unexpected type");
2591 Kind = EK_ComplexElement;
2592 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002593 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002594}
2595
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002596InitializedEntity
2597InitializedEntity::InitializeBase(ASTContext &Context,
2598 const CXXBaseSpecifier *Base,
2599 bool IsInheritedVirtualBase) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002600 InitializedEntity Result;
2601 Result.Kind = EK_Base;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002602 Result.Parent = nullptr;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002603 Result.Base = reinterpret_cast<uintptr_t>(Base);
2604 if (IsInheritedVirtualBase)
2605 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002606
Douglas Gregord6542d82009-12-22 15:35:07 +00002607 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002608 return Result;
2609}
2610
Douglas Gregor99a2e602009-12-16 01:38:02 +00002611DeclarationName InitializedEntity::getName() const {
2612 switch (getKind()) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002613 case EK_Parameter:
2614 case EK_Parameter_CF_Audited: {
John McCallf85e1932011-06-15 23:02:42 +00002615 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2616 return (D ? D->getDeclName() : DeclarationName());
2617 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002618
2619 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002620 case EK_Member:
2621 return VariableOrMember->getDeclName();
2622
Douglas Gregor47736542012-02-15 16:57:26 +00002623 case EK_LambdaCapture:
Bill Wendling2434dcf2013-12-05 05:25:04 +00002624 return DeclarationName(Capture.VarID);
Douglas Gregor47736542012-02-15 16:57:26 +00002625
Douglas Gregor99a2e602009-12-16 01:38:02 +00002626 case EK_Result:
2627 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002628 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002629 case EK_Temporary:
2630 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002631 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002632 case EK_ArrayElement:
2633 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002634 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002635 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002636 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002637 case EK_RelatedResult:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002638 return DeclarationName();
2639 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002640
David Blaikie7530c032012-01-17 06:56:22 +00002641 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002642}
2643
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002644DeclaratorDecl *InitializedEntity::getDecl() const {
2645 switch (getKind()) {
2646 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002647 case EK_Member:
2648 return VariableOrMember;
2649
John McCallf85e1932011-06-15 23:02:42 +00002650 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002651 case EK_Parameter_CF_Audited:
John McCallf85e1932011-06-15 23:02:42 +00002652 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2653
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002654 case EK_Result:
2655 case EK_Exception:
2656 case EK_New:
2657 case EK_Temporary:
2658 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002659 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002660 case EK_ArrayElement:
2661 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002662 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002663 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002664 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002665 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002666 case EK_RelatedResult:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002667 return nullptr;
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002668 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002669
David Blaikie7530c032012-01-17 06:56:22 +00002670 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002671}
2672
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002673bool InitializedEntity::allowsNRVO() const {
2674 switch (getKind()) {
2675 case EK_Result:
2676 case EK_Exception:
2677 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002678
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002679 case EK_Variable:
2680 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002681 case EK_Parameter_CF_Audited:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002682 case EK_Member:
2683 case EK_New:
2684 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002685 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002686 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002687 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002688 case EK_ArrayElement:
2689 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002690 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002691 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002692 case EK_LambdaCapture:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002693 case EK_RelatedResult:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002694 break;
2695 }
2696
2697 return false;
2698}
2699
Richard Smith211c8dd2013-06-05 00:46:14 +00002700unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smitha4bb99c2013-06-12 21:51:50 +00002701 assert(getParent() != this);
Richard Smith211c8dd2013-06-05 00:46:14 +00002702 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2703 for (unsigned I = 0; I != Depth; ++I)
2704 OS << "`-";
2705
2706 switch (getKind()) {
2707 case EK_Variable: OS << "Variable"; break;
2708 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002709 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2710 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002711 case EK_Result: OS << "Result"; break;
2712 case EK_Exception: OS << "Exception"; break;
2713 case EK_Member: OS << "Member"; break;
2714 case EK_New: OS << "New"; break;
2715 case EK_Temporary: OS << "Temporary"; break;
2716 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002717 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002718 case EK_Base: OS << "Base"; break;
2719 case EK_Delegating: OS << "Delegating"; break;
2720 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2721 case EK_VectorElement: OS << "VectorElement " << Index; break;
2722 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2723 case EK_BlockElement: OS << "Block"; break;
2724 case EK_LambdaCapture:
2725 OS << "LambdaCapture ";
Bill Wendling2434dcf2013-12-05 05:25:04 +00002726 OS << DeclarationName(Capture.VarID);
Richard Smith211c8dd2013-06-05 00:46:14 +00002727 break;
2728 }
2729
2730 if (Decl *D = getDecl()) {
2731 OS << " ";
2732 cast<NamedDecl>(D)->printQualifiedName(OS);
2733 }
2734
2735 OS << " '" << getType().getAsString() << "'\n";
2736
2737 return Depth + 1;
2738}
2739
2740void InitializedEntity::dump() const {
2741 dumpImpl(llvm::errs());
2742}
2743
Douglas Gregor20093b42009-12-09 23:02:17 +00002744//===----------------------------------------------------------------------===//
2745// Initialization sequence
2746//===----------------------------------------------------------------------===//
2747
2748void InitializationSequence::Step::Destroy() {
2749 switch (Kind) {
2750 case SK_ResolveAddressOfOverloadedFunction:
2751 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002752 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002753 case SK_CastDerivedToBaseLValue:
2754 case SK_BindReference:
2755 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002756 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002757 case SK_UserConversion:
2758 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002759 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002760 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002761 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002762 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002763 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002764 case SK_UnwrapInitList:
2765 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002766 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002767 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002768 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002769 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002770 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002771 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002772 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002773 case SK_PassByIndirectCopyRestore:
2774 case SK_PassByIndirectRestore:
2775 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002776 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002777 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002778 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002779 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002780
Douglas Gregor20093b42009-12-09 23:02:17 +00002781 case SK_ConversionSequence:
Richard Smith13b228d2013-09-21 21:19:19 +00002782 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor20093b42009-12-09 23:02:17 +00002783 delete ICS;
2784 }
2785}
2786
Douglas Gregorb70cf442010-03-26 20:14:36 +00002787bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002788 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002789}
2790
2791bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002792 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002793 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002794
Douglas Gregorb70cf442010-03-26 20:14:36 +00002795 switch (getFailureKind()) {
2796 case FK_TooManyInitsForReference:
2797 case FK_ArrayNeedsInitList:
2798 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002799 case FK_ArrayNeedsInitListOrWideStringLiteral:
2800 case FK_NarrowStringIntoWideCharArray:
2801 case FK_WideStringIntoCharArray:
2802 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002803 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2804 case FK_NonConstLValueReferenceBindingToTemporary:
2805 case FK_NonConstLValueReferenceBindingToUnrelated:
2806 case FK_RValueReferenceBindingToLValue:
2807 case FK_ReferenceInitDropsQualifiers:
2808 case FK_ReferenceInitFailed:
2809 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002810 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002811 case FK_TooManyInitsForScalar:
2812 case FK_ReferenceBindingToInitList:
2813 case FK_InitListBadDestinationType:
2814 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002815 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002816 case FK_ArrayTypeMismatch:
2817 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002818 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002819 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002820 case FK_PlaceholderType:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002821 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002822 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002823
Douglas Gregorb70cf442010-03-26 20:14:36 +00002824 case FK_ReferenceInitOverloadFailed:
2825 case FK_UserConversionOverloadFailed:
2826 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002827 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002828 return FailedOverloadResult == OR_Ambiguous;
2829 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830
David Blaikie7530c032012-01-17 06:56:22 +00002831 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002832}
2833
Douglas Gregord6e44a32010-04-16 22:09:46 +00002834bool InitializationSequence::isConstructorInitialization() const {
2835 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2836}
2837
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002838void
2839InitializationSequence
2840::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2841 DeclAccessPair Found,
2842 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002843 Step S;
2844 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2845 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002846 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002847 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002848 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002849 Steps.push_back(S);
2850}
2851
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002852void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002853 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002854 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002855 switch (VK) {
2856 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2857 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2858 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002859 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002860 S.Type = BaseType;
2861 Steps.push_back(S);
2862}
2863
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002864void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002865 bool BindingTemporary) {
2866 Step S;
2867 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2868 S.Type = T;
2869 Steps.push_back(S);
2870}
2871
Douglas Gregor523d46a2010-04-18 07:40:54 +00002872void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2873 Step S;
2874 S.Kind = SK_ExtraneousCopyToTemporary;
2875 S.Type = T;
2876 Steps.push_back(S);
2877}
2878
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002879void
2880InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2881 DeclAccessPair FoundDecl,
2882 QualType T,
2883 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002884 Step S;
2885 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002886 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002887 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002888 S.Function.Function = Function;
2889 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002890 Steps.push_back(S);
2891}
2892
2893void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002894 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002895 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002896 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002897 switch (VK) {
2898 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002899 S.Kind = SK_QualificationConversionRValue;
2900 break;
John McCall5baba9d2010-08-25 10:28:54 +00002901 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002902 S.Kind = SK_QualificationConversionXValue;
2903 break;
John McCall5baba9d2010-08-25 10:28:54 +00002904 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002905 S.Kind = SK_QualificationConversionLValue;
2906 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002907 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002908 S.Type = Ty;
2909 Steps.push_back(S);
2910}
2911
Jordan Rose1fd1e282013-04-11 00:58:58 +00002912void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2913 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2914
2915 Step S;
2916 S.Kind = SK_LValueToRValue;
2917 S.Type = Ty;
2918 Steps.push_back(S);
2919}
2920
Douglas Gregor20093b42009-12-09 23:02:17 +00002921void InitializationSequence::AddConversionSequenceStep(
Richard Smith13b228d2013-09-21 21:19:19 +00002922 const ImplicitConversionSequence &ICS, QualType T,
2923 bool TopLevelOfInitList) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002924 Step S;
Richard Smith13b228d2013-09-21 21:19:19 +00002925 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2926 : SK_ConversionSequence;
Douglas Gregor20093b42009-12-09 23:02:17 +00002927 S.Type = T;
2928 S.ICS = new ImplicitConversionSequence(ICS);
2929 Steps.push_back(S);
2930}
2931
Douglas Gregord87b61f2009-12-10 17:56:55 +00002932void InitializationSequence::AddListInitializationStep(QualType T) {
2933 Step S;
2934 S.Kind = SK_ListInitialization;
2935 S.Type = T;
2936 Steps.push_back(S);
2937}
2938
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002939void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002940InitializationSequence
2941::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2942 AccessSpecifier Access,
2943 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002944 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002945 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002946 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002947 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2948 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002949 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002950 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002951 S.Function.Function = Constructor;
2952 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002953 Steps.push_back(S);
2954}
2955
Douglas Gregor71d17402009-12-15 00:01:57 +00002956void InitializationSequence::AddZeroInitializationStep(QualType T) {
2957 Step S;
2958 S.Kind = SK_ZeroInitialization;
2959 S.Type = T;
2960 Steps.push_back(S);
2961}
2962
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002963void InitializationSequence::AddCAssignmentStep(QualType T) {
2964 Step S;
2965 S.Kind = SK_CAssignment;
2966 S.Type = T;
2967 Steps.push_back(S);
2968}
2969
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002970void InitializationSequence::AddStringInitStep(QualType T) {
2971 Step S;
2972 S.Kind = SK_StringInit;
2973 S.Type = T;
2974 Steps.push_back(S);
2975}
2976
Douglas Gregor569c3162010-08-07 11:51:51 +00002977void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2978 Step S;
2979 S.Kind = SK_ObjCObjectConversion;
2980 S.Type = T;
2981 Steps.push_back(S);
2982}
2983
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002984void InitializationSequence::AddArrayInitStep(QualType T) {
2985 Step S;
2986 S.Kind = SK_ArrayInit;
2987 S.Type = T;
2988 Steps.push_back(S);
2989}
2990
Richard Smith0f163e92012-02-15 22:38:09 +00002991void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2992 Step S;
2993 S.Kind = SK_ParenthesizedArrayInit;
2994 S.Type = T;
2995 Steps.push_back(S);
2996}
2997
John McCallf85e1932011-06-15 23:02:42 +00002998void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2999 bool shouldCopy) {
3000 Step s;
3001 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3002 : SK_PassByIndirectRestore);
3003 s.Type = type;
3004 Steps.push_back(s);
3005}
3006
3007void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3008 Step S;
3009 S.Kind = SK_ProduceObjCObject;
3010 S.Type = T;
3011 Steps.push_back(S);
3012}
3013
Sebastian Redl2b916b82012-01-17 22:49:42 +00003014void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3015 Step S;
3016 S.Kind = SK_StdInitializerList;
3017 S.Type = T;
3018 Steps.push_back(S);
3019}
3020
Guy Benyei21f18c42013-02-07 10:55:47 +00003021void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3022 Step S;
3023 S.Kind = SK_OCLSamplerInit;
3024 S.Type = T;
3025 Steps.push_back(S);
3026}
3027
Guy Benyeie6b9d802013-01-20 12:31:11 +00003028void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3029 Step S;
3030 S.Kind = SK_OCLZeroEvent;
3031 S.Type = T;
3032 Steps.push_back(S);
3033}
3034
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003035void InitializationSequence::RewrapReferenceInitList(QualType T,
3036 InitListExpr *Syntactic) {
3037 assert(Syntactic->getNumInits() == 1 &&
3038 "Can only rewrap trivial init lists.");
3039 Step S;
3040 S.Kind = SK_UnwrapInitList;
3041 S.Type = Syntactic->getInit(0)->getType();
3042 Steps.insert(Steps.begin(), S);
3043
3044 S.Kind = SK_RewrapInitList;
3045 S.Type = T;
3046 S.WrappingSyntacticList = Syntactic;
3047 Steps.push_back(S);
3048}
3049
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003050void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00003051 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00003052 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00003053 this->Failure = Failure;
3054 this->FailedOverloadResult = Result;
3055}
3056
3057//===----------------------------------------------------------------------===//
3058// Attempt initialization
3059//===----------------------------------------------------------------------===//
3060
John McCallf85e1932011-06-15 23:02:42 +00003061static void MaybeProduceObjCObject(Sema &S,
3062 InitializationSequence &Sequence,
3063 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003064 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00003065
3066 /// When initializing a parameter, produce the value if it's marked
3067 /// __attribute__((ns_consumed)).
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00003068 if (Entity.isParameterKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003069 if (!Entity.isParameterConsumed())
3070 return;
3071
3072 assert(Entity.getType()->isObjCRetainableType() &&
3073 "consuming an object of unretainable type?");
3074 Sequence.AddProduceObjCObjectStep(Entity.getType());
3075
3076 /// When initializing a return value, if the return type is a
3077 /// retainable type, then returns need to immediately retain the
3078 /// object. If an autorelease is required, it will be done at the
3079 /// last instant.
3080 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3081 if (!Entity.getType()->isObjCRetainableType())
3082 return;
3083
3084 Sequence.AddProduceObjCObjectStep(Entity.getType());
3085 }
3086}
3087
Richard Smith7c3e6152013-06-12 22:31:48 +00003088static void TryListInitialization(Sema &S,
3089 const InitializedEntity &Entity,
3090 const InitializationKind &Kind,
3091 InitListExpr *InitList,
3092 InitializationSequence &Sequence);
3093
Richard Smithf4bb8d02012-07-05 08:39:21 +00003094/// \brief When initializing from init list via constructor, handle
3095/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00003096///
Richard Smithf4bb8d02012-07-05 08:39:21 +00003097/// \return true if we have handled initialization of an object of type
3098/// std::initializer_list<T>, false otherwise.
3099static bool TryInitializerListConstruction(Sema &S,
3100 InitListExpr *List,
3101 QualType DestType,
3102 InitializationSequence &Sequence) {
3103 QualType E;
3104 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00003105 return false;
3106
Richard Smith7c3e6152013-06-12 22:31:48 +00003107 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3108 Sequence.setIncompleteTypeFailure(E);
3109 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003110 }
Richard Smith7c3e6152013-06-12 22:31:48 +00003111
3112 // Try initializing a temporary array from the init list.
3113 QualType ArrayType = S.Context.getConstantArrayType(
3114 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3115 List->getNumInits()),
3116 clang::ArrayType::Normal, 0);
3117 InitializedEntity HiddenArray =
3118 InitializedEntity::InitializeTemporary(ArrayType);
3119 InitializationKind Kind =
3120 InitializationKind::CreateDirectList(List->getExprLoc());
3121 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3122 if (Sequence)
3123 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003124 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003125}
3126
Sebastian Redl96715b22012-02-04 21:27:39 +00003127static OverloadingResult
3128ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003129 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00003130 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003131 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00003132 OverloadCandidateSet::iterator &Best,
3133 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003134 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003135 CandidateSet.clear();
3136
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003137 for (ArrayRef<NamedDecl *>::iterator
3138 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003139 NamedDecl *D = *Con;
3140 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3141 bool SuppressUserConversions = false;
3142
3143 // Find the constructor (which may be a template).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003144 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl96715b22012-02-04 21:27:39 +00003145 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3146 if (ConstructorTmpl)
3147 Constructor = cast<CXXConstructorDecl>(
3148 ConstructorTmpl->getTemplatedDecl());
3149 else {
3150 Constructor = cast<CXXConstructorDecl>(D);
3151
Richard Smith867521c2013-09-21 21:23:47 +00003152 // C++11 [over.best.ics]p4:
3153 // However, when considering the argument of a constructor or
3154 // user-defined conversion function that is a candidate:
3155 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3156 // in the second step of a class copy-initialization,
3157 // -- by 13.3.1.7 when passing the initializer list as a single
3158 // argument or when the initializer list has exactly one elementand
3159 // a conversion to some class X or reference to (possibly
3160 // cv-qualified) X is considered for the first parameter of a
3161 // constructor of X, or
3162 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3163 // only standard conversion sequences and ellipsis conversion sequences
3164 // are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003165 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003166 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00003167 SuppressUserConversions = true;
3168 }
3169
3170 if (!Constructor->isInvalidDecl() &&
3171 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003172 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003173 if (ConstructorTmpl)
3174 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003175 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003176 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00003177 else {
3178 // C++ [over.match.copy]p1:
3179 // - When initializing a temporary to be bound to the first parameter
3180 // of a constructor that takes a reference to possibly cv-qualified
3181 // T as its first argument, called with a single argument in the
3182 // context of direct-initialization, explicit conversion functions
3183 // are also considered.
3184 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003185 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00003186 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003187 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00003188 SuppressUserConversions,
3189 /*PartialOverloading=*/false,
3190 /*AllowExplicit=*/AllowExplicitConv);
3191 }
Sebastian Redl96715b22012-02-04 21:27:39 +00003192 }
3193 }
3194
3195 // Perform overload resolution and return the result.
3196 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3197}
3198
Sebastian Redl10f04a62011-12-22 14:44:04 +00003199/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3200/// enumerates the constructors of the initialized entity and performs overload
3201/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00003202/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00003203/// class type.
3204static void TryConstructorInitialization(Sema &S,
3205 const InitializedEntity &Entity,
3206 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003207 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003208 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00003209 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003210 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00003211 "InitListSyntax must come with a single initializer list argument.");
3212
Sebastian Redl10f04a62011-12-22 14:44:04 +00003213 // The type we're constructing needs to be complete.
3214 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003215 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00003216 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003217 }
3218
3219 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3220 assert(DestRecordType && "Constructor initialization requires record type");
3221 CXXRecordDecl *DestRecordDecl
3222 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3223
Sebastian Redl96715b22012-02-04 21:27:39 +00003224 // Build the candidate set directly in the initialization sequence
3225 // structure, so that it will persist if we fail.
3226 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3227
3228 // Determine whether we are allowed to call explicit constructors or
3229 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003230 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003231 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00003232
Sebastian Redl10f04a62011-12-22 14:44:04 +00003233 // - Otherwise, if T is a class type, constructors are considered. The
3234 // applicable constructors are enumerated, and the best one is chosen
3235 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00003236 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003237 // The container holding the constructors can under certain conditions
3238 // be changed while iterating (e.g. because of deserialization).
3239 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003240 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00003241
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003242 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003243 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003244 bool AsInitializerList = false;
3245
3246 // C++11 [over.match.list]p1:
3247 // When objects of non-aggregate type T are list-initialized, overload
3248 // resolution selects the constructor in two phases:
3249 // - Initially, the candidate functions are the initializer-list
3250 // constructors of the class T and the argument list consists of the
3251 // initializer list as a single argument.
3252 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003253 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003254 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003255
3256 // If the initializer list has no elements and T has a default constructor,
3257 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003258 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003259 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003260 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003261 CopyInitialization, AllowExplicit,
3262 /*OnlyListConstructor=*/true,
3263 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003264
3265 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003266 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003267 }
3268
3269 // C++11 [over.match.list]p1:
3270 // - If no viable initializer-list constructor is found, overload resolution
3271 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003272 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003273 // elements of the initializer list.
3274 if (Result == OR_No_Viable_Function) {
3275 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003276 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003277 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003278 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003279 /*OnlyListConstructors=*/false,
3280 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003281 }
3282 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003283 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003284 InitializationSequence::FK_ListConstructorOverloadFailed :
3285 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003286 Result);
3287 return;
3288 }
3289
Richard Smithf4bb8d02012-07-05 08:39:21 +00003290 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003291 // If a program calls for the default initialization of an object
3292 // of a const-qualified type T, T shall be a class type with a
3293 // user-provided default constructor.
3294 if (Kind.getKind() == InitializationKind::IK_Default &&
3295 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003296 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003297 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3298 return;
3299 }
3300
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003301 // C++11 [over.match.list]p1:
3302 // In copy-list-initialization, if an explicit constructor is chosen, the
3303 // initializer is ill-formed.
3304 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3305 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3306 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3307 return;
3308 }
3309
Sebastian Redl10f04a62011-12-22 14:44:04 +00003310 // Add the constructor initialization step. Any cv-qualification conversion is
3311 // subsumed by the initialization.
3312 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003313 Sequence.AddConstructorInitializationStep(CtorDecl,
3314 Best->FoundDecl.getAccess(),
3315 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003316 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003317}
3318
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003319static bool
3320ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3321 Expr *Initializer,
3322 QualType &SourceType,
3323 QualType &UnqualifiedSourceType,
3324 QualType UnqualifiedTargetType,
3325 InitializationSequence &Sequence) {
3326 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3327 S.Context.OverloadTy) {
3328 DeclAccessPair Found;
3329 bool HadMultipleCandidates = false;
3330 if (FunctionDecl *Fn
3331 = S.ResolveAddressOfOverloadedFunction(Initializer,
3332 UnqualifiedTargetType,
3333 false, Found,
3334 &HadMultipleCandidates)) {
3335 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3336 HadMultipleCandidates);
3337 SourceType = Fn->getType();
3338 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3339 } else if (!UnqualifiedTargetType->isRecordType()) {
3340 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3341 return true;
3342 }
3343 }
3344 return false;
3345}
3346
3347static void TryReferenceInitializationCore(Sema &S,
3348 const InitializedEntity &Entity,
3349 const InitializationKind &Kind,
3350 Expr *Initializer,
3351 QualType cv1T1, QualType T1,
3352 Qualifiers T1Quals,
3353 QualType cv2T2, QualType T2,
3354 Qualifiers T2Quals,
3355 InitializationSequence &Sequence);
3356
Richard Smithf4bb8d02012-07-05 08:39:21 +00003357static void TryValueInitialization(Sema &S,
3358 const InitializedEntity &Entity,
3359 const InitializationKind &Kind,
3360 InitializationSequence &Sequence,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003361 InitListExpr *InitList = nullptr);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003362
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003363/// \brief Attempt list initialization of a reference.
3364static void TryReferenceListInitialization(Sema &S,
3365 const InitializedEntity &Entity,
3366 const InitializationKind &Kind,
3367 InitListExpr *InitList,
Richard Smithb6e38082013-06-08 00:02:08 +00003368 InitializationSequence &Sequence) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003369 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003370 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003371 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3372 return;
3373 }
3374
3375 QualType DestType = Entity.getType();
3376 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3377 Qualifiers T1Quals;
3378 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3379
3380 // Reference initialization via an initializer list works thus:
3381 // If the initializer list consists of a single element that is
3382 // reference-related to the referenced type, bind directly to that element
3383 // (possibly creating temporaries).
3384 // Otherwise, initialize a temporary with the initializer list and
3385 // bind to that.
3386 if (InitList->getNumInits() == 1) {
3387 Expr *Initializer = InitList->getInit(0);
3388 QualType cv2T2 = Initializer->getType();
3389 Qualifiers T2Quals;
3390 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3391
3392 // If this fails, creating a temporary wouldn't work either.
3393 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3394 T1, Sequence))
3395 return;
3396
3397 SourceLocation DeclLoc = Initializer->getLocStart();
3398 bool dummy1, dummy2, dummy3;
3399 Sema::ReferenceCompareResult RefRelationship
3400 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3401 dummy2, dummy3);
3402 if (RefRelationship >= Sema::Ref_Related) {
3403 // Try to bind the reference here.
3404 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3405 T1Quals, cv2T2, T2, T2Quals, Sequence);
3406 if (Sequence)
3407 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3408 return;
3409 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003410
3411 // Update the initializer if we've resolved an overloaded function.
3412 if (Sequence.step_begin() != Sequence.step_end())
3413 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003414 }
3415
3416 // Not reference-related. Create a temporary and bind to that.
3417 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3418
3419 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3420 if (Sequence) {
3421 if (DestType->isRValueReferenceType() ||
3422 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3423 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3424 else
3425 Sequence.SetFailed(
3426 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3427 }
3428}
3429
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003430/// \brief Attempt list initialization (C++0x [dcl.init.list])
3431static void TryListInitialization(Sema &S,
3432 const InitializedEntity &Entity,
3433 const InitializationKind &Kind,
3434 InitListExpr *InitList,
3435 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003436 QualType DestType = Entity.getType();
3437
Sebastian Redl14b0c192011-09-24 17:48:00 +00003438 // C++ doesn't allow scalar initialization with more than one argument.
3439 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003440 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003441 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3442 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3443 return;
3444 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003445 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003446 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003447 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003448 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003449 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003450 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003451 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003452 return;
3453 }
3454
Richard Smithf4bb8d02012-07-05 08:39:21 +00003455 // C++11 [dcl.init.list]p3:
3456 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003457 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003458 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003459 // - Otherwise, if the initializer list has no elements and T is a
3460 // class type with a default constructor, the object is
3461 // value-initialized.
3462 if (InitList->getNumInits() == 0) {
3463 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003464 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003465 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3466 return;
3467 }
3468 }
3469
3470 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3471 // an initializer_list object constructed [...]
3472 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3473 return;
3474
3475 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003476 Expr *InitListAsExpr = InitList;
3477 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003478 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003479 } else
3480 Sequence.SetFailed(
3481 InitializationSequence::FK_InitListBadDestinationType);
3482 return;
3483 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003484 }
Richard Smithb390e492013-09-21 21:55:46 +00003485 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3486 InitList->getNumInits() == 1 &&
3487 InitList->getInit(0)->getType()->isRecordType()) {
3488 // - Otherwise, if the initializer list has a single element of type E
3489 // [...references are handled above...], the object or reference is
3490 // initialized from that element; if a narrowing conversion is required
3491 // to convert the element to T, the program is ill-formed.
3492 //
3493 // Per core-24034, this is direct-initialization if we were performing
3494 // direct-list-initialization and copy-initialization otherwise.
3495 // We can't use InitListChecker for this, because it always performs
3496 // copy-initialization. This only matters if we might use an 'explicit'
3497 // conversion operator, so we only need to handle the cases where the source
3498 // is of record type.
3499 InitializationKind SubKind =
3500 Kind.getKind() == InitializationKind::IK_DirectList
3501 ? InitializationKind::CreateDirect(Kind.getLocation(),
3502 InitList->getLBraceLoc(),
3503 InitList->getRBraceLoc())
3504 : Kind;
3505 Expr *SubInit[1] = { InitList->getInit(0) };
3506 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3507 /*TopLevelOfInitList*/true);
3508 if (Sequence)
3509 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3510 return;
3511 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003512
Sebastian Redl14b0c192011-09-24 17:48:00 +00003513 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00003514 DestType, /*VerifyOnly=*/true);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003515 if (CheckInitList.HadError()) {
3516 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3517 return;
3518 }
3519
3520 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003521 Sequence.AddListInitializationStep(DestType);
3522}
Douglas Gregor20093b42009-12-09 23:02:17 +00003523
3524/// \brief Try a reference initialization that involves calling a conversion
3525/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003526static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3527 const InitializedEntity &Entity,
3528 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003529 Expr *Initializer,
3530 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003531 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003532 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003533 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3534 QualType T1 = cv1T1.getUnqualifiedType();
3535 QualType cv2T2 = Initializer->getType();
3536 QualType T2 = cv2T2.getUnqualifiedType();
3537
3538 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003539 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003540 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003541 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003542 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003543 ObjCConversion,
3544 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003545 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003546 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003547 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003548 (void)ObjCLifetimeConversion;
3549
Douglas Gregor20093b42009-12-09 23:02:17 +00003550 // Build the candidate set directly in the initialization sequence
3551 // structure, so that it will persist if we fail.
3552 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3553 CandidateSet.clear();
3554
3555 // Determine whether we are allowed to call explicit constructors or
3556 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003557 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith867521c2013-09-21 21:23:47 +00003558 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3559
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003560 const RecordType *T1RecordType = nullptr;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003561 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3562 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003563 // The type we're converting to is a class type. Enumerate its constructors
3564 // to see if there is a suitable conversion.
3565 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003566
David Blaikie3bc93e32012-12-19 00:45:41 +00003567 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003568 // The container holding the constructors can under certain conditions
3569 // be changed while iterating (e.g. because of deserialization).
3570 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003571 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00003572 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003573 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3574 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003575 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3576
Douglas Gregor20093b42009-12-09 23:02:17 +00003577 // Find the constructor (which may be a template).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003578 CXXConstructorDecl *Constructor = nullptr;
John McCall9aa472c2010-03-19 07:35:19 +00003579 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003580 if (ConstructorTmpl)
3581 Constructor = cast<CXXConstructorDecl>(
3582 ConstructorTmpl->getTemplatedDecl());
3583 else
John McCall9aa472c2010-03-19 07:35:19 +00003584 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003585
Douglas Gregor20093b42009-12-09 23:02:17 +00003586 if (!Constructor->isInvalidDecl() &&
3587 Constructor->isConvertingConstructor(AllowExplicit)) {
3588 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003589 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003590 /*ExplicitArgs*/ nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003591 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003592 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003593 else
John McCall9aa472c2010-03-19 07:35:19 +00003594 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003595 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003596 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003597 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003598 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003599 }
John McCall572fc622010-08-17 07:23:57 +00003600 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3601 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003602
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003603 const RecordType *T2RecordType = nullptr;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003604 if ((T2RecordType = T2->getAs<RecordType>()) &&
3605 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003606 // The type we're converting from is a class type, enumerate its conversion
3607 // functions.
3608 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3609
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003610 std::pair<CXXRecordDecl::conversion_iterator,
3611 CXXRecordDecl::conversion_iterator>
3612 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3613 for (CXXRecordDecl::conversion_iterator
3614 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003615 NamedDecl *D = *I;
3616 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3617 if (isa<UsingShadowDecl>(D))
3618 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003619
Douglas Gregor20093b42009-12-09 23:02:17 +00003620 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3621 CXXConversionDecl *Conv;
3622 if (ConvTemplate)
3623 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3624 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003625 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003626
Douglas Gregor20093b42009-12-09 23:02:17 +00003627 // If the conversion function doesn't return a reference type,
3628 // it can't be considered for this conversion unless we're allowed to
3629 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003630 // FIXME: Do we need to make sure that we only consider conversion
3631 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003632 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003633 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003634 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3635 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003636 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003637 ActingDC, Initializer,
Stephen Hines651f13c2014-04-23 16:59:28 -07003638 DestType, CandidateSet,
3639 /*AllowObjCConversionOnExplicit=*/
3640 false);
Douglas Gregor20093b42009-12-09 23:02:17 +00003641 else
John McCall9aa472c2010-03-19 07:35:19 +00003642 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Stephen Hines651f13c2014-04-23 16:59:28 -07003643 Initializer, DestType, CandidateSet,
3644 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00003645 }
3646 }
3647 }
John McCall572fc622010-08-17 07:23:57 +00003648 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3649 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003650
Douglas Gregor20093b42009-12-09 23:02:17 +00003651 SourceLocation DeclLoc = Initializer->getLocStart();
3652
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003653 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003654 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003656 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003657 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003658
Douglas Gregor20093b42009-12-09 23:02:17 +00003659 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003660 // This is the overload that will be used for this initialization step if we
3661 // use this initialization. Mark it as referenced.
3662 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003663
Eli Friedman03981012009-12-11 02:42:07 +00003664 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003665 if (isa<CXXConversionDecl>(Function))
Stephen Hines651f13c2014-04-23 16:59:28 -07003666 T2 = Function->getReturnType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003667 else
3668 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003669
3670 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003671 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003672 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003673 T2.getNonLValueExprType(S.Context),
3674 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003675
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003676 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003677 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003678 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003679 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003680 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003681 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003682 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003683
Douglas Gregor20093b42009-12-09 23:02:17 +00003684 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003685 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003686 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003687 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003688 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003689 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003690 NewDerivedToBase, NewObjCConversion,
3691 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003692 if (NewRefRelationship == Sema::Ref_Incompatible) {
3693 // If the type we've converted to is not reference-related to the
3694 // type we're looking for, then there is another conversion step
3695 // we need to perform to produce a temporary of the right type
3696 // that we'll be binding to.
3697 ImplicitConversionSequence ICS;
3698 ICS.setStandard();
3699 ICS.Standard = Best->FinalConversion;
3700 T2 = ICS.Standard.getToType(2);
3701 Sequence.AddConversionSequenceStep(ICS, T2);
3702 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003703 Sequence.AddDerivedToBaseCastStep(
3704 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003705 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003706 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003707 else if (NewObjCConversion)
3708 Sequence.AddObjCObjectConversionStep(
3709 S.Context.getQualifiedType(T1,
3710 T2.getNonReferenceType().getQualifiers()));
3711
Douglas Gregor20093b42009-12-09 23:02:17 +00003712 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003713 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003714
Douglas Gregor20093b42009-12-09 23:02:17 +00003715 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3716 return OR_Success;
3717}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003718
Richard Smith83da2e72011-10-19 16:55:56 +00003719static void CheckCXX98CompatAccessibleCopy(Sema &S,
3720 const InitializedEntity &Entity,
3721 Expr *CurInitExpr);
3722
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3724static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003725 const InitializedEntity &Entity,
3726 const InitializationKind &Kind,
3727 Expr *Initializer,
3728 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003729 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003730 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003731 Qualifiers T1Quals;
3732 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003733 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003734 Qualifiers T2Quals;
3735 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003736
Douglas Gregor20093b42009-12-09 23:02:17 +00003737 // If the initializer is the address of an overloaded function, try
3738 // to resolve the overloaded function. If all goes well, T2 is the
3739 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003740 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3741 T1, Sequence))
3742 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003743
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003744 // Delegate everything else to a subfunction.
3745 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3746 T1Quals, cv2T2, T2, T2Quals, Sequence);
3747}
3748
Jordan Rose1fd1e282013-04-11 00:58:58 +00003749/// Converts the target of reference initialization so that it has the
3750/// appropriate qualifiers and value kind.
3751///
3752/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3753/// \code
3754/// int x;
3755/// const int &r = x;
3756/// \endcode
3757///
3758/// In this case the reference is binding to a bitfield lvalue, which isn't
3759/// valid. Perform a load to create a lifetime-extended temporary instead.
3760/// \code
3761/// const int &r = someStruct.bitfield;
3762/// \endcode
3763static ExprValueKind
3764convertQualifiersAndValueKindIfNecessary(Sema &S,
3765 InitializationSequence &Sequence,
3766 Expr *Initializer,
3767 QualType cv1T1,
3768 Qualifiers T1Quals,
3769 Qualifiers T2Quals,
3770 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003771 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003772 Initializer->refersToVectorElement();
3773
3774 if (IsNonAddressableType) {
3775 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3776 // lvalue reference to a non-volatile const type, or the reference shall be
3777 // an rvalue reference.
3778 //
3779 // If not, we can't make a temporary and bind to that. Give up and allow the
3780 // error to be diagnosed later.
3781 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3782 assert(Initializer->isGLValue());
3783 return Initializer->getValueKind();
3784 }
3785
3786 // Force a load so we can materialize a temporary.
3787 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3788 return VK_RValue;
3789 }
3790
3791 if (T1Quals != T2Quals) {
3792 Sequence.AddQualificationConversionStep(cv1T1,
3793 Initializer->getValueKind());
3794 }
3795
3796 return Initializer->getValueKind();
3797}
3798
3799
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003800/// \brief Reference initialization without resolving overloaded functions.
3801static void TryReferenceInitializationCore(Sema &S,
3802 const InitializedEntity &Entity,
3803 const InitializationKind &Kind,
3804 Expr *Initializer,
3805 QualType cv1T1, QualType T1,
3806 Qualifiers T1Quals,
3807 QualType cv2T2, QualType T2,
3808 Qualifiers T2Quals,
3809 InitializationSequence &Sequence) {
3810 QualType DestType = Entity.getType();
3811 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003812 // Compute some basic properties of the types and the initializer.
3813 bool isLValueRef = DestType->isLValueReferenceType();
3814 bool isRValueRef = !isLValueRef;
3815 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003816 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003817 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003818 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003819 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003820 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003821 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003822
Douglas Gregor20093b42009-12-09 23:02:17 +00003823 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003824 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003825 // "cv2 T2" as follows:
3826 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003828 // expression
Richard Smith867521c2013-09-21 21:23:47 +00003829 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redl4680bf22010-06-30 18:13:39 +00003830 // there are no function rvalues in C++, rvalue refs to functions are treated
3831 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003832 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003833 bool T1Function = T1->isFunctionType();
3834 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003836 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003837 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003838 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003839 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003840 // reference-compatible with "cv2 T2," or
3841 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003843 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003844 // can occur. However, we do pay attention to whether it is a bit-field
3845 // to decide whether we're actually binding to a temporary created from
3846 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003847 if (DerivedToBase)
3848 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003849 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003850 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003851 else if (ObjCConversion)
3852 Sequence.AddObjCObjectConversionStep(
3853 S.Context.getQualifiedType(T1, T2Quals));
3854
Jordan Rose1fd1e282013-04-11 00:58:58 +00003855 ExprValueKind ValueKind =
3856 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3857 cv1T1, T1Quals, T2Quals,
3858 isLValueRef);
3859 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003860 return;
3861 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003862
3863 // - has a class type (i.e., T2 is a class type), where T1 is not
3864 // reference-related to T2, and can be implicitly converted to an
3865 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3866 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003867 // applicable conversion functions (13.3.1.6) and choosing the best
3868 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003869 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith867521c2013-09-21 21:23:47 +00003870 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003871 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3872 (isLValueRef || InitCategory.isRValue())) {
Richard Smith867521c2013-09-21 21:23:47 +00003873 ConvOvlResult = TryRefInitWithConversionFunction(
3874 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00003875 if (ConvOvlResult == OR_Success)
3876 return;
Richard Smith867521c2013-09-21 21:23:47 +00003877 if (ConvOvlResult != OR_No_Viable_Function)
John McCall1d318332010-01-12 00:44:57 +00003878 Sequence.SetOverloadFailure(
Richard Smith867521c2013-09-21 21:23:47 +00003879 InitializationSequence::FK_ReferenceInitOverloadFailed,
3880 ConvOvlResult);
Douglas Gregor20093b42009-12-09 23:02:17 +00003881 }
3882 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003883
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003884 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003885 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003886 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003887 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003888 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3889 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3890 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003891 Sequence.SetOverloadFailure(
3892 InitializationSequence::FK_ReferenceInitOverloadFailed,
3893 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003894 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003895 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003896 ? (RefRelationship == Sema::Ref_Related
3897 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3898 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3899 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003900
Douglas Gregor20093b42009-12-09 23:02:17 +00003901 return;
3902 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003903
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003904 // - If the initializer expression
3905 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3906 // "cv1 T1" is reference-compatible with "cv2 T2"
3907 // Note: functions are handled below.
3908 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003909 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003910 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003911 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003912 (InitCategory.isXValue() ||
3913 (InitCategory.isPRValue() && T2->isRecordType()) ||
3914 (InitCategory.isPRValue() && T2->isArrayType()))) {
3915 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3916 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003917 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3918 // compiler the freedom to perform a copy here or bind to the
3919 // object, while C++0x requires that we bind directly to the
3920 // object. Hence, we always bind to the object without making an
3921 // extra copy. However, in C++03 requires that we check for the
3922 // presence of a suitable copy constructor:
3923 //
3924 // The constructor that would be used to make the copy shall
3925 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003926 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003927 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003928 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003929 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003930 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003931
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003932 if (DerivedToBase)
3933 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3934 ValueKind);
3935 else if (ObjCConversion)
3936 Sequence.AddObjCObjectConversionStep(
3937 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938
Jordan Rose1fd1e282013-04-11 00:58:58 +00003939 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3940 Initializer, cv1T1,
3941 T1Quals, T2Quals,
3942 isLValueRef);
3943
3944 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003946 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003947
3948 // - has a class type (i.e., T2 is a class type), where T1 is not
3949 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003950 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3951 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith867521c2013-09-21 21:23:47 +00003952 //
3953 // DR1287 removes the "implicitly" here.
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003954 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003955 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith867521c2013-09-21 21:23:47 +00003956 ConvOvlResult = TryRefInitWithConversionFunction(
3957 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00003958 if (ConvOvlResult)
3959 Sequence.SetOverloadFailure(
Richard Smith867521c2013-09-21 21:23:47 +00003960 InitializationSequence::FK_ReferenceInitOverloadFailed,
3961 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003962
Douglas Gregor20093b42009-12-09 23:02:17 +00003963 return;
3964 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003965
Douglas Gregordefa32e2013-03-26 23:59:23 +00003966 if ((RefRelationship == Sema::Ref_Compatible ||
3967 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3968 isRValueRef && InitCategory.isLValue()) {
3969 Sequence.SetFailed(
3970 InitializationSequence::FK_RValueReferenceBindingToLValue);
3971 return;
3972 }
3973
Douglas Gregor20093b42009-12-09 23:02:17 +00003974 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3975 return;
3976 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003977
3978 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003979 // from the initializer expression using the rules for a non-reference
Richard Smith4e47ecb2013-06-13 00:57:57 +00003980 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003981 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003982
John McCall369371c2010-06-04 02:29:22 +00003983 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3984
Richard Smith4e47ecb2013-06-13 00:57:57 +00003985 // FIXME: Why do we use an implicit conversion here rather than trying
3986 // copy-initialization?
John McCallf85e1932011-06-15 23:02:42 +00003987 ImplicitConversionSequence ICS
3988 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith4e47ecb2013-06-13 00:57:57 +00003989 /*SuppressUserConversions=*/false,
3990 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003991 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003992 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3993 /*AllowObjCWritebackConversion=*/false);
3994
3995 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003996 // FIXME: Use the conversion function set stored in ICS to turn
3997 // this into an overloading ambiguity diagnostic. However, we need
3998 // to keep that set as an OverloadCandidateSet rather than as some
3999 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004000 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4001 Sequence.SetOverloadFailure(
4002 InitializationSequence::FK_ReferenceInitOverloadFailed,
4003 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00004004 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4005 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004006 else
4007 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00004008 return;
John McCallf85e1932011-06-15 23:02:42 +00004009 } else {
4010 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00004011 }
4012
4013 // [...] If T1 is reference-related to T2, cv1 must be the
4014 // same cv-qualification as, or greater cv-qualification
4015 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00004016 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4017 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004018 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00004019 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004020 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4021 return;
4022 }
4023
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004024 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00004025 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004026 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00004027 InitCategory.isLValue()) {
4028 Sequence.SetFailed(
4029 InitializationSequence::FK_RValueReferenceBindingToLValue);
4030 return;
4031 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004032
Douglas Gregor20093b42009-12-09 23:02:17 +00004033 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4034 return;
4035}
4036
4037/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004038/// (C++ [dcl.init.string], C99 6.7.8).
4039static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004040 const InitializedEntity &Entity,
4041 const InitializationKind &Kind,
4042 Expr *Initializer,
4043 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004044 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00004045}
4046
Douglas Gregor71d17402009-12-15 00:01:57 +00004047/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004048static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00004049 const InitializedEntity &Entity,
4050 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00004051 InitializationSequence &Sequence,
4052 InitListExpr *InitList) {
4053 assert((!InitList || InitList->getNumInits() == 0) &&
4054 "Shouldn't use value-init for non-empty init lists");
4055
Richard Smith1d0c9a82012-02-14 21:14:13 +00004056 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00004057 //
4058 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00004059 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004060
Douglas Gregor71d17402009-12-15 00:01:57 +00004061 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00004062 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063
Douglas Gregor71d17402009-12-15 00:01:57 +00004064 if (const RecordType *RT = T->getAs<RecordType>()) {
4065 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00004066 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00004067 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00004068 // C++98:
4069 // -- if T is a class type (clause 9) with a user-declared constructor
4070 // (12.1), then the default constructor for T is called (and the
4071 // initialization is ill-formed if T has no accessible default
4072 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00004073 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00004074 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00004075 } else {
4076 // C++11:
4077 // -- if T is a class type (clause 9) with either no default constructor
4078 // (12.1 [class.ctor]) or a default constructor that is user-provided
4079 // or deleted, then the object is default-initialized;
4080 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4081 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00004082 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00004083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004084
Richard Smith1d0c9a82012-02-14 21:14:13 +00004085 // -- if T is a (possibly cv-qualified) non-union class type without a
4086 // user-provided or deleted default constructor, then the object is
4087 // zero-initialized and, if T has a non-trivial default constructor,
4088 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00004089 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4090 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00004091 if (NeedZeroInitialization)
4092 Sequence.AddZeroInitializationStep(Entity.getType());
4093
Richard Smithd5bc8672012-12-08 02:01:17 +00004094 // C++03:
4095 // -- if T is a non-union class type without a user-declared constructor,
4096 // then every non-static data member and base class component of T is
4097 // value-initialized;
4098 // [...] A program that calls for [...] value-initialization of an
4099 // entity of reference type is ill-formed.
4100 //
4101 // C++11 doesn't need this handling, because value-initialization does not
4102 // occur recursively there, and the implicit default constructor is
4103 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00004104 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00004105 ClassDecl->hasUninitializedReferenceMember()) {
4106 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4107 return;
4108 }
4109
Richard Smithf4bb8d02012-07-05 08:39:21 +00004110 // If this is list-value-initialization, pass the empty init list on when
4111 // building the constructor call. This affects the semantics of a few
4112 // things (such as whether an explicit default constructor can be called).
4113 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004114 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00004115 bool InitListSyntax = InitList;
4116
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004117 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4118 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00004119 }
4120 }
4121
Douglas Gregord6542d82009-12-22 15:35:07 +00004122 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00004123}
4124
Douglas Gregor99a2e602009-12-16 01:38:02 +00004125/// \brief Attempt default initialization (C++ [dcl.init]p6).
4126static void TryDefaultInitialization(Sema &S,
4127 const InitializedEntity &Entity,
4128 const InitializationKind &Kind,
4129 InitializationSequence &Sequence) {
4130 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004131
Douglas Gregor99a2e602009-12-16 01:38:02 +00004132 // C++ [dcl.init]p6:
4133 // To default-initialize an object of type T means:
4134 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00004135 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4136
Douglas Gregor99a2e602009-12-16 01:38:02 +00004137 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4138 // constructor for T is called (and the initialization is ill-formed if
4139 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00004140 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00004141 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004142 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004143 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144
Douglas Gregor99a2e602009-12-16 01:38:02 +00004145 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004146
Douglas Gregor99a2e602009-12-16 01:38:02 +00004147 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004148 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00004149 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00004150 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004151 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00004152 return;
4153 }
4154
4155 // If the destination type has a lifetime property, zero-initialize it.
4156 if (DestType.getQualifiers().hasObjCLifetime()) {
4157 Sequence.AddZeroInitializationStep(Entity.getType());
4158 return;
4159 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004160}
4161
Douglas Gregor20093b42009-12-09 23:02:17 +00004162/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4163/// which enumerates all conversion functions and performs overload resolution
4164/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004165static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004166 const InitializedEntity &Entity,
4167 const InitializationKind &Kind,
4168 Expr *Initializer,
Richard Smith13b228d2013-09-21 21:19:19 +00004169 InitializationSequence &Sequence,
4170 bool TopLevelOfInitList) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004171 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004172 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4173 QualType SourceType = Initializer->getType();
4174 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4175 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004176
Douglas Gregor4a520a22009-12-14 17:27:33 +00004177 // Build the candidate set directly in the initialization sequence
4178 // structure, so that it will persist if we fail.
4179 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4180 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004181
Douglas Gregor4a520a22009-12-14 17:27:33 +00004182 // Determine whether we are allowed to call explicit constructors or
4183 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00004184 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004185
Douglas Gregor4a520a22009-12-14 17:27:33 +00004186 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4187 // The type we're converting to is a class type. Enumerate its constructors
4188 // to see if there is a suitable conversion.
4189 CXXRecordDecl *DestRecordDecl
4190 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004191
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004192 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004193 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004194 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004195 // The container holding the constructors can under certain conditions
4196 // be changed while iterating. To be safe we copy the lookup results
4197 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004198 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004199 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004200 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004201 Con != ConEnd; ++Con) {
4202 NamedDecl *D = *Con;
4203 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004204
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004205 // Find the constructor (which may be a template).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004206 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004207 FunctionTemplateDecl *ConstructorTmpl
4208 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004209 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004210 Constructor = cast<CXXConstructorDecl>(
4211 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00004212 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004213 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004214
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004215 if (!Constructor->isInvalidDecl() &&
4216 Constructor->isConvertingConstructor(AllowExplicit)) {
4217 if (ConstructorTmpl)
4218 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004219 /*ExplicitArgs*/ nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004220 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004221 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004222 else
4223 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004224 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004225 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004226 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004227 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004228 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004229 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004230
4231 SourceLocation DeclLoc = Initializer->getLocStart();
4232
Douglas Gregor4a520a22009-12-14 17:27:33 +00004233 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4234 // The type we're converting from is a class type, enumerate its conversion
4235 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004236
Eli Friedman33c2da92009-12-20 22:12:03 +00004237 // We can only enumerate the conversion functions for a complete type; if
4238 // the type isn't complete, simply skip this step.
4239 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4240 CXXRecordDecl *SourceRecordDecl
4241 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004242
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004243 std::pair<CXXRecordDecl::conversion_iterator,
4244 CXXRecordDecl::conversion_iterator>
4245 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4246 for (CXXRecordDecl::conversion_iterator
4247 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00004248 NamedDecl *D = *I;
4249 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4250 if (isa<UsingShadowDecl>(D))
4251 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004252
Eli Friedman33c2da92009-12-20 22:12:03 +00004253 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4254 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00004255 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00004256 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00004257 else
John McCall32daa422010-03-31 01:36:47 +00004258 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004259
Eli Friedman33c2da92009-12-20 22:12:03 +00004260 if (AllowExplicit || !Conv->isExplicit()) {
4261 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00004262 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00004263 ActingDC, Initializer, DestType,
Stephen Hines651f13c2014-04-23 16:59:28 -07004264 CandidateSet, AllowExplicit);
Eli Friedman33c2da92009-12-20 22:12:03 +00004265 else
John McCall9aa472c2010-03-19 07:35:19 +00004266 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Stephen Hines651f13c2014-04-23 16:59:28 -07004267 Initializer, DestType, CandidateSet,
4268 AllowExplicit);
Eli Friedman33c2da92009-12-20 22:12:03 +00004269 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004270 }
4271 }
4272 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004273
4274 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004275 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004276 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004277 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004278 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004279 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004280 Result);
4281 return;
4282 }
John McCall1d318332010-01-12 00:44:57 +00004283
Douglas Gregor4a520a22009-12-14 17:27:33 +00004284 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004285 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004286 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004287
Douglas Gregor4a520a22009-12-14 17:27:33 +00004288 if (isa<CXXConstructorDecl>(Function)) {
4289 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004290 // subsumed by the initialization. Per DR5, the created temporary is of the
4291 // cv-unqualified type of the destination.
4292 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4293 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004294 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004295 return;
4296 }
4297
4298 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004299 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004300 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004301 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004302 // the resulting temporary object (possible to create an object of
4303 // a base class type). That copy is not a separate conversion, so
4304 // we just make a note of the actual destination type (possibly a
4305 // base class of the type returned by the conversion function) and
4306 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004307 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4308 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004309 return;
4310 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004311
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004312 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4313 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004315 // If the conversion following the call to the conversion function
4316 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004317 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4318 Best->FinalConversion.Third) {
4319 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004320 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004321 ICS.Standard = Best->FinalConversion;
Richard Smith13b228d2013-09-21 21:19:19 +00004322 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004323 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004324}
4325
Richard Smith87c29322013-06-20 02:18:31 +00004326/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4327/// a function with a pointer return type contains a 'return false;' statement.
4328/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4329/// code using that header.
4330///
4331/// Work around this by treating 'return false;' as zero-initializing the result
4332/// if it's used in a pointer-returning function in a system header.
4333static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4334 const InitializedEntity &Entity,
4335 const Expr *Init) {
4336 return S.getLangOpts().CPlusPlus11 &&
4337 Entity.getKind() == InitializedEntity::EK_Result &&
4338 Entity.getType()->isPointerType() &&
4339 isa<CXXBoolLiteralExpr>(Init) &&
4340 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4341 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4342}
4343
John McCallf85e1932011-06-15 23:02:42 +00004344/// The non-zero enum values here are indexes into diagnostic alternatives.
4345enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4346
4347/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004348static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004349 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004350 // Skip parens.
4351 e = e->IgnoreParens();
4352
4353 // Skip address-of nodes.
4354 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4355 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004356 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4357 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004358
4359 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004360 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4361 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004362 case CK_Dependent:
4363 case CK_BitCast:
4364 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004365 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004366 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004367
4368 case CK_ArrayToPointerDecay:
4369 return IIK_nonscalar;
4370
4371 case CK_NullToPointer:
4372 return IIK_okay;
4373
4374 default:
4375 break;
4376 }
4377
4378 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004379 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004380 // set isWeakAccess to true, to mean that there will be an implicit
4381 // load which requires a cleanup.
4382 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4383 isWeakAccess = true;
4384
John McCallc03fa492011-06-27 23:59:58 +00004385 if (!isAddressOf) return IIK_nonlocal;
4386
John McCallf4b88a42012-03-10 09:33:50 +00004387 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4388 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004389
4390 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004391
4392 // If we have a conditional operator, check both sides.
4393 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004394 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4395 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004396 return iik;
4397
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004398 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004399
4400 // These are never scalar.
4401 } else if (isa<ArraySubscriptExpr>(e)) {
4402 return IIK_nonscalar;
4403
4404 // Otherwise, it needs to be a null pointer constant.
4405 } else {
4406 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4407 ? IIK_okay : IIK_nonlocal);
4408 }
4409
4410 return IIK_nonlocal;
4411}
4412
4413/// Check whether the given expression is a valid operand for an
4414/// indirect copy/restore.
4415static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4416 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004417 bool isWeakAccess = false;
4418 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4419 // If isWeakAccess to true, there will be an implicit
4420 // load which requires a cleanup.
4421 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4422 S.ExprNeedsCleanups = true;
4423
John McCallf85e1932011-06-15 23:02:42 +00004424 if (iik == IIK_okay) return;
4425
4426 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4427 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4428 << src->getSourceRange();
4429}
4430
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004431/// \brief Determine whether we have compatible array types for the
4432/// purposes of GNU by-copy array initialization.
4433static bool hasCompatibleArrayTypes(ASTContext &Context,
4434 const ArrayType *Dest,
4435 const ArrayType *Source) {
4436 // If the source and destination array types are equivalent, we're
4437 // done.
4438 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4439 return true;
4440
4441 // Make sure that the element types are the same.
4442 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4443 return false;
4444
4445 // The only mismatch we allow is when the destination is an
4446 // incomplete array type and the source is a constant array type.
4447 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4448}
4449
John McCallf85e1932011-06-15 23:02:42 +00004450static bool tryObjCWritebackConversion(Sema &S,
4451 InitializationSequence &Sequence,
4452 const InitializedEntity &Entity,
4453 Expr *Initializer) {
4454 bool ArrayDecay = false;
4455 QualType ArgType = Initializer->getType();
4456 QualType ArgPointee;
4457 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4458 ArrayDecay = true;
4459 ArgPointee = ArgArrayType->getElementType();
4460 ArgType = S.Context.getPointerType(ArgPointee);
4461 }
4462
4463 // Handle write-back conversion.
4464 QualType ConvertedArgType;
4465 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4466 ConvertedArgType))
4467 return false;
4468
4469 // We should copy unless we're passing to an argument explicitly
4470 // marked 'out'.
4471 bool ShouldCopy = true;
4472 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4473 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4474
4475 // Do we need an lvalue conversion?
4476 if (ArrayDecay || Initializer->isGLValue()) {
4477 ImplicitConversionSequence ICS;
4478 ICS.setStandard();
4479 ICS.Standard.setAsIdentityConversion();
4480
4481 QualType ResultType;
4482 if (ArrayDecay) {
4483 ICS.Standard.First = ICK_Array_To_Pointer;
4484 ResultType = S.Context.getPointerType(ArgPointee);
4485 } else {
4486 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4487 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4488 }
4489
4490 Sequence.AddConversionSequenceStep(ICS, ResultType);
4491 }
4492
4493 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4494 return true;
4495}
4496
Guy Benyei21f18c42013-02-07 10:55:47 +00004497static bool TryOCLSamplerInitialization(Sema &S,
4498 InitializationSequence &Sequence,
4499 QualType DestType,
4500 Expr *Initializer) {
4501 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4502 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4503 return false;
4504
4505 Sequence.AddOCLSamplerInitStep(DestType);
4506 return true;
4507}
4508
Guy Benyeie6b9d802013-01-20 12:31:11 +00004509//
4510// OpenCL 1.2 spec, s6.12.10
4511//
4512// The event argument can also be used to associate the
4513// async_work_group_copy with a previous async copy allowing
4514// an event to be shared by multiple async copies; otherwise
4515// event should be zero.
4516//
4517static bool TryOCLZeroEventInitialization(Sema &S,
4518 InitializationSequence &Sequence,
4519 QualType DestType,
4520 Expr *Initializer) {
4521 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4522 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4523 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4524 return false;
4525
4526 Sequence.AddOCLZeroEventStep(DestType);
4527 return true;
4528}
4529
Douglas Gregor20093b42009-12-09 23:02:17 +00004530InitializationSequence::InitializationSequence(Sema &S,
4531 const InitializedEntity &Entity,
4532 const InitializationKind &Kind,
Richard Smith13b228d2013-09-21 21:19:19 +00004533 MultiExprArg Args,
4534 bool TopLevelOfInitList)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004535 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smithb390e492013-09-21 21:55:46 +00004536 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4537}
4538
4539void InitializationSequence::InitializeFrom(Sema &S,
4540 const InitializedEntity &Entity,
4541 const InitializationKind &Kind,
4542 MultiExprArg Args,
4543 bool TopLevelOfInitList) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004544 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004545
John McCall76da55d2013-04-16 07:28:30 +00004546 // Eliminate non-overload placeholder types in the arguments. We
4547 // need to do this before checking whether types are dependent
4548 // because lowering a pseudo-object expression might well give us
4549 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004550 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004551 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4552 // FIXME: should we be doing this here?
4553 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4554 if (result.isInvalid()) {
4555 SetFailed(FK_PlaceholderType);
4556 return;
4557 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004558 Args[I] = result.get();
John McCall76da55d2013-04-16 07:28:30 +00004559 }
4560
Douglas Gregor20093b42009-12-09 23:02:17 +00004561 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004562 // The semantics of initializers are as follows. The destination type is
4563 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004564 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004566 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004567 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004568
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004569 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004570 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004571 SequenceKind = DependentSequence;
4572 return;
4573 }
4574
Sebastian Redl7491c492011-06-05 13:59:11 +00004575 // Almost everything is a normal sequence.
4576 setSequenceKind(NormalSequence);
4577
Douglas Gregor20093b42009-12-09 23:02:17 +00004578 QualType SourceType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004579 Expr *Initializer = nullptr;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004580 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004581 Initializer = Args[0];
Stephen Hines651f13c2014-04-23 16:59:28 -07004582 if (S.getLangOpts().ObjC1) {
4583 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4584 DestType, Initializer->getType(),
4585 Initializer) ||
4586 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4587 Args[0] = Initializer;
4588
4589 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004590 if (!isa<InitListExpr>(Initializer))
4591 SourceType = Initializer->getType();
4592 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004593
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004594 // - If the initializer is a (non-parenthesized) braced-init-list, the
4595 // object is list-initialized (8.5.4).
4596 if (Kind.getKind() != InitializationKind::IK_Direct) {
4597 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4598 TryListInitialization(S, Entity, Kind, InitList, *this);
4599 return;
4600 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004601 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004602
Douglas Gregor20093b42009-12-09 23:02:17 +00004603 // - If the destination type is a reference type, see 8.5.3.
4604 if (DestType->isReferenceType()) {
4605 // C++0x [dcl.init.ref]p1:
4606 // A variable declared to be a T& or T&&, that is, "reference to type T"
4607 // (8.3.2), shall be initialized by an object, or function, of type T or
4608 // by an object that can be converted into a T.
4609 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004610 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004611 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004612 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004613 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004614 return;
4615 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004616
Douglas Gregor20093b42009-12-09 23:02:17 +00004617 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004618 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004619 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004620 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004621 return;
4622 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004623
Douglas Gregor99a2e602009-12-16 01:38:02 +00004624 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004625 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004626 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004627 return;
4628 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004629
John McCallce6c9b72011-02-21 07:22:22 +00004630 // - If the destination type is an array of characters, an array of
4631 // char16_t, an array of char32_t, or an array of wchar_t, and the
4632 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004633 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004634 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004635 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004636 if (Initializer && isa<VariableArrayType>(DestAT)) {
4637 SetFailed(FK_VariableLengthArrayHasInitializer);
4638 return;
4639 }
4640
Hans Wennborg0ff50742013-05-15 11:03:04 +00004641 if (Initializer) {
4642 switch (IsStringInit(Initializer, DestAT, Context)) {
4643 case SIF_None:
4644 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4645 return;
4646 case SIF_NarrowStringIntoWideChar:
4647 SetFailed(FK_NarrowStringIntoWideCharArray);
4648 return;
4649 case SIF_WideStringIntoChar:
4650 SetFailed(FK_WideStringIntoCharArray);
4651 return;
4652 case SIF_IncompatWideStringIntoWideChar:
4653 SetFailed(FK_IncompatWideStringIntoWideChar);
4654 return;
4655 case SIF_Other:
4656 break;
4657 }
John McCallce6c9b72011-02-21 07:22:22 +00004658 }
4659
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004660 // Note: as an GNU C extension, we allow initialization of an
4661 // array from a compound literal that creates an array of the same
4662 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004663 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004664 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4665 Initializer->getType()->isArrayType()) {
4666 const ArrayType *SourceAT
4667 = Context.getAsArrayType(Initializer->getType());
4668 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004669 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004670 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004671 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004672 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004673 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004674 }
Richard Smith0f163e92012-02-15 22:38:09 +00004675 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004676 // Note: as a GNU C++ extension, we allow list-initialization of a
4677 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004678 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004679 Entity.getKind() == InitializedEntity::EK_Member &&
4680 Initializer && isa<InitListExpr>(Initializer)) {
4681 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4682 *this);
4683 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004684 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004685 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004686 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4687 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004688 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004689 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004690
Douglas Gregor20093b42009-12-09 23:02:17 +00004691 return;
4692 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004693
John McCallf85e1932011-06-15 23:02:42 +00004694 // Determine whether we should consider writeback conversions for
4695 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004696 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004697 Entity.isParameterKind();
John McCallf85e1932011-06-15 23:02:42 +00004698
4699 // We're at the end of the line for C: it's either a write-back conversion
4700 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004701 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004702 // If allowed, check whether this is an Objective-C writeback conversion.
4703 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004704 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004705 return;
4706 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004707
4708 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4709 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004710
4711 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4712 return;
4713
John McCallf85e1932011-06-15 23:02:42 +00004714 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004715 AddCAssignmentStep(DestType);
4716 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004717 return;
4718 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004719
David Blaikie4e4d0842012-03-11 07:00:24 +00004720 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004721
Douglas Gregor20093b42009-12-09 23:02:17 +00004722 // - If the destination type is a (possibly cv-qualified) class type:
4723 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004724 // - If the initialization is direct-initialization, or if it is
4725 // copy-initialization where the cv-unqualified version of the
4726 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004727 // class of the destination, constructors are considered. [...]
4728 if (Kind.getKind() == InitializationKind::IK_Direct ||
4729 (Kind.getKind() == InitializationKind::IK_Copy &&
4730 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4731 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004732 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004733 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004734 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004735 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004736 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004737 // used) to a derived class thereof are enumerated as described in
4738 // 13.3.1.4, and the best one is chosen through overload resolution
4739 // (13.3).
4740 else
Richard Smith13b228d2013-09-21 21:19:19 +00004741 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4742 TopLevelOfInitList);
Douglas Gregor20093b42009-12-09 23:02:17 +00004743 return;
4744 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004745
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004746 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004747 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004748 return;
4749 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004750 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004751
4752 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004753 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004754 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith13b228d2013-09-21 21:19:19 +00004755 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4756 TopLevelOfInitList);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004757 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004758 return;
4759 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004760
Douglas Gregor20093b42009-12-09 23:02:17 +00004761 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004762 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004763 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004764 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004765 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004766
4767 ImplicitConversionSequence ICS
4768 = S.TryImplicitConversion(Initializer, Entity.getType(),
4769 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004770 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004771 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004772 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4773 allowObjCWritebackConversion);
4774
4775 if (ICS.isStandard() &&
4776 ICS.Standard.Second == ICK_Writeback_Conversion) {
4777 // Objective-C ARC writeback conversion.
4778
4779 // We should copy unless we're passing to an argument explicitly
4780 // marked 'out'.
4781 bool ShouldCopy = true;
4782 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4783 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4784
4785 // If there was an lvalue adjustment, add it as a separate conversion.
4786 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4787 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4788 ImplicitConversionSequence LvalueICS;
4789 LvalueICS.setStandard();
4790 LvalueICS.Standard.setAsIdentityConversion();
4791 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4792 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004793 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004794 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004795
4796 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004797 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004798 DeclAccessPair dap;
Richard Smith87c29322013-06-20 02:18:31 +00004799 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4800 AddZeroInitializationStep(Entity.getType());
4801 } else if (Initializer->getType() == Context.OverloadTy &&
4802 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4803 false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004804 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004805 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004806 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004807 } else {
Richard Smith13b228d2013-09-21 21:19:19 +00004808 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCall856d3792011-06-16 23:24:51 +00004809
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004810 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004811 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004812}
4813
4814InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004815 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004816 StepEnd = Steps.end();
4817 Step != StepEnd; ++Step)
4818 Step->Destroy();
4819}
4820
4821//===----------------------------------------------------------------------===//
4822// Perform initialization
4823//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004824static Sema::AssignmentAction
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004825getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004826 switch(Entity.getKind()) {
4827 case InitializedEntity::EK_Variable:
4828 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004829 case InitializedEntity::EK_Exception:
4830 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004831 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004832 return Sema::AA_Initializing;
4833
4834 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004835 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004836 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4837 return Sema::AA_Sending;
4838
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004839 return Sema::AA_Passing;
4840
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004841 case InitializedEntity::EK_Parameter_CF_Audited:
4842 if (Entity.getDecl() &&
4843 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4844 return Sema::AA_Sending;
4845
4846 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4847
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004848 case InitializedEntity::EK_Result:
4849 return Sema::AA_Returning;
4850
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004851 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf5200d62013-07-11 19:13:34 +00004852 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004853 // FIXME: Can we tell apart casting vs. converting?
4854 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004855
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004856 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004857 case InitializedEntity::EK_ArrayElement:
4858 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004859 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004860 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004861 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004862 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004863 return Sema::AA_Initializing;
4864 }
4865
David Blaikie7530c032012-01-17 06:56:22 +00004866 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004867}
4868
Richard Smith774d8b42013-01-08 00:08:23 +00004869/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004870/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004871static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004872 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004873 case InitializedEntity::EK_ArrayElement:
4874 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004875 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004876 case InitializedEntity::EK_New:
4877 case InitializedEntity::EK_Variable:
4878 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004879 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004880 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004881 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004882 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004883 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004884 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004885 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004886 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004887
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004888 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004889 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004890 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004891 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004892 return true;
4893 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004894
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004895 llvm_unreachable("missed an InitializedEntity kind?");
4896}
4897
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004898/// \brief Whether the given entity, when initialized with an object
4899/// created for that initialization, requires destruction.
4900static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4901 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004902 case InitializedEntity::EK_Result:
4903 case InitializedEntity::EK_New:
4904 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004905 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004906 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004907 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004908 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004909 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004910 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004911
Richard Smith774d8b42013-01-08 00:08:23 +00004912 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004913 case InitializedEntity::EK_Variable:
4914 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004915 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004916 case InitializedEntity::EK_Temporary:
4917 case InitializedEntity::EK_ArrayElement:
4918 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004919 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004920 case InitializedEntity::EK_RelatedResult:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004921 return true;
4922 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004923
4924 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004925}
4926
Richard Smith83da2e72011-10-19 16:55:56 +00004927/// \brief Look for copy and move constructors and constructor templates, for
4928/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4929static void LookupCopyAndMoveConstructors(Sema &S,
4930 OverloadCandidateSet &CandidateSet,
4931 CXXRecordDecl *Class,
4932 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004933 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004934 // The container holding the constructors can under certain conditions
4935 // be changed while iterating (e.g. because of deserialization).
4936 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004937 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004938 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004939 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4940 NamedDecl *D = *CI;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004941 CXXConstructorDecl *Constructor = nullptr;
Richard Smith83da2e72011-10-19 16:55:56 +00004942
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004943 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004944 // Handle copy/moveconstructors, only.
4945 if (!Constructor || Constructor->isInvalidDecl() ||
4946 !Constructor->isCopyOrMoveConstructor() ||
4947 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4948 continue;
4949
4950 DeclAccessPair FoundDecl
4951 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4952 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004953 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004954 continue;
4955 }
4956
4957 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004958 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004959 if (ConstructorTmpl->isInvalidDecl())
4960 continue;
4961
4962 Constructor = cast<CXXConstructorDecl>(
4963 ConstructorTmpl->getTemplatedDecl());
4964 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4965 continue;
4966
4967 // FIXME: Do we need to limit this to copy-constructor-like
4968 // candidates?
4969 DeclAccessPair FoundDecl
4970 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004971 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004972 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004973 }
4974}
4975
4976/// \brief Get the location at which initialization diagnostics should appear.
4977static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4978 Expr *Initializer) {
4979 switch (Entity.getKind()) {
4980 case InitializedEntity::EK_Result:
4981 return Entity.getReturnLoc();
4982
4983 case InitializedEntity::EK_Exception:
4984 return Entity.getThrowLoc();
4985
4986 case InitializedEntity::EK_Variable:
4987 return Entity.getDecl()->getLocation();
4988
Douglas Gregor47736542012-02-15 16:57:26 +00004989 case InitializedEntity::EK_LambdaCapture:
4990 return Entity.getCaptureLoc();
4991
Richard Smith83da2e72011-10-19 16:55:56 +00004992 case InitializedEntity::EK_ArrayElement:
4993 case InitializedEntity::EK_Member:
4994 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004995 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith83da2e72011-10-19 16:55:56 +00004996 case InitializedEntity::EK_Temporary:
4997 case InitializedEntity::EK_New:
4998 case InitializedEntity::EK_Base:
4999 case InitializedEntity::EK_Delegating:
5000 case InitializedEntity::EK_VectorElement:
5001 case InitializedEntity::EK_ComplexElement:
5002 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00005003 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005004 case InitializedEntity::EK_RelatedResult:
Richard Smith83da2e72011-10-19 16:55:56 +00005005 return Initializer->getLocStart();
5006 }
5007 llvm_unreachable("missed an InitializedEntity kind?");
5008}
5009
Douglas Gregor523d46a2010-04-18 07:40:54 +00005010/// \brief Make a (potentially elidable) temporary copy of the object
5011/// provided by the given initializer by calling the appropriate copy
5012/// constructor.
5013///
5014/// \param S The Sema object used for type-checking.
5015///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00005016/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00005017/// the type of the initializer expression or a superclass thereof.
5018///
James Dennett1dfbd922012-06-14 21:40:34 +00005019/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00005020///
5021/// \param CurInit The initializer expression.
5022///
5023/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5024/// is permitted in C++03 (but not C++0x) when binding a reference to
5025/// an rvalue.
5026///
5027/// \returns An expression that copies the initializer expression into
5028/// a temporary object, or an error expression if a copy could not be
5029/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00005030static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005031 QualType T,
5032 const InitializedEntity &Entity,
5033 ExprResult CurInit,
5034 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005035 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00005036 Expr *CurInitExpr = (Expr *)CurInit.get();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005037 CXXRecordDecl *Class = nullptr;
Douglas Gregor523d46a2010-04-18 07:40:54 +00005038 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00005039 Class = cast<CXXRecordDecl>(Record->getDecl());
5040 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005041 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00005042
Douglas Gregorf5d8f462011-01-21 18:05:27 +00005043 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00005044 // When certain criteria are met, an implementation is allowed to
5045 // omit the copy/move construction of a class object, even if the
5046 // copy/move constructor and/or destructor for the object have
5047 // side effects. [...]
5048 // - when a temporary class object that has not been bound to a
5049 // reference (12.2) would be copied/moved to a class object
5050 // with the same cv-unqualified type, the copy/move operation
5051 // can be omitted by constructing the temporary object
5052 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005053 //
Douglas Gregor2f599792010-04-02 18:24:57 +00005054 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00005055 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005056 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00005057 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00005058 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00005059 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00005060
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005061 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00005062 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005063 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00005064
Douglas Gregorcc15f012011-01-21 19:38:21 +00005065 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00005066 // Only consider constructors and constructor templates. Per
5067 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5068 // is direct-initialization.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005069 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith83da2e72011-10-19 16:55:56 +00005070 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005071
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005072 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5073
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005074 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00005075 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005076 case OR_Success:
5077 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005078
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005079 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00005080 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5081 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5082 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00005083 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005084 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005085 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00005086 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00005087 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005088 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005089
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005090 case OR_Ambiguous:
5091 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00005092 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005093 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005094 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00005095 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005096
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005097 case OR_Deleted:
5098 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00005099 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005100 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00005101 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00005102 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005103 }
5104
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005105 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005106 SmallVector<Expr*, 8> ConstructorArgs;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005107 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00005108
Anders Carlsson9a68a672010-04-21 18:47:17 +00005109 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00005110 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00005111
5112 if (IsExtraneousCopy) {
5113 // If this is a totally extraneous copy for C++03 reference
5114 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00005115 // expression. We don't generate an (elided) copy operation here
5116 // because doing so would require us to pass down a flag to avoid
5117 // infinite recursion, where each step adds another extraneous,
5118 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00005119
Douglas Gregor2559a702010-04-18 07:57:34 +00005120 // Instantiate the default arguments of any extra parameters in
5121 // the selected copy constructor, as if we were going to create a
5122 // proper call to the copy constructor.
5123 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5124 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5125 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005126 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00005127 break;
5128
5129 // Build the default argument expression; we don't actually care
5130 // if this succeeds or not, because this routine will complain
5131 // if there was a problem.
5132 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5133 }
5134
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005135 return CurInitExpr;
Douglas Gregor523d46a2010-04-18 07:40:54 +00005136 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005137
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005138 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00005139 // constructor call (we might have derived-to-base conversions, or
5140 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005141 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005142 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005143
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005144 // Actually perform the constructor call.
5145 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005146 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005147 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005148 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005149 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005150 CXXConstructExpr::CK_Complete,
5151 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005152
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005153 // If we're supposed to bind temporaries, do so.
5154 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005155 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005156 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005157}
Douglas Gregor20093b42009-12-09 23:02:17 +00005158
Richard Smith83da2e72011-10-19 16:55:56 +00005159/// \brief Check whether elidable copy construction for binding a reference to
5160/// a temporary would have succeeded if we were building in C++98 mode, for
5161/// -Wc++98-compat.
5162static void CheckCXX98CompatAccessibleCopy(Sema &S,
5163 const InitializedEntity &Entity,
5164 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00005165 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00005166
5167 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5168 if (!Record)
5169 return;
5170
5171 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005172 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smith83da2e72011-10-19 16:55:56 +00005173 return;
5174
5175 // Find constructors which would have been considered.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005176 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith83da2e72011-10-19 16:55:56 +00005177 LookupCopyAndMoveConstructors(
5178 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5179
5180 // Perform overload resolution.
5181 OverloadCandidateSet::iterator Best;
5182 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5183
5184 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5185 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5186 << CurInitExpr->getSourceRange();
5187
5188 switch (OR) {
5189 case OR_Success:
5190 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00005191 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00005192 // FIXME: Check default arguments as far as that's possible.
5193 break;
5194
5195 case OR_No_Viable_Function:
5196 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005197 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005198 break;
5199
5200 case OR_Ambiguous:
5201 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005202 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005203 break;
5204
5205 case OR_Deleted:
5206 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005207 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00005208 break;
5209 }
5210}
5211
Douglas Gregora41a8c52010-04-22 00:20:18 +00005212void InitializationSequence::PrintInitLocationNote(Sema &S,
5213 const InitializedEntity &Entity) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005214 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregora41a8c52010-04-22 00:20:18 +00005215 if (Entity.getDecl()->getLocation().isInvalid())
5216 return;
5217
5218 if (Entity.getDecl()->getDeclName())
5219 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5220 << Entity.getDecl()->getDeclName();
5221 else
5222 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5223 }
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005224 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5225 Entity.getMethodDecl())
5226 S.Diag(Entity.getMethodDecl()->getLocation(),
5227 diag::note_method_return_type_change)
5228 << Entity.getMethodDecl()->getDeclName();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005229}
5230
Sebastian Redl3b802322011-07-14 19:07:55 +00005231static bool isReferenceBinding(const InitializationSequence::Step &s) {
5232 return s.Kind == InitializationSequence::SK_BindReference ||
5233 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5234}
5235
Jordan Rose2624b812013-05-06 16:48:12 +00005236/// Returns true if the parameters describe a constructor initialization of
5237/// an explicit temporary object, e.g. "Point(x, y)".
5238static bool isExplicitTemporary(const InitializedEntity &Entity,
5239 const InitializationKind &Kind,
5240 unsigned NumArgs) {
5241 switch (Entity.getKind()) {
5242 case InitializedEntity::EK_Temporary:
5243 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005244 case InitializedEntity::EK_RelatedResult:
Jordan Rose2624b812013-05-06 16:48:12 +00005245 break;
5246 default:
5247 return false;
5248 }
5249
5250 switch (Kind.getKind()) {
5251 case InitializationKind::IK_DirectList:
5252 return true;
5253 // FIXME: Hack to work around cast weirdness.
5254 case InitializationKind::IK_Direct:
5255 case InitializationKind::IK_Value:
5256 return NumArgs != 1;
5257 default:
5258 return false;
5259 }
5260}
5261
Sebastian Redl10f04a62011-12-22 14:44:04 +00005262static ExprResult
5263PerformConstructorInitialization(Sema &S,
5264 const InitializedEntity &Entity,
5265 const InitializationKind &Kind,
5266 MultiExprArg Args,
5267 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005268 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005269 bool IsListInitialization,
5270 SourceLocation LBraceLoc,
5271 SourceLocation RBraceLoc) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005272 unsigned NumArgs = Args.size();
5273 CXXConstructorDecl *Constructor
5274 = cast<CXXConstructorDecl>(Step.Function.Function);
5275 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5276
5277 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005278 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005279 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5280 ? Kind.getEqualLoc()
5281 : Kind.getLocation();
5282
5283 if (Kind.getKind() == InitializationKind::IK_Default) {
5284 // Force even a trivial, implicit default constructor to be
5285 // semantically checked. We do this explicitly because we don't build
5286 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00005287 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00005288 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00005289 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005290 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5291 }
5292
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005293 ExprResult CurInit((Expr *)nullptr);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005294
Douglas Gregored878af2012-02-24 23:56:31 +00005295 // C++ [over.match.copy]p1:
5296 // - When initializing a temporary to be bound to the first parameter
5297 // of a constructor that takes a reference to possibly cv-qualified
5298 // T as its first argument, called with a single argument in the
5299 // context of direct-initialization, explicit conversion functions
5300 // are also considered.
5301 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5302 Args.size() == 1 &&
5303 Constructor->isCopyOrMoveConstructor();
5304
Sebastian Redl10f04a62011-12-22 14:44:04 +00005305 // Determine the arguments required to actually perform the constructor
5306 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005307 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00005308 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00005309 AllowExplicitConv,
5310 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005311 return ExprError();
5312
5313
Jordan Rose2624b812013-05-06 16:48:12 +00005314 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005315 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00005316 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005317 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5318 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005319
5320 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5321 if (!TSInfo)
5322 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella1245a542013-09-07 05:49:53 +00005323 SourceRange ParenOrBraceRange =
5324 (Kind.getKind() == InitializationKind::IK_DirectList)
5325 ? SourceRange(LBraceLoc, RBraceLoc)
5326 : Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005327
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005328 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5329 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5330 HadMultipleCandidates, IsListInitialization,
5331 ConstructorInitRequiresZeroInit);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005332 } else {
5333 CXXConstructExpr::ConstructionKind ConstructKind =
5334 CXXConstructExpr::CK_Complete;
5335
5336 if (Entity.getKind() == InitializedEntity::EK_Base) {
5337 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5338 CXXConstructExpr::CK_VirtualBase :
5339 CXXConstructExpr::CK_NonVirtualBase;
5340 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5341 ConstructKind = CXXConstructExpr::CK_Delegating;
5342 }
5343
Stephen Hines651f13c2014-04-23 16:59:28 -07005344 // Only get the parenthesis or brace range if it is a list initialization or
5345 // direct construction.
5346 SourceRange ParenOrBraceRange;
5347 if (IsListInitialization)
5348 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5349 else if (Kind.getKind() == InitializationKind::IK_Direct)
5350 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005351
5352 // If the entity allows NRVO, mark the construction as elidable
5353 // unconditionally.
5354 if (Entity.allowsNRVO())
5355 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5356 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005357 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005358 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005359 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005360 ConstructorInitRequiresZeroInit,
5361 ConstructKind,
Stephen Hines651f13c2014-04-23 16:59:28 -07005362 ParenOrBraceRange);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005363 else
5364 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5365 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005366 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005367 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005368 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005369 ConstructorInitRequiresZeroInit,
5370 ConstructKind,
Stephen Hines651f13c2014-04-23 16:59:28 -07005371 ParenOrBraceRange);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005372 }
5373 if (CurInit.isInvalid())
5374 return ExprError();
5375
5376 // Only check access if all of that succeeded.
5377 S.CheckConstructorAccess(Loc, Constructor, Entity,
5378 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005379 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5380 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005381
5382 if (shouldBindAsTemporary(Entity))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005383 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redl10f04a62011-12-22 14:44:04 +00005384
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005385 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005386}
5387
Richard Smith36d02af2012-06-04 22:27:30 +00005388/// Determine whether the specified InitializedEntity definitely has a lifetime
5389/// longer than the current full-expression. Conservatively returns false if
5390/// it's unclear.
5391static bool
5392InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5393 const InitializedEntity *Top = &Entity;
5394 while (Top->getParent())
5395 Top = Top->getParent();
5396
5397 switch (Top->getKind()) {
5398 case InitializedEntity::EK_Variable:
5399 case InitializedEntity::EK_Result:
5400 case InitializedEntity::EK_Exception:
5401 case InitializedEntity::EK_Member:
5402 case InitializedEntity::EK_New:
5403 case InitializedEntity::EK_Base:
5404 case InitializedEntity::EK_Delegating:
5405 return true;
5406
5407 case InitializedEntity::EK_ArrayElement:
5408 case InitializedEntity::EK_VectorElement:
5409 case InitializedEntity::EK_BlockElement:
5410 case InitializedEntity::EK_ComplexElement:
5411 // Could not determine what the full initialization is. Assume it might not
5412 // outlive the full-expression.
5413 return false;
5414
5415 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005416 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith36d02af2012-06-04 22:27:30 +00005417 case InitializedEntity::EK_Temporary:
5418 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005419 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005420 case InitializedEntity::EK_RelatedResult:
Richard Smith36d02af2012-06-04 22:27:30 +00005421 // The entity being initialized might not outlive the full-expression.
5422 return false;
5423 }
5424
5425 llvm_unreachable("unknown entity kind");
5426}
5427
Richard Smith211c8dd2013-06-05 00:46:14 +00005428/// Determine the declaration which an initialized entity ultimately refers to,
5429/// for the purpose of lifetime-extending a temporary bound to a reference in
5430/// the initialization of \p Entity.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005431static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5432 const InitializedEntity *Entity,
5433 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005434 // C++11 [class.temporary]p5:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005435 switch (Entity->getKind()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005436 case InitializedEntity::EK_Variable:
5437 // The temporary [...] persists for the lifetime of the reference
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005438 return Entity;
Richard Smith211c8dd2013-06-05 00:46:14 +00005439
5440 case InitializedEntity::EK_Member:
5441 // For subobjects, we look at the complete object.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005442 if (Entity->getParent())
5443 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5444 Entity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005445
5446 // except:
5447 // -- A temporary bound to a reference member in a constructor's
5448 // ctor-initializer persists until the constructor exits.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005449 return Entity;
Richard Smith211c8dd2013-06-05 00:46:14 +00005450
5451 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005452 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith211c8dd2013-06-05 00:46:14 +00005453 // -- A temporary bound to a reference parameter in a function call
5454 // persists until the completion of the full-expression containing
5455 // the call.
5456 case InitializedEntity::EK_Result:
5457 // -- The lifetime of a temporary bound to the returned value in a
5458 // function return statement is not extended; the temporary is
5459 // destroyed at the end of the full-expression in the return statement.
5460 case InitializedEntity::EK_New:
5461 // -- A temporary bound to a reference in a new-initializer persists
5462 // until the completion of the full-expression containing the
5463 // new-initializer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005464 return nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00005465
5466 case InitializedEntity::EK_Temporary:
5467 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005468 case InitializedEntity::EK_RelatedResult:
Richard Smith211c8dd2013-06-05 00:46:14 +00005469 // We don't yet know the storage duration of the surrounding temporary.
5470 // Assume it's got full-expression duration for now, it will patch up our
5471 // storage duration if that's not correct.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005472 return nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00005473
5474 case InitializedEntity::EK_ArrayElement:
5475 // For subobjects, we look at the complete object.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005476 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5477 FallbackDecl);
Richard Smith211c8dd2013-06-05 00:46:14 +00005478
5479 case InitializedEntity::EK_Base:
5480 case InitializedEntity::EK_Delegating:
5481 // We can reach this case for aggregate initialization in a constructor:
5482 // struct A { int &&r; };
5483 // struct B : A { B() : A{0} {} };
5484 // In this case, use the innermost field decl as the context.
5485 return FallbackDecl;
5486
5487 case InitializedEntity::EK_BlockElement:
5488 case InitializedEntity::EK_LambdaCapture:
5489 case InitializedEntity::EK_Exception:
5490 case InitializedEntity::EK_VectorElement:
5491 case InitializedEntity::EK_ComplexElement:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005492 return nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00005493 }
Benjamin Kramer6f773e82013-06-05 15:37:50 +00005494 llvm_unreachable("unknown entity kind");
Richard Smith211c8dd2013-06-05 00:46:14 +00005495}
5496
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005497static void performLifetimeExtension(Expr *Init,
5498 const InitializedEntity *ExtendingEntity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005499
5500/// Update a glvalue expression that is used as the initializer of a reference
5501/// to note that its lifetime is extended.
Richard Smithd6b69872013-06-15 00:30:29 +00005502/// \return \c true if any temporary had its lifetime extended.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005503static bool
5504performReferenceExtension(Expr *Init,
5505 const InitializedEntity *ExtendingEntity) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005506 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5507 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5508 // This is just redundant braces around an initializer. Step over it.
5509 Init = ILE->getInit(0);
5510 }
5511 }
5512
Richard Smithd6b69872013-06-15 00:30:29 +00005513 // Walk past any constructs which we can lifetime-extend across.
5514 Expr *Old;
5515 do {
5516 Old = Init;
5517
5518 // Step over any subobject adjustments; we may have a materialized
5519 // temporary inside them.
5520 SmallVector<const Expr *, 2> CommaLHSs;
5521 SmallVector<SubobjectAdjustment, 2> Adjustments;
5522 Init = const_cast<Expr *>(
5523 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5524
5525 // Per current approach for DR1376, look through casts to reference type
5526 // when performing lifetime extension.
5527 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5528 if (CE->getSubExpr()->isGLValue())
5529 Init = CE->getSubExpr();
5530
5531 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5532 // It's unclear if binding a reference to that xvalue extends the array
5533 // temporary.
5534 } while (Init != Old);
5535
Richard Smith211c8dd2013-06-05 00:46:14 +00005536 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5537 // Update the storage duration of the materialized temporary.
5538 // FIXME: Rebuild the expression instead of mutating it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005539 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5540 ExtendingEntity->allocateManglingNumber());
5541 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smithd6b69872013-06-15 00:30:29 +00005542 return true;
Richard Smith211c8dd2013-06-05 00:46:14 +00005543 }
Richard Smithd6b69872013-06-15 00:30:29 +00005544
5545 return false;
Richard Smith211c8dd2013-06-05 00:46:14 +00005546}
5547
5548/// Update a prvalue expression that is going to be materialized as a
5549/// lifetime-extended temporary.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005550static void performLifetimeExtension(Expr *Init,
5551 const InitializedEntity *ExtendingEntity) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005552 // Dig out the expression which constructs the extended temporary.
5553 SmallVector<const Expr *, 2> CommaLHSs;
5554 SmallVector<SubobjectAdjustment, 2> Adjustments;
5555 Init = const_cast<Expr *>(
5556 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5557
Richard Smith8a07cd32013-06-12 20:42:33 +00005558 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5559 Init = BTE->getSubExpr();
5560
Richard Smith7c3e6152013-06-12 22:31:48 +00005561 if (CXXStdInitializerListExpr *ILE =
Richard Smithd6b69872013-06-15 00:30:29 +00005562 dyn_cast<CXXStdInitializerListExpr>(Init)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005563 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smithd6b69872013-06-15 00:30:29 +00005564 return;
5565 }
Richard Smith7c3e6152013-06-12 22:31:48 +00005566
Richard Smith211c8dd2013-06-05 00:46:14 +00005567 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith7c3e6152013-06-12 22:31:48 +00005568 if (ILE->getType()->isArrayType()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005569 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005570 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005571 return;
5572 }
5573
Richard Smith7c3e6152013-06-12 22:31:48 +00005574 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005575 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5576
5577 // If we lifetime-extend a braced initializer which is initializing an
5578 // aggregate, and that aggregate contains reference members which are
5579 // bound to temporaries, those temporaries are also lifetime-extended.
5580 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5581 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005582 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005583 else {
5584 unsigned Index = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07005585 for (const auto *I : RD->fields()) {
Richard Smith3c3af142013-07-01 06:08:20 +00005586 if (Index >= ILE->getNumInits())
5587 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005588 if (I->isUnnamedBitfield())
5589 continue;
Richard Smith5771aab2013-06-27 22:54:33 +00005590 Expr *SubInit = ILE->getInit(Index);
Richard Smith211c8dd2013-06-05 00:46:14 +00005591 if (I->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005592 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith5771aab2013-06-27 22:54:33 +00005593 else if (isa<InitListExpr>(SubInit) ||
5594 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smith211c8dd2013-06-05 00:46:14 +00005595 // This may be either aggregate-initialization of a member or
5596 // initialization of a std::initializer_list object. Either way,
5597 // we should recursively lifetime-extend that initializer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005598 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005599 ++Index;
5600 }
5601 }
5602 }
5603 }
5604}
5605
Richard Smith7c3e6152013-06-12 22:31:48 +00005606static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5607 const Expr *Init, bool IsInitializerList,
5608 const ValueDecl *ExtendingDecl) {
5609 // Warn if a field lifetime-extends a temporary.
5610 if (isa<FieldDecl>(ExtendingDecl)) {
5611 if (IsInitializerList) {
5612 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5613 << /*at end of constructor*/true;
5614 return;
5615 }
5616
5617 bool IsSubobjectMember = false;
5618 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5619 Ent = Ent->getParent()) {
5620 if (Ent->getKind() != InitializedEntity::EK_Base) {
5621 IsSubobjectMember = true;
5622 break;
5623 }
5624 }
5625 S.Diag(Init->getExprLoc(),
5626 diag::warn_bind_ref_member_to_temporary)
5627 << ExtendingDecl << Init->getSourceRange()
5628 << IsSubobjectMember << IsInitializerList;
5629 if (IsSubobjectMember)
5630 S.Diag(ExtendingDecl->getLocation(),
5631 diag::note_ref_subobject_of_member_declared_here);
5632 else
5633 S.Diag(ExtendingDecl->getLocation(),
5634 diag::note_ref_or_ptr_member_declared_here)
5635 << /*is pointer*/false;
5636 }
5637}
5638
Richard Smith13b228d2013-09-21 21:19:19 +00005639static void DiagnoseNarrowingInInitList(Sema &S,
5640 const ImplicitConversionSequence &ICS,
5641 QualType PreNarrowingType,
5642 QualType EntityType,
5643 const Expr *PostInit);
5644
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005645ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005646InitializationSequence::Perform(Sema &S,
5647 const InitializedEntity &Entity,
5648 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005649 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005650 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005651 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005652 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005653 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005654 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005655
Sebastian Redl7491c492011-06-05 13:59:11 +00005656 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005657 // If the declaration is a non-dependent, incomplete array type
5658 // that has an initializer, then its type will be completed once
5659 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005660 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005661 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005662 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005663 if (const IncompleteArrayType *ArrayT
5664 = S.Context.getAsIncompleteArrayType(DeclType)) {
5665 // FIXME: We don't currently have the ability to accurately
5666 // compute the length of an initializer list without
5667 // performing full type-checking of the initializer list
5668 // (since we have to determine where braces are implicitly
5669 // introduced and such). So, we fall back to making the array
5670 // type a dependently-sized array type with no specified
5671 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005672 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005673 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005674
Douglas Gregord87b61f2009-12-10 17:56:55 +00005675 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005676 if (DeclaratorDecl *DD = Entity.getDecl()) {
5677 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5678 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005679 if (IncompleteArrayTypeLoc ArrayLoc =
5680 TL.getAs<IncompleteArrayTypeLoc>())
5681 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005682 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005683 }
5684
5685 *ResultType
5686 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005687 /*NumElts=*/nullptr,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005688 ArrayT->getSizeModifier(),
5689 ArrayT->getIndexTypeCVRQualifiers(),
5690 Brackets);
5691 }
5692
5693 }
5694 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005695 if (Kind.getKind() == InitializationKind::IK_Direct &&
5696 !Kind.isExplicitCast()) {
5697 // Rebuild the ParenListExpr.
5698 SourceRange ParenRange = Kind.getParenRange();
5699 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005700 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005701 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005702 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005703 Kind.isExplicitCast() ||
5704 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005705 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005706 }
5707
Sebastian Redl7491c492011-06-05 13:59:11 +00005708 // No steps means no initialization.
5709 if (Steps.empty())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005710 return ExprResult((Expr *)nullptr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005711
Richard Smith80ad52f2013-01-02 11:42:31 +00005712 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005713 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005714 !Entity.isParameterKind()) {
Richard Smith03544fc2012-04-19 06:58:00 +00005715 // Produce a C++98 compatibility warning if we are initializing a reference
5716 // from an initializer list. For parameters, we produce a better warning
5717 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005718 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005719 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5720 << Init->getSourceRange();
5721 }
5722
Richard Smith36d02af2012-06-04 22:27:30 +00005723 // Diagnose cases where we initialize a pointer to an array temporary, and the
5724 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005725 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005726 Entity.getType()->isPointerType() &&
5727 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005728 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005729 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5730 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5731 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5732 << Init->getSourceRange();
5733 }
5734
Douglas Gregord6542d82009-12-22 15:35:07 +00005735 QualType DestType = Entity.getType().getNonReferenceType();
5736 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005737 // the same as Entity.getDecl()->getType() in cases involving type merging,
5738 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005739 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005740 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005741 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005742
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005743 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005744
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005745 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005746 // grab the only argument out the Args and place it into the "current"
5747 // initializer.
5748 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005749 case SK_ResolveAddressOfOverloadedFunction:
5750 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005751 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005752 case SK_CastDerivedToBaseLValue:
5753 case SK_BindReference:
5754 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005755 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005756 case SK_UserConversion:
5757 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005758 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005759 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005760 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005761 case SK_ConversionSequence:
Richard Smith13b228d2013-09-21 21:19:19 +00005762 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005763 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005764 case SK_UnwrapInitList:
5765 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005766 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005767 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005768 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005769 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005770 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005771 case SK_PassByIndirectCopyRestore:
5772 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005773 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005774 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005775 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005776 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005777 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005778 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005779 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005780 break;
John McCallf6a16482010-12-04 03:47:34 +00005781 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005782
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005783 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005784 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005785 case SK_ZeroInitialization:
5786 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005787 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005788
5789 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005790 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005791 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005792 for (step_iterator Step = step_begin(), StepEnd = step_end();
5793 Step != StepEnd; ++Step) {
5794 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005795 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005796
John Wiegley429bb272011-04-08 18:41:53 +00005797 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005798
Douglas Gregor20093b42009-12-09 23:02:17 +00005799 switch (Step->Kind) {
5800 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005801 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005802 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005803 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005804 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5805 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005806 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005807 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005808 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005809 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005810
Douglas Gregor20093b42009-12-09 23:02:17 +00005811 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005812 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005813 case SK_CastDerivedToBaseLValue: {
5814 // We have a derived-to-base cast that produces either an rvalue or an
5815 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005816
John McCallf871d0c2010-08-07 06:22:56 +00005817 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005818
Douglas Gregor20093b42009-12-09 23:02:17 +00005819 // Casts to inaccessible base classes are allowed with C-style casts.
5820 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5821 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005822 CurInit.get()->getLocStart(),
5823 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005824 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005825 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005826
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005827 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5828 QualType T = SourceType;
5829 if (const PointerType *Pointer = T->getAs<PointerType>())
5830 T = Pointer->getPointeeType();
5831 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005832 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005833 cast<CXXRecordDecl>(RecordTy->getDecl()));
5834 }
5835
John McCall5baba9d2010-08-25 10:28:54 +00005836 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005837 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005838 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005839 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005840 VK_XValue :
5841 VK_RValue);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005842 CurInit =
5843 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5844 CurInit.get(), &BasePath, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005845 break;
5846 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005847
Douglas Gregor20093b42009-12-09 23:02:17 +00005848 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005849 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5850 if (CurInit.get()->refersToBitField()) {
5851 // We don't necessarily have an unambiguous source bit-field.
5852 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005853 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005854 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005855 << (BitField ? BitField->getDeclName() : DeclarationName())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005856 << (BitField != nullptr)
John Wiegley429bb272011-04-08 18:41:53 +00005857 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005858 if (BitField)
5859 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5860
John McCallf312b1e2010-08-26 23:41:50 +00005861 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005862 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005863
John Wiegley429bb272011-04-08 18:41:53 +00005864 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005865 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005866 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5867 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005868 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005869 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005870 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005871 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005872
Douglas Gregor20093b42009-12-09 23:02:17 +00005873 // Reference binding does not have any corresponding ASTs.
5874
5875 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005876 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005877 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005878
Richard Smithd6b69872013-06-15 00:30:29 +00005879 // Even though we didn't materialize a temporary, the binding may still
5880 // extend the lifetime of a temporary. This happens if we bind a reference
5881 // to the result of a cast to reference type.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005882 if (const InitializedEntity *ExtendingEntity =
5883 getEntityForTemporaryLifetimeExtension(&Entity))
5884 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5885 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5886 /*IsInitializerList=*/false,
5887 ExtendingEntity->getDecl());
Richard Smithd6b69872013-06-15 00:30:29 +00005888
Douglas Gregor20093b42009-12-09 23:02:17 +00005889 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005890
Richard Smith211c8dd2013-06-05 00:46:14 +00005891 case SK_BindReferenceToTemporary: {
Jordan Rose1fd1e282013-04-11 00:58:58 +00005892 // Make sure the "temporary" is actually an rvalue.
5893 assert(CurInit.get()->isRValue() && "not a temporary");
5894
Douglas Gregor20093b42009-12-09 23:02:17 +00005895 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005896 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005897 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005898
Douglas Gregor03e80032011-06-21 17:03:29 +00005899 // Materialize the temporary into memory.
Richard Smith8a07cd32013-06-12 20:42:33 +00005900 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smith211c8dd2013-06-05 00:46:14 +00005901 Entity.getType().getNonReferenceType(), CurInit.get(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005902 Entity.getType()->isLValueReferenceType());
5903
5904 // Maybe lifetime-extend the temporary's subobjects to match the
5905 // entity's lifetime.
5906 if (const InitializedEntity *ExtendingEntity =
5907 getEntityForTemporaryLifetimeExtension(&Entity))
5908 if (performReferenceExtension(MTE, ExtendingEntity))
5909 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5910 ExtendingEntity->getDecl());
Douglas Gregord7b23162011-06-22 16:12:01 +00005911
5912 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith8a07cd32013-06-12 20:42:33 +00005913 // need cleanups. Likewise if we're extending this temporary to automatic
5914 // storage duration -- we need to register its cleanup during the
5915 // full-expression's cleanups.
5916 if ((S.getLangOpts().ObjCAutoRefCount &&
5917 MTE->getType()->isObjCLifetimeType()) ||
5918 (MTE->getStorageDuration() == SD_Automatic &&
5919 MTE->getType().isDestructedType()))
Douglas Gregord7b23162011-06-22 16:12:01 +00005920 S.ExprNeedsCleanups = true;
Richard Smith8a07cd32013-06-12 20:42:33 +00005921
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005922 CurInit = MTE;
Douglas Gregor20093b42009-12-09 23:02:17 +00005923 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005925
Douglas Gregor523d46a2010-04-18 07:40:54 +00005926 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005927 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005928 /*IsExtraneousCopy=*/true);
5929 break;
5930
Douglas Gregor20093b42009-12-09 23:02:17 +00005931 case SK_UserConversion: {
5932 // We have a user-defined conversion that invokes either a constructor
5933 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005934 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005935 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005936 FunctionDecl *Fn = Step->Function.Function;
5937 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005938 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005939 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005940 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005941 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005942 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005943 SourceLocation Loc = CurInit.get()->getLocStart();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005944 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005945
Douglas Gregor20093b42009-12-09 23:02:17 +00005946 // Determine the arguments required to actually perform the constructor
5947 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005948 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005949 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005950 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005951 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005952 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005953
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005954 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005955 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005956 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005957 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005958 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005959 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005960 CXXConstructExpr::CK_Complete,
5961 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005962 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005963 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005964
Anders Carlsson9a68a672010-04-21 18:47:17 +00005965 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005966 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005967 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5968 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005969
John McCall2de56d12010-08-25 11:45:40 +00005970 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005971 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5972 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5973 S.IsDerivedFrom(SourceType, Class))
5974 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005975
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005976 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005977 } else {
5978 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005979 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005980 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCall9aa472c2010-03-19 07:35:19 +00005981 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005982 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5983 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005984
5985 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005986 // derived-to-base conversion? I believe the answer is "no", because
5987 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005988 ExprResult CurInitExprRes =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005989 S.PerformObjectArgumentInitialization(CurInit.get(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005990 /*Qualifier=*/nullptr,
John Wiegley429bb272011-04-08 18:41:53 +00005991 FoundFn, Conversion);
5992 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005993 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005994 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005995
Douglas Gregor20093b42009-12-09 23:02:17 +00005996 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005997 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5998 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005999 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00006000 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006001
John McCall2de56d12010-08-25 11:45:40 +00006002 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006003
Stephen Hines651f13c2014-04-23 16:59:28 -07006004 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00006005 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006006
Sebastian Redl3b802322011-07-14 19:07:55 +00006007 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00006008 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6009
6010 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00006011 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00006012 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006013 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00006014 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00006015 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00006016 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00006017 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00006018 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6019 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00006020 }
6021 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006022
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006023 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6024 CastKind, CurInit.get(), nullptr,
6025 CurInit.get()->getValueKind());
Abramo Bagnara960809e2011-11-16 22:46:05 +00006026 if (MaybeBindToTemp)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006027 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00006028 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00006029 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006030 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00006031 break;
6032 }
Sebastian Redl906082e2010-07-20 04:20:21 +00006033
Douglas Gregor20093b42009-12-09 23:02:17 +00006034 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00006035 case SK_QualificationConversionXValue:
6036 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00006037 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00006038 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00006039 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00006040 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00006041 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00006042 VK_XValue :
6043 VK_RValue);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006044 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00006045 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006046 }
6047
Jordan Rose1fd1e282013-04-11 00:58:58 +00006048 case SK_LValueToRValue: {
6049 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006050 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6051 CK_LValueToRValue, CurInit.get(),
6052 /*BasePath=*/nullptr, VK_RValue);
Jordan Rose1fd1e282013-04-11 00:58:58 +00006053 break;
6054 }
6055
Richard Smith13b228d2013-09-21 21:19:19 +00006056 case SK_ConversionSequence:
6057 case SK_ConversionSequenceNoNarrowing: {
6058 Sema::CheckedConversionKind CCK
John McCallf85e1932011-06-15 23:02:42 +00006059 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6060 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00006061 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00006062 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00006063 ExprResult CurInitExprRes =
6064 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00006065 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00006066 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006067 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006068 CurInit = CurInitExprRes;
Richard Smith13b228d2013-09-21 21:19:19 +00006069
6070 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6071 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6072 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6073 CurInit.get());
Douglas Gregor20093b42009-12-09 23:02:17 +00006074 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00006075 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006076
Douglas Gregord87b61f2009-12-10 17:56:55 +00006077 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00006078 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smith7c3e6152013-06-12 22:31:48 +00006079 // If we're not initializing the top-level entity, we need to create an
6080 // InitializeTemporary entity for our target type.
6081 QualType Ty = Step->Type;
6082 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006083 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00006084 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6085 InitListChecker PerformInitList(S, InitEntity,
Richard Smith40cba902013-06-06 11:41:05 +00006086 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006087 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00006088 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00006089
Richard Smith7c3e6152013-06-12 22:31:48 +00006090 // Hack: We must update *ResultType if available in order to set the
6091 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6092 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6093 if (ResultType &&
6094 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006095 if ((*ResultType)->isRValueReferenceType())
6096 Ty = S.Context.getRValueReferenceType(Ty);
6097 else if ((*ResultType)->isLValueReferenceType())
6098 Ty = S.Context.getLValueReferenceType(Ty,
6099 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6100 *ResultType = Ty;
6101 }
6102
6103 InitListExpr *StructuredInitList =
6104 PerformInitList.getFullyStructuredList();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006105 CurInit.get();
Richard Smith802e2262013-02-02 01:13:06 +00006106 CurInit = shouldBindAsTemporary(InitEntity)
6107 ? S.MaybeBindToTemporary(StructuredInitList)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006108 : StructuredInitList;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006109 break;
6110 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006111
Sebastian Redl10f04a62011-12-22 14:44:04 +00006112 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00006113 // When an initializer list is passed for a parameter of type "reference
6114 // to object", we don't get an EK_Temporary entity, but instead an
6115 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00006116 // FIXME: This is a hack. What we really should do is create a user
6117 // conversion step for this case, but this makes it considerably more
6118 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00006119 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6120 Entity.getType().getNonReferenceType());
6121 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00006122 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006123 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00006124 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6125 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00006126 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00006127 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6128 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006129 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00006130 ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00006131 /*IsListInitialization*/ true,
6132 InitList->getLBraceLoc(),
6133 InitList->getRBraceLoc());
Sebastian Redl10f04a62011-12-22 14:44:04 +00006134 break;
6135 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006136
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006137 case SK_UnwrapInitList:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006138 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006139 break;
6140
6141 case SK_RewrapInitList: {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006142 Expr *E = CurInit.get();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006143 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6144 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00006145 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006146 ILE->setSyntacticForm(Syntactic);
6147 ILE->setType(E->getType());
6148 ILE->setValueKind(E->getValueKind());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006149 CurInit = ILE;
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006150 break;
6151 }
6152
Sebastian Redlbac5cf42012-02-19 12:27:56 +00006153 case SK_ConstructorInitialization: {
6154 // When an initializer list is passed for a parameter of type "reference
6155 // to object", we don't get an EK_Temporary entity, but instead an
6156 // EK_Parameter entity with reference type.
6157 // FIXME: This is a hack. What we really should do is create a user
6158 // conversion step for this case, but this makes it considerably more
6159 // complicated. For now, this will do.
6160 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6161 Entity.getType().getNonReferenceType());
6162 bool UseTemporary = Entity.getType()->isReferenceType();
6163 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6164 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006165 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00006166 ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00006167 /*IsListInitialization*/ false,
6168 /*LBraceLoc*/ SourceLocation(),
6169 /*RBraceLoc*/ SourceLocation());
Douglas Gregor51c56d62009-12-14 20:49:26 +00006170 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00006171 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006172
Douglas Gregor71d17402009-12-15 00:01:57 +00006173 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00006174 step_iterator NextStep = Step;
6175 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006176 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00006177 (NextStep->Kind == SK_ConstructorInitialization ||
6178 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00006179 // The need for zero-initialization is recorded directly into
6180 // the call to the object's constructor within the next step.
6181 ConstructorInitRequiresZeroInit = true;
6182 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006183 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00006184 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00006185 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6186 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006187 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00006188 Kind.getRange().getBegin());
6189
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006190 CurInit = new (S.Context) CXXScalarValueInitExpr(
6191 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6192 Kind.getRange().getEnd());
Douglas Gregor16006c92009-12-16 18:50:27 +00006193 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006194 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor16006c92009-12-16 18:50:27 +00006195 }
Douglas Gregor71d17402009-12-15 00:01:57 +00006196 break;
6197 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006198
6199 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00006200 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006201 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006202 Sema::AssignConvertType ConvTy =
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00006203 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6204 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley429bb272011-04-08 18:41:53 +00006205 if (Result.isInvalid())
6206 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006207 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00006208
6209 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006210 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00006211 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006212 Entity.isParameterKind() &&
John Wiegley429bb272011-04-08 18:41:53 +00006213 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00006214 == Sema::Compatible)
6215 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00006216 if (CurInitExprRes.isInvalid())
6217 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006218 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00006219
Douglas Gregora41a8c52010-04-22 00:20:18 +00006220 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006221 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6222 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00006223 CurInit.get(),
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00006224 getAssignmentAction(Entity, true),
Douglas Gregora41a8c52010-04-22 00:20:18 +00006225 &Complained)) {
6226 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00006227 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00006228 } else if (Complained)
6229 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006230 break;
6231 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006232
6233 case SK_StringInit: {
6234 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00006235 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00006236 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006237 break;
6238 }
Douglas Gregor569c3162010-08-07 11:51:51 +00006239
6240 case SK_ObjCObjectConversion:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006241 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00006242 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00006243 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00006244 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006245
6246 case SK_ArrayInit:
6247 // Okay: we checked everything before creating this step. Note that
6248 // this is a GNU extension.
6249 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00006250 << Step->Type << CurInit.get()->getType()
6251 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006252
6253 // If the destination type is an incomplete array type, update the
6254 // type accordingly.
6255 if (ResultType) {
6256 if (const IncompleteArrayType *IncompleteDest
6257 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6258 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00006259 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006260 *ResultType = S.Context.getConstantArrayType(
6261 IncompleteDest->getElementType(),
6262 ConstantSource->getSize(),
6263 ArrayType::Normal, 0);
6264 }
6265 }
6266 }
John McCallf85e1932011-06-15 23:02:42 +00006267 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006268
Richard Smith0f163e92012-02-15 22:38:09 +00006269 case SK_ParenthesizedArrayInit:
6270 // Okay: we checked everything before creating this step. Note that
6271 // this is a GNU extension.
6272 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6273 << CurInit.get()->getSourceRange();
6274 break;
6275
John McCallf85e1932011-06-15 23:02:42 +00006276 case SK_PassByIndirectCopyRestore:
6277 case SK_PassByIndirectRestore:
6278 checkIndirectCopyRestoreSource(S, CurInit.get());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006279 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6280 CurInit.get(), Step->Type,
6281 Step->Kind == SK_PassByIndirectCopyRestore);
John McCallf85e1932011-06-15 23:02:42 +00006282 break;
6283
6284 case SK_ProduceObjCObject:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006285 CurInit =
6286 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6287 CurInit.get(), nullptr, VK_RValue);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006288 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006289
6290 case SK_StdInitializerList: {
Richard Smith7c3e6152013-06-12 22:31:48 +00006291 S.Diag(CurInit.get()->getExprLoc(),
6292 diag::warn_cxx98_compat_initializer_list_init)
6293 << CurInit.get()->getSourceRange();
Sebastian Redl28357452012-03-05 19:35:43 +00006294
Richard Smith7c3e6152013-06-12 22:31:48 +00006295 // Materialize the temporary into memory.
6296 MaterializeTemporaryExpr *MTE = new (S.Context)
6297 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006298 /*BoundToLvalueReference=*/false);
6299
6300 // Maybe lifetime-extend the array temporary's subobjects to match the
6301 // entity's lifetime.
6302 if (const InitializedEntity *ExtendingEntity =
6303 getEntityForTemporaryLifetimeExtension(&Entity))
6304 if (performReferenceExtension(MTE, ExtendingEntity))
6305 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6306 /*IsInitializerList=*/true,
6307 ExtendingEntity->getDecl());
Richard Smith7c3e6152013-06-12 22:31:48 +00006308
6309 // Wrap it in a construction of a std::initializer_list<T>.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006310 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smith7c3e6152013-06-12 22:31:48 +00006311
6312 // Bind the result, in case the library has given initializer_list a
6313 // non-trivial destructor.
6314 if (shouldBindAsTemporary(Entity))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006315 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redl2b916b82012-01-17 22:49:42 +00006316 break;
6317 }
Richard Smith7c3e6152013-06-12 22:31:48 +00006318
Guy Benyei21f18c42013-02-07 10:55:47 +00006319 case SK_OCLSamplerInit: {
6320 assert(Step->Type->isSamplerT() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07006321 "Sampler initialization on non-sampler type.");
Guy Benyei21f18c42013-02-07 10:55:47 +00006322
6323 QualType SourceType = CurInit.get()->getType();
Guy Benyei21f18c42013-02-07 10:55:47 +00006324
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006325 if (Entity.isParameterKind()) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006326 if (!SourceType->isSamplerT())
6327 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6328 << SourceType;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006329 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006330 llvm_unreachable("Invalid EntityKind!");
6331 }
6332
6333 break;
6334 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00006335 case SK_OCLZeroEvent: {
6336 assert(Step->Type->isEventT() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07006337 "Event initialization on non-event type.");
Guy Benyeie6b9d802013-01-20 12:31:11 +00006338
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006339 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyeie6b9d802013-01-20 12:31:11 +00006340 CK_ZeroToOCLEvent,
6341 CurInit.get()->getValueKind());
6342 break;
6343 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006344 }
6345 }
John McCall15d7d122010-11-11 03:21:53 +00006346
6347 // Diagnose non-fatal problems with the completed initialization.
6348 if (Entity.getKind() == InitializedEntity::EK_Member &&
6349 cast<FieldDecl>(Entity.getDecl())->isBitField())
6350 S.CheckBitFieldInitialization(Kind.getLocation(),
6351 cast<FieldDecl>(Entity.getDecl()),
6352 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006353
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006354 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00006355}
6356
Richard Smithd5bc8672012-12-08 02:01:17 +00006357/// Somewhere within T there is an uninitialized reference subobject.
6358/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00006359static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6360 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006361 if (T->isReferenceType()) {
6362 S.Diag(Loc, diag::err_reference_without_init)
6363 << T.getNonReferenceType();
6364 return true;
6365 }
6366
6367 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6368 if (!RD || !RD->hasUninitializedReferenceMember())
6369 return false;
6370
Stephen Hines651f13c2014-04-23 16:59:28 -07006371 for (const auto *FI : RD->fields()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006372 if (FI->isUnnamedBitfield())
6373 continue;
6374
6375 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6376 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6377 return true;
6378 }
6379 }
6380
Stephen Hines651f13c2014-04-23 16:59:28 -07006381 for (const auto &BI : RD->bases()) {
6382 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006383 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6384 return true;
6385 }
6386 }
6387
6388 return false;
6389}
6390
6391
Douglas Gregor20093b42009-12-09 23:02:17 +00006392//===----------------------------------------------------------------------===//
6393// Diagnose initialization failures
6394//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00006395
6396/// Emit notes associated with an initialization that failed due to a
6397/// "simple" conversion failure.
6398static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6399 Expr *op) {
6400 QualType destType = entity.getType();
6401 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6402 op->getType()->isObjCObjectPointerType()) {
6403
6404 // Emit a possible note about the conversion failing because the
6405 // operand is a message send with a related result type.
6406 S.EmitRelatedResultTypeNote(op);
6407
6408 // Emit a possible note about a return failing because we're
6409 // expecting a related result type.
6410 if (entity.getKind() == InitializedEntity::EK_Result)
6411 S.EmitRelatedResultTypeNoteForReturn(destType);
6412 }
6413}
6414
Bill Wendling2ca3db42013-11-22 00:01:44 +00006415static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6416 InitListExpr *InitList) {
6417 QualType DestType = Entity.getType();
6418
6419 QualType E;
6420 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6421 QualType ArrayType = S.Context.getConstantArrayType(
6422 E.withConst(),
6423 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6424 InitList->getNumInits()),
6425 clang::ArrayType::Normal, 0);
6426 InitializedEntity HiddenArray =
6427 InitializedEntity::InitializeTemporary(ArrayType);
6428 return diagnoseListInit(S, HiddenArray, InitList);
6429 }
6430
6431 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6432 /*VerifyOnly=*/false);
6433 assert(DiagnoseInitList.HadError() &&
6434 "Inconsistent init list check result.");
6435}
6436
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006437bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00006438 const InitializedEntity &Entity,
6439 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006440 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00006441 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00006442 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006443
Douglas Gregord6542d82009-12-22 15:35:07 +00006444 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00006445 switch (Failure) {
6446 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006447 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006448 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006449 // Dig out the reference subobject which is uninitialized and diagnose it.
6450 // If this is value-initialization, this could be nested some way within
6451 // the target type.
6452 assert(Kind.getKind() == InitializationKind::IK_Value ||
6453 DestType->isReferenceType());
6454 bool Diagnosed =
6455 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6456 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6457 (void)Diagnosed;
6458 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006459 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006460 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00006461 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006462
Douglas Gregor20093b42009-12-09 23:02:17 +00006463 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00006464 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00006465 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00006466 case FK_ArrayNeedsInitListOrStringLiteral:
6467 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6468 break;
6469 case FK_ArrayNeedsInitListOrWideStringLiteral:
6470 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6471 break;
6472 case FK_NarrowStringIntoWideCharArray:
6473 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6474 break;
6475 case FK_WideStringIntoCharArray:
6476 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6477 break;
6478 case FK_IncompatWideStringIntoWideChar:
6479 S.Diag(Kind.getLocation(),
6480 diag::err_array_init_incompat_wide_string_into_wchar);
6481 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006482 case FK_ArrayTypeMismatch:
6483 case FK_NonConstantArrayInit:
Bill Wendling2ca3db42013-11-22 00:01:44 +00006484 S.Diag(Kind.getLocation(),
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006485 (Failure == FK_ArrayTypeMismatch
6486 ? diag::err_array_init_different_type
6487 : diag::err_array_init_non_constant_array))
6488 << DestType.getNonReferenceType()
6489 << Args[0]->getType()
6490 << Args[0]->getSourceRange();
6491 break;
6492
John McCall73076432012-01-05 00:13:19 +00006493 case FK_VariableLengthArrayHasInitializer:
6494 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6495 << Args[0]->getSourceRange();
6496 break;
6497
John McCall6bb80172010-03-30 21:47:33 +00006498 case FK_AddressOfOverloadFailed: {
6499 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006500 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00006501 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00006502 true,
6503 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00006504 break;
John McCall6bb80172010-03-30 21:47:33 +00006505 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006506
Douglas Gregor20093b42009-12-09 23:02:17 +00006507 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00006508 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00006509 switch (FailedOverloadResult) {
6510 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006511 if (Failure == FK_UserConversionOverloadFailed)
6512 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6513 << Args[0]->getType() << DestType
6514 << Args[0]->getSourceRange();
6515 else
6516 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6517 << DestType << Args[0]->getType()
6518 << Args[0]->getSourceRange();
6519
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006520 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006521 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006522
Douglas Gregor20093b42009-12-09 23:02:17 +00006523 case OR_No_Viable_Function:
Larisse Voufo288f76a2013-06-27 03:36:30 +00006524 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo7419d012013-06-27 01:50:25 +00006525 DestType.getNonReferenceType(),
6526 diag::err_typecheck_nonviable_condition_incomplete,
6527 Args[0]->getType(), Args[0]->getSourceRange()))
6528 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6529 << Args[0]->getType() << Args[0]->getSourceRange()
6530 << DestType.getNonReferenceType();
6531
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006532 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006533 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006534
Douglas Gregor20093b42009-12-09 23:02:17 +00006535 case OR_Deleted: {
6536 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6537 << Args[0]->getType() << DestType.getNonReferenceType()
6538 << Args[0]->getSourceRange();
6539 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006540 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006541 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6542 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00006543 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00006544 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00006545 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006546 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00006547 }
6548 break;
6549 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006550
Douglas Gregor20093b42009-12-09 23:02:17 +00006551 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006552 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00006553 }
6554 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006555
Douglas Gregor20093b42009-12-09 23:02:17 +00006556 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006557 if (isa<InitListExpr>(Args[0])) {
6558 S.Diag(Kind.getLocation(),
6559 diag::err_lvalue_reference_bind_to_initlist)
6560 << DestType.getNonReferenceType().isVolatileQualified()
6561 << DestType.getNonReferenceType()
6562 << Args[0]->getSourceRange();
6563 break;
6564 }
6565 // Intentional fallthrough
6566
Douglas Gregor20093b42009-12-09 23:02:17 +00006567 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006568 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00006569 Failure == FK_NonConstLValueReferenceBindingToTemporary
6570 ? diag::err_lvalue_reference_bind_to_temporary
6571 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00006572 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00006573 << DestType.getNonReferenceType()
6574 << Args[0]->getType()
6575 << Args[0]->getSourceRange();
6576 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006577
Douglas Gregor20093b42009-12-09 23:02:17 +00006578 case FK_RValueReferenceBindingToLValue:
6579 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00006580 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00006581 << Args[0]->getSourceRange();
6582 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006583
Douglas Gregor20093b42009-12-09 23:02:17 +00006584 case FK_ReferenceInitDropsQualifiers:
6585 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6586 << DestType.getNonReferenceType()
6587 << Args[0]->getType()
6588 << Args[0]->getSourceRange();
6589 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006590
Douglas Gregor20093b42009-12-09 23:02:17 +00006591 case FK_ReferenceInitFailed:
6592 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6593 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006594 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006595 << Args[0]->getType()
6596 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006597 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006598 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006599
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006600 case FK_ConversionFailed: {
6601 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006602 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006603 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006604 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006605 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006606 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006607 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006608 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6609 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006610 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006611 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006612 }
John Wiegley429bb272011-04-08 18:41:53 +00006613
6614 case FK_ConversionFromPropertyFailed:
6615 // No-op. This error has already been reported.
6616 break;
6617
Douglas Gregord87b61f2009-12-10 17:56:55 +00006618 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006619 SourceRange R;
6620
6621 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006622 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006623 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006624 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006625 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006626
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006627 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor19311e72010-09-08 21:40:08 +00006628 if (Kind.isCStyleOrFunctionalCast())
6629 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6630 << R;
6631 else
6632 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6633 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006634 break;
6635 }
6636
6637 case FK_ReferenceBindingToInitList:
6638 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6639 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6640 break;
6641
6642 case FK_InitListBadDestinationType:
6643 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6644 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6645 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006646
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006647 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006648 case FK_ConstructorOverloadFailed: {
6649 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006650 if (Args.size())
6651 ArgsRange = SourceRange(Args.front()->getLocStart(),
6652 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006653
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006654 if (Failure == FK_ListConstructorOverloadFailed) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006655 assert(Args.size() == 1 &&
6656 "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006657 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006658 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006659 }
6660
Douglas Gregor51c56d62009-12-14 20:49:26 +00006661 // FIXME: Using "DestType" for the entity we're printing is probably
6662 // bad.
6663 switch (FailedOverloadResult) {
6664 case OR_Ambiguous:
6665 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6666 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006667 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006668 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006669
Douglas Gregor51c56d62009-12-14 20:49:26 +00006670 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006671 if (Kind.getKind() == InitializationKind::IK_Default &&
6672 (Entity.getKind() == InitializedEntity::EK_Base ||
6673 Entity.getKind() == InitializedEntity::EK_Member) &&
6674 isa<CXXConstructorDecl>(S.CurContext)) {
6675 // This is implicit default initialization of a member or
6676 // base within a constructor. If no viable function was
6677 // found, notify the user that she needs to explicitly
6678 // initialize this base/member.
6679 CXXConstructorDecl *Constructor
6680 = cast<CXXConstructorDecl>(S.CurContext);
6681 if (Entity.getKind() == InitializedEntity::EK_Base) {
6682 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006683 << (Constructor->getInheritedConstructor() ? 2 :
6684 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006685 << S.Context.getTypeDeclType(Constructor->getParent())
6686 << /*base=*/0
6687 << Entity.getType();
6688
6689 RecordDecl *BaseDecl
6690 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6691 ->getDecl();
6692 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6693 << S.Context.getTagDeclType(BaseDecl);
6694 } else {
6695 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006696 << (Constructor->getInheritedConstructor() ? 2 :
6697 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006698 << S.Context.getTypeDeclType(Constructor->getParent())
6699 << /*member=*/1
6700 << Entity.getName();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006701 S.Diag(Entity.getDecl()->getLocation(),
6702 diag::note_member_declared_at);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006703
6704 if (const RecordType *Record
6705 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006706 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006707 diag::note_previous_decl)
6708 << S.Context.getTagDeclType(Record->getDecl());
6709 }
6710 break;
6711 }
6712
Douglas Gregor51c56d62009-12-14 20:49:26 +00006713 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6714 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006715 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006716 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006717
Douglas Gregor51c56d62009-12-14 20:49:26 +00006718 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006719 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006720 OverloadingResult Ovl
6721 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006722 if (Ovl != OR_Deleted) {
6723 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6724 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006725 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006726 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006727 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006728
6729 // If this is a defaulted or implicitly-declared function, then
6730 // it was implicitly deleted. Make it clear that the deletion was
6731 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006732 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006733 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006734 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006735 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006736 else
6737 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6738 << true << DestType << ArgsRange;
6739
6740 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006741 break;
6742 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006743
Douglas Gregor51c56d62009-12-14 20:49:26 +00006744 case OR_Success:
6745 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006746 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006747 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006748 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006749
Douglas Gregor99a2e602009-12-16 01:38:02 +00006750 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006751 if (Entity.getKind() == InitializedEntity::EK_Member &&
6752 isa<CXXConstructorDecl>(S.CurContext)) {
6753 // This is implicit default-initialization of a const member in
6754 // a constructor. Complain that it needs to be explicitly
6755 // initialized.
6756 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6757 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006758 << (Constructor->getInheritedConstructor() ? 2 :
6759 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006760 << S.Context.getTypeDeclType(Constructor->getParent())
6761 << /*const=*/1
6762 << Entity.getName();
6763 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6764 << Entity.getName();
6765 } else {
6766 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6767 << DestType << (bool)DestType->getAs<RecordType>();
6768 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006769 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006770
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006771 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006772 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006773 diag::err_init_incomplete_type);
6774 break;
6775
Sebastian Redl14b0c192011-09-24 17:48:00 +00006776 case FK_ListInitializationFailed: {
6777 // Run the init list checker again to emit diagnostics.
Bill Wendling2ca3db42013-11-22 00:01:44 +00006778 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6779 diagnoseListInit(S, Entity, InitList);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006780 break;
6781 }
John McCall5acb0c92011-10-17 18:40:02 +00006782
6783 case FK_PlaceholderType: {
6784 // FIXME: Already diagnosed!
6785 break;
6786 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006787
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006788 case FK_ExplicitConstructor: {
6789 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6790 << Args[0]->getSourceRange();
6791 OverloadCandidateSet::iterator Best;
6792 OverloadingResult Ovl
6793 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006794 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006795 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6796 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6797 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6798 break;
6799 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006800 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006801
Douglas Gregora41a8c52010-04-22 00:20:18 +00006802 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006803 return true;
6804}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006805
Chris Lattner5f9e2722011-07-23 10:55:15 +00006806void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006807 switch (SequenceKind) {
6808 case FailedSequence: {
6809 OS << "Failed sequence: ";
6810 switch (Failure) {
6811 case FK_TooManyInitsForReference:
6812 OS << "too many initializers for reference";
6813 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006814
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006815 case FK_ArrayNeedsInitList:
6816 OS << "array requires initializer list";
6817 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006818
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006819 case FK_ArrayNeedsInitListOrStringLiteral:
6820 OS << "array requires initializer list or string literal";
6821 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006822
Hans Wennborg0ff50742013-05-15 11:03:04 +00006823 case FK_ArrayNeedsInitListOrWideStringLiteral:
6824 OS << "array requires initializer list or wide string literal";
6825 break;
6826
6827 case FK_NarrowStringIntoWideCharArray:
6828 OS << "narrow string into wide char array";
6829 break;
6830
6831 case FK_WideStringIntoCharArray:
6832 OS << "wide string into char array";
6833 break;
6834
6835 case FK_IncompatWideStringIntoWideChar:
6836 OS << "incompatible wide string into wide char array";
6837 break;
6838
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006839 case FK_ArrayTypeMismatch:
6840 OS << "array type mismatch";
6841 break;
6842
6843 case FK_NonConstantArrayInit:
6844 OS << "non-constant array initializer";
6845 break;
6846
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006847 case FK_AddressOfOverloadFailed:
6848 OS << "address of overloaded function failed";
6849 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006850
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006851 case FK_ReferenceInitOverloadFailed:
6852 OS << "overload resolution for reference initialization failed";
6853 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006854
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006855 case FK_NonConstLValueReferenceBindingToTemporary:
6856 OS << "non-const lvalue reference bound to temporary";
6857 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006858
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006859 case FK_NonConstLValueReferenceBindingToUnrelated:
6860 OS << "non-const lvalue reference bound to unrelated type";
6861 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006862
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006863 case FK_RValueReferenceBindingToLValue:
6864 OS << "rvalue reference bound to an lvalue";
6865 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006866
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006867 case FK_ReferenceInitDropsQualifiers:
6868 OS << "reference initialization drops qualifiers";
6869 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006870
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006871 case FK_ReferenceInitFailed:
6872 OS << "reference initialization failed";
6873 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006874
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006875 case FK_ConversionFailed:
6876 OS << "conversion failed";
6877 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006878
John Wiegley429bb272011-04-08 18:41:53 +00006879 case FK_ConversionFromPropertyFailed:
6880 OS << "conversion from property failed";
6881 break;
6882
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006883 case FK_TooManyInitsForScalar:
6884 OS << "too many initializers for scalar";
6885 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006886
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006887 case FK_ReferenceBindingToInitList:
6888 OS << "referencing binding to initializer list";
6889 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006890
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006891 case FK_InitListBadDestinationType:
6892 OS << "initializer list for non-aggregate, non-scalar type";
6893 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006894
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006895 case FK_UserConversionOverloadFailed:
6896 OS << "overloading failed for user-defined conversion";
6897 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006898
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006899 case FK_ConstructorOverloadFailed:
6900 OS << "constructor overloading failed";
6901 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006902
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006903 case FK_DefaultInitOfConst:
6904 OS << "default initialization of a const variable";
6905 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006906
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006907 case FK_Incomplete:
6908 OS << "initialization of incomplete type";
6909 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006910
6911 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006912 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006913 break;
6914
John McCall73076432012-01-05 00:13:19 +00006915 case FK_VariableLengthArrayHasInitializer:
6916 OS << "variable length array has an initializer";
6917 break;
6918
John McCall5acb0c92011-10-17 18:40:02 +00006919 case FK_PlaceholderType:
6920 OS << "initializer expression isn't contextually valid";
6921 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006922
6923 case FK_ListConstructorOverloadFailed:
6924 OS << "list constructor overloading failed";
6925 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006926
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006927 case FK_ExplicitConstructor:
6928 OS << "list copy initialization chose explicit constructor";
6929 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006930 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006931 OS << '\n';
6932 return;
6933 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006934
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006935 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006936 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006937 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006938
Sebastian Redl7491c492011-06-05 13:59:11 +00006939 case NormalSequence:
6940 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006941 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006942 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006943
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006944 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6945 if (S != step_begin()) {
6946 OS << " -> ";
6947 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006948
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006949 switch (S->Kind) {
6950 case SK_ResolveAddressOfOverloadedFunction:
6951 OS << "resolve address of overloaded function";
6952 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006953
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006954 case SK_CastDerivedToBaseRValue:
6955 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6956 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006957
Sebastian Redl906082e2010-07-20 04:20:21 +00006958 case SK_CastDerivedToBaseXValue:
6959 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6960 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006961
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006962 case SK_CastDerivedToBaseLValue:
6963 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6964 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006965
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006966 case SK_BindReference:
6967 OS << "bind reference to lvalue";
6968 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006969
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006970 case SK_BindReferenceToTemporary:
6971 OS << "bind reference to a temporary";
6972 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006973
Douglas Gregor523d46a2010-04-18 07:40:54 +00006974 case SK_ExtraneousCopyToTemporary:
6975 OS << "extraneous C++03 copy to temporary";
6976 break;
6977
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006978 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006979 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006980 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006981
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006982 case SK_QualificationConversionRValue:
6983 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006984 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006985
Sebastian Redl906082e2010-07-20 04:20:21 +00006986 case SK_QualificationConversionXValue:
6987 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006988 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006989
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006990 case SK_QualificationConversionLValue:
6991 OS << "qualification conversion (lvalue)";
6992 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006993
Jordan Rose1fd1e282013-04-11 00:58:58 +00006994 case SK_LValueToRValue:
6995 OS << "load (lvalue to rvalue)";
6996 break;
6997
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006998 case SK_ConversionSequence:
6999 OS << "implicit conversion sequence (";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +00007000 S->ICS->dump(); // FIXME: use OS
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007001 OS << ")";
7002 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007003
Richard Smith13b228d2013-09-21 21:19:19 +00007004 case SK_ConversionSequenceNoNarrowing:
7005 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +00007006 S->ICS->dump(); // FIXME: use OS
Richard Smith13b228d2013-09-21 21:19:19 +00007007 OS << ")";
7008 break;
7009
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007010 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00007011 OS << "list aggregate initialization";
7012 break;
7013
7014 case SK_ListConstructorCall:
7015 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007016 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007017
Sebastian Redl13dc8f92011-11-27 16:50:07 +00007018 case SK_UnwrapInitList:
7019 OS << "unwrap reference initializer list";
7020 break;
7021
7022 case SK_RewrapInitList:
7023 OS << "rewrap reference initializer list";
7024 break;
7025
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007026 case SK_ConstructorInitialization:
7027 OS << "constructor initialization";
7028 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007029
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007030 case SK_ZeroInitialization:
7031 OS << "zero initialization";
7032 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007033
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007034 case SK_CAssignment:
7035 OS << "C assignment";
7036 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007037
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007038 case SK_StringInit:
7039 OS << "string initialization";
7040 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00007041
7042 case SK_ObjCObjectConversion:
7043 OS << "Objective-C object conversion";
7044 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00007045
7046 case SK_ArrayInit:
7047 OS << "array initialization";
7048 break;
John McCallf85e1932011-06-15 23:02:42 +00007049
Richard Smith0f163e92012-02-15 22:38:09 +00007050 case SK_ParenthesizedArrayInit:
7051 OS << "parenthesized array initialization";
7052 break;
7053
John McCallf85e1932011-06-15 23:02:42 +00007054 case SK_PassByIndirectCopyRestore:
7055 OS << "pass by indirect copy and restore";
7056 break;
7057
7058 case SK_PassByIndirectRestore:
7059 OS << "pass by indirect restore";
7060 break;
7061
7062 case SK_ProduceObjCObject:
7063 OS << "Objective-C object retension";
7064 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00007065
7066 case SK_StdInitializerList:
7067 OS << "std::initializer_list from initializer list";
7068 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007069
Guy Benyei21f18c42013-02-07 10:55:47 +00007070 case SK_OCLSamplerInit:
7071 OS << "OpenCL sampler_t from integer constant";
7072 break;
7073
Guy Benyeie6b9d802013-01-20 12:31:11 +00007074 case SK_OCLZeroEvent:
7075 OS << "OpenCL event_t from zero";
7076 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007077 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00007078
7079 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007080 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00007081
7082 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007083}
7084
7085void InitializationSequence::dump() const {
7086 dump(llvm::errs());
7087}
7088
Richard Smith13b228d2013-09-21 21:19:19 +00007089static void DiagnoseNarrowingInInitList(Sema &S,
7090 const ImplicitConversionSequence &ICS,
7091 QualType PreNarrowingType,
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007092 QualType EntityType,
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007093 const Expr *PostInit) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007094 const StandardConversionSequence *SCS = nullptr;
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007095 switch (ICS.getKind()) {
7096 case ImplicitConversionSequence::StandardConversion:
7097 SCS = &ICS.Standard;
7098 break;
7099 case ImplicitConversionSequence::UserDefinedConversion:
7100 SCS = &ICS.UserDefined.After;
7101 break;
7102 case ImplicitConversionSequence::AmbiguousConversion:
7103 case ImplicitConversionSequence::EllipsisConversion:
7104 case ImplicitConversionSequence::BadConversion:
7105 return;
7106 }
7107
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007108 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7109 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00007110 QualType ConstantType;
7111 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7112 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007113 case NK_Not_Narrowing:
7114 // No narrowing occurred.
7115 return;
7116
7117 case NK_Type_Narrowing:
7118 // This was a floating-to-integer conversion, which is always considered a
7119 // narrowing conversion even if the value is a constant and can be
7120 // represented exactly as an integer.
7121 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007122 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7123 ? diag::warn_init_list_type_narrowing
7124 : diag::ext_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007125 << PostInit->getSourceRange()
7126 << PreNarrowingType.getLocalUnqualifiedType()
7127 << EntityType.getLocalUnqualifiedType();
7128 break;
7129
7130 case NK_Constant_Narrowing:
7131 // A constant value was narrowed.
7132 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007133 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7134 ? diag::warn_init_list_constant_narrowing
7135 : diag::ext_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007136 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00007137 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00007138 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007139 break;
7140
7141 case NK_Variable_Narrowing:
7142 // A variable's value may have been narrowed.
7143 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007144 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7145 ? diag::warn_init_list_variable_narrowing
7146 : diag::ext_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007147 << PostInit->getSourceRange()
7148 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00007149 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007150 break;
7151 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007152
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007153 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007154 llvm::raw_svector_ostream OS(StaticCast);
7155 OS << "static_cast<";
7156 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7157 // It's important to use the typedef's name if there is one so that the
7158 // fixit doesn't break code using types like int64_t.
7159 //
7160 // FIXME: This will break if the typedef requires qualification. But
7161 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00007162 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007163 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00007164 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007165 else {
7166 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7167 // with a broken cast.
7168 return;
7169 }
7170 OS << ">(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007171 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
7172 << PostInit->getSourceRange()
7173 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7174 << FixItHint::CreateInsertion(
7175 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007176}
7177
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007178//===----------------------------------------------------------------------===//
7179// Initialization helper functions
7180//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00007181bool
7182Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7183 ExprResult Init) {
7184 if (Init.isInvalid())
7185 return false;
7186
7187 Expr *InitE = Init.get();
7188 assert(InitE && "No initialization expression");
7189
Douglas Gregor3c394c52012-07-31 22:15:04 +00007190 InitializationKind Kind
7191 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007192 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00007193 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00007194}
7195
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007196ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007197Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7198 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007199 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00007200 bool TopLevelOfInitList,
7201 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007202 if (Init.isInvalid())
7203 return ExprError();
7204
John McCall15d7d122010-11-11 03:21:53 +00007205 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007206 assert(InitE && "No initialization expression?");
7207
7208 if (EqualLoc.isInvalid())
7209 EqualLoc = InitE->getLocStart();
7210
7211 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00007212 EqualLoc,
7213 AllowExplicit);
Richard Smith13b228d2013-09-21 21:19:19 +00007214 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007215 Init.get();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007216
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007217 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007218
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007219 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007220}