blob: b57e029ddfdbe7f09fb058ff69629029ad591e5b [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(),
Stephen Hines176edba2014-12-01 14:53:08 -0800192 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000193 << 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 Hines176edba2014-12-01 14:53:08 -0800469 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
470 if (DIE.isInvalid()) {
471 hadError = true;
472 return;
473 }
Richard Smithc3bf52c2013-04-20 22:23:05 +0000474 if (Init < NumInits)
Stephen Hines176edba2014-12-01 14:53:08 -0800475 ILE->setInit(Init, DIE.get());
Richard Smithc3bf52c2013-04-20 22:23:05 +0000476 else {
Stephen Hines176edba2014-12-01 14:53:08 -0800477 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smithc3bf52c2013-04-20 22:23:05 +0000478 RequiresSecondPass = true;
479 }
480 return;
481 }
482
Douglas Gregord6d37de2009-12-22 00:05:34 +0000483 if (Field->getType()->isReferenceType()) {
484 // C++ [dcl.init.aggr]p9:
485 // If an incomplete or empty initializer-list leaves a
486 // member of reference type uninitialized, the program is
487 // ill-formed.
488 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
489 << Field->getType()
490 << ILE->getSyntacticForm()->getSourceRange();
491 SemaRef.Diag(Field->getLocation(),
492 diag::note_uninit_reference_member);
493 hadError = true;
494 return;
495 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000496
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700497 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
498 /*VerifyOnly*/false);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000499 if (MemberInit.isInvalid()) {
500 hadError = true;
501 return;
502 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000503
Douglas Gregord6d37de2009-12-22 00:05:34 +0000504 if (hadError) {
505 // Do nothing
506 } else if (Init < NumInits) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700507 ILE->setInit(Init, MemberInit.getAs<Expr>());
508 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
509 // Empty initialization requires a constructor call, so
Douglas Gregord6d37de2009-12-22 00:05:34 +0000510 // extend the initializer list to include the constructor
511 // call and make a note that we'll need to take another pass
512 // through the initializer list.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700513 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000514 RequiresSecondPass = true;
515 }
516 } else if (InitListExpr *InnerILE
517 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700518 FillInEmptyInitializations(MemberEntity, InnerILE,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000519 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000520}
521
Douglas Gregor4c678342009-01-28 21:54:33 +0000522/// Recursively replaces NULL values within the given initializer list
523/// with expressions that perform value-initialization of the
524/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000525void
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700526InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000527 InitListExpr *ILE,
528 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000529 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000530 "Should not have void type");
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Ted Kremenek6217b802009-07-29 21:53:49 +0000532 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000533 const RecordDecl *RDecl = RType->getDecl();
534 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700535 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Douglas Gregord6d37de2009-12-22 00:05:34 +0000536 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000537 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
538 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700539 for (auto *Field : RDecl->fields()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000540 if (Field->hasInClassInitializer()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700541 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000542 break;
543 }
544 }
545 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000546 unsigned Init = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700547 for (auto *Field : RDecl->fields()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000548 if (Field->isUnnamedBitfield())
549 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000550
Douglas Gregord6d37de2009-12-22 00:05:34 +0000551 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000552 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000553
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700554 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000555 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000556 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000557
Douglas Gregord6d37de2009-12-22 00:05:34 +0000558 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000559
Douglas Gregord6d37de2009-12-22 00:05:34 +0000560 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000561 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000562 break;
563 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000564 }
565
566 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000567 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000568
569 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000571 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000572 unsigned NumInits = ILE->getNumInits();
573 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000574 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000576 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
577 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000579 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000580 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000581 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000582 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000584 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000585 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000586 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Douglas Gregor87fd7032009-02-02 17:43:21 +0000588 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000589 if (hadError)
590 return;
591
Anders Carlssond3d824d2010-01-23 04:34:47 +0000592 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
593 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000594 ElementEntity.setElementIndex(Init);
595
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700596 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000597 if (!InitExpr && !ILE->hasArrayFiller()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700598 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
599 ElementEntity,
600 /*VerifyOnly*/false);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000601 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000602 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000603 return;
604 }
605
606 if (hadError) {
607 // Do nothing
608 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000609 // For arrays, just set the expression used for value-initialization
610 // of the "holes" in the array.
611 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700612 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000613 else
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700614 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000615 } else {
616 // For arrays, just set the expression used for value-initialization
617 // of the rest of elements and exit.
618 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700619 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000620 return;
621 }
622
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700623 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
624 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000625 // extend the initializer list to include the constructor
626 // call and make a note that we'll need to take another pass
627 // through the initializer list.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700628 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000629 RequiresSecondPass = true;
630 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000631 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000632 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000633 = dyn_cast_or_null<InitListExpr>(InitExpr))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700634 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000635 }
636}
637
Chris Lattner68355a52009-01-29 05:10:57 +0000638
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000639InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000640 InitListExpr *IL, QualType &T,
Richard Smith40cba902013-06-06 11:41:05 +0000641 bool VerifyOnly)
642 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000643 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000644
Richard Smithb9bf3122013-09-20 20:10:22 +0000645 FullyStructuredList =
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700646 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smithb9bf3122013-09-20 20:10:22 +0000647 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000648 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000649
Sebastian Redl14b0c192011-09-24 17:48:00 +0000650 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000651 bool RequiresSecondPass = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700652 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000653 if (RequiresSecondPass && !hadError)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700654 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000655 RequiresSecondPass);
656 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000657}
658
659int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000660 // FIXME: use a proper constant
661 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000662 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000663 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000664 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
665 }
666 return maxElements;
667}
668
669int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000670 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000671 int InitializableMembers = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700672 for (const auto *Field : structDecl->fields())
Douglas Gregord61db332011-10-10 17:22:13 +0000673 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 ++InitializableMembers;
Stephen Hines651f13c2014-04-23 16:59:28 -0700675
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000676 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000677 return std::min(InitializableMembers, 1);
678 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000679}
680
Richard Smithb9bf3122013-09-20 20:10:22 +0000681/// Check whether the range of the initializer \p ParentIList from element
682/// \p Index onwards can be used to initialize an object of type \p T. Update
683/// \p Index to indicate how many elements of the list were consumed.
684///
685/// This also fills in \p StructuredList, from element \p StructuredIndex
686/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000687void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000688 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000689 QualType T, unsigned &Index,
690 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000691 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000692 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Steve Naroff0cca7492008-05-01 22:18:59 +0000694 if (T->isArrayType())
695 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000696 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000697 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000698 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000699 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000700 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000701 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000702
Eli Friedman402256f2008-05-25 13:49:22 +0000703 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000704 if (!VerifyOnly)
705 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
706 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000707 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000708 hadError = true;
709 return;
710 }
711
Douglas Gregor4c678342009-01-28 21:54:33 +0000712 // Build a structured initializer list corresponding to this subobject.
713 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000714 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
715 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000716 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000717 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000718 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000719
Douglas Gregor4c678342009-01-28 21:54:33 +0000720 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000721 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000722 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000723 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000724 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000725 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000726
Richard Smith40cba902013-06-06 11:41:05 +0000727 if (!VerifyOnly) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000728 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000729
Sebastian Redlc2235182011-10-16 18:19:28 +0000730 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000731 // Update the structured sub-object initializer so that it's ending
732 // range corresponds with the end of the last initializer it used.
733 if (EndIndex < ParentIList->getNumInits()) {
734 SourceLocation EndLoc
735 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
736 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
737 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000738
Sebastian Redlc2235182011-10-16 18:19:28 +0000739 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000740 if (T->isArrayType() || T->isRecordType()) {
741 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smith40cba902013-06-06 11:41:05 +0000742 diag::warn_missing_braces)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700743 << StructuredSubobjectInitList->getSourceRange()
744 << FixItHint::CreateInsertion(
745 StructuredSubobjectInitList->getLocStart(), "{")
746 << FixItHint::CreateInsertion(
747 SemaRef.getLocForEndOfToken(
748 StructuredSubobjectInitList->getLocEnd()),
749 "}");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000750 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000751 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000752}
753
Richard Smithb9bf3122013-09-20 20:10:22 +0000754/// Check whether the initializer \p IList (that was written with explicit
755/// braces) can be used to initialize an object of type \p T.
756///
757/// This also fills in \p StructuredList with the fully-braced, desugared
758/// form of the initialization.
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000759void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000760 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000761 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000762 bool TopLevelObject) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000763 if (!VerifyOnly) {
764 SyntacticToSemantic[IList] = StructuredList;
765 StructuredList->setSyntacticForm(IList);
766 }
Richard Smithb9bf3122013-09-20 20:10:22 +0000767
768 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000770 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000771 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000772 QualType ExprTy = T;
773 if (!ExprTy->isArrayType())
774 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000775 IList->setType(ExprTy);
776 StructuredList->setType(ExprTy);
777 }
Eli Friedman638e1442008-05-25 13:22:35 +0000778 if (hadError)
779 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000780
Eli Friedman638e1442008-05-25 13:22:35 +0000781 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000782 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000783 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000784 if (SemaRef.getLangOpts().CPlusPlus ||
785 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000786 IList->getType()->isVectorType())) {
787 hadError = true;
788 }
789 return;
790 }
791
Eli Friedmane5408582009-05-29 20:20:05 +0000792 if (StructuredIndex == 1 &&
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000793 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
794 SIF_None) {
Stephen Hines176edba2014-12-01 14:53:08 -0800795 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000796 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000797 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000798 hadError = true;
799 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000800 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000801 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000802 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000803 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000804 // Don't complain for incomplete types, since we'll get an error
805 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000806 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000807 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000808 CurrentObjectType->isArrayType()? 0 :
809 CurrentObjectType->isVectorType()? 1 :
810 CurrentObjectType->isScalarType()? 2 :
811 CurrentObjectType->isUnionType()? 3 :
812 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000813
Stephen Hines176edba2014-12-01 14:53:08 -0800814 unsigned DK = diag::ext_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000815 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000816 DK = diag::err_excess_initializers;
817 hadError = true;
818 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000819 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000820 DK = diag::err_excess_initializers;
821 hadError = true;
822 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000823
Chris Lattner08202542009-02-24 22:50:46 +0000824 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000825 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000826 }
827 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000828
Sebastian Redl14b0c192011-09-24 17:48:00 +0000829 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
830 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000831 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000832 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000833 << FixItHint::CreateRemoval(IList->getLocStart())
834 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000835}
836
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000837void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000838 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000839 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000840 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000841 unsigned &Index,
842 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000843 unsigned &StructuredIndex,
844 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000845 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
846 // Explicitly braced initializer for complex type can be real+imaginary
847 // parts.
848 CheckComplexType(Entity, IList, DeclType, Index,
849 StructuredList, StructuredIndex);
850 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000851 CheckScalarType(Entity, IList, DeclType, Index,
852 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000853 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000854 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000855 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000856 } else if (DeclType->isRecordType()) {
857 assert(DeclType->isAggregateType() &&
858 "non-aggregate records should be handed in CheckSubElementType");
859 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
860 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
861 SubobjectIsDesignatorContext, Index,
862 StructuredList, StructuredIndex,
863 TopLevelObject);
864 } else if (DeclType->isArrayType()) {
865 llvm::APSInt Zero(
866 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
867 false);
868 CheckArrayType(Entity, IList, DeclType, Zero,
869 SubobjectIsDesignatorContext, Index,
870 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000871 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
872 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000873 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000874 if (!VerifyOnly)
875 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
876 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000877 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000878 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000879 CheckReferenceType(Entity, IList, DeclType, Index,
880 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000881 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000882 if (!VerifyOnly)
883 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
884 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000885 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000886 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000887 if (!VerifyOnly)
888 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
889 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000890 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000891 }
892}
893
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000894void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000895 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000896 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000897 unsigned &Index,
898 InitListExpr *StructuredList,
899 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000900 Expr *expr = IList->getInit(Index);
Richard Smith6242a452013-05-31 02:56:17 +0000901
902 if (ElemType->isReferenceType())
903 return CheckReferenceType(Entity, IList, ElemType, Index,
904 StructuredList, StructuredIndex);
905
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000906 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000907 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smithb9bf3122013-09-20 20:10:22 +0000908 InitListExpr *InnerStructuredList
Richard Smith20599392012-07-07 08:35:56 +0000909 = getStructuredSubobjectInit(IList, Index, ElemType,
910 StructuredList, StructuredIndex,
911 SubInitList->getSourceRange());
Richard Smithb9bf3122013-09-20 20:10:22 +0000912 CheckExplicitInitList(Entity, SubInitList, ElemType,
913 InnerStructuredList);
Richard Smith20599392012-07-07 08:35:56 +0000914 ++StructuredIndex;
915 ++Index;
916 return;
917 }
918 assert(SemaRef.getLangOpts().CPlusPlus &&
919 "non-aggregate records are only possible in C++");
920 // C++ initialization is handled later.
Stephen Hines176edba2014-12-01 14:53:08 -0800921 } else if (isa<ImplicitValueInitExpr>(expr)) {
922 // This happens during template instantiation when we see an InitListExpr
923 // that we've already checked once.
924 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
925 "found implicit initialization for the wrong type");
926 if (!VerifyOnly)
927 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
928 ++Index;
929 return;
Richard Smith20599392012-07-07 08:35:56 +0000930 }
931
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000932 // FIXME: Need to handle atomic aggregate types with implicit init lists.
933 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCallfef8b342011-02-21 07:57:55 +0000934 return CheckScalarType(Entity, IList, ElemType, Index,
935 StructuredList, StructuredIndex);
Anders Carlssond28b4282009-08-27 17:18:13 +0000936
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000937 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
938 ElemType->isArrayType()) && "Unexpected type");
939
John McCallfef8b342011-02-21 07:57:55 +0000940 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
941 // arrayType can be incomplete if we're initializing a flexible
942 // array member. There's nothing we can do with the completed
943 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000944
Hans Wennborg0ff50742013-05-15 11:03:04 +0000945 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000946 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000947 CheckStringInit(expr, ElemType, arrayType, SemaRef);
948 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000949 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000950 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000951 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000952 }
John McCallfef8b342011-02-21 07:57:55 +0000953
954 // Fall through for subaggregate initialization.
955
David Blaikie4e4d0842012-03-11 07:00:24 +0000956 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000957 // C++ [dcl.init.aggr]p12:
958 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000959 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000960 // an initializer-list. If the initializer can initialize a
961 // member, the member is initialized. [...]
962
963 // FIXME: Better EqualLoc?
964 InitializationKind Kind =
965 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000966 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000967
968 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000969 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000970 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000971 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000972 if (Result.isInvalid())
973 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000974
Sebastian Redl14b0c192011-09-24 17:48:00 +0000975 UpdateStructuredListElement(StructuredList, StructuredIndex,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700976 Result.getAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000977 }
John McCallfef8b342011-02-21 07:57:55 +0000978 ++Index;
979 return;
980 }
981
982 // Fall through for subaggregate initialization
983 } else {
984 // C99 6.7.8p13:
985 //
986 // The initializer for a structure or union object that has
987 // automatic storage duration shall be either an initializer
988 // list as described below, or a single expression that has
989 // compatible structure or union type. In the latter case, the
990 // initial value of the object, including unnamed members, is
991 // that of the expression.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700992 ExprResult ExprRes = expr;
John McCallfef8b342011-02-21 07:57:55 +0000993 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000994 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
995 !VerifyOnly)
Eli Friedman08f0bbc2013-09-17 04:07:04 +0000996 != Sema::Incompatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000997 if (ExprRes.isInvalid())
998 hadError = true;
999 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001000 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00001001 if (ExprRes.isInvalid())
1002 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +00001003 }
1004 UpdateStructuredListElement(StructuredList, StructuredIndex,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001005 ExprRes.getAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +00001006 ++Index;
1007 return;
1008 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001009 ExprRes.get();
John McCallfef8b342011-02-21 07:57:55 +00001010 // Fall through for subaggregate initialization
1011 }
1012
1013 // C++ [dcl.init.aggr]p12:
1014 //
1015 // [...] Otherwise, if the member is itself a non-empty
1016 // subaggregate, brace elision is assumed and the initializer is
1017 // considered for the initialization of the first member of
1018 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +00001019 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00001020 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +00001021 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1022 StructuredIndex);
1023 ++StructuredIndex;
1024 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001025 if (!VerifyOnly) {
1026 // We cannot initialize this element, so let
1027 // PerformCopyInitialization produce the appropriate diagnostic.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001028 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001029 /*TopLevelOfInitList=*/true);
1030 }
John McCallfef8b342011-02-21 07:57:55 +00001031 hadError = true;
1032 ++Index;
1033 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001034 }
Eli Friedmanb85f7072008-05-19 19:16:24 +00001035}
1036
Eli Friedman0c706c22011-09-19 23:17:44 +00001037void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1038 InitListExpr *IList, QualType DeclType,
1039 unsigned &Index,
1040 InitListExpr *StructuredList,
1041 unsigned &StructuredIndex) {
1042 assert(Index == 0 && "Index in explicit init list must be zero");
1043
1044 // As an extension, clang supports complex initializers, which initialize
1045 // a complex number component-wise. When an explicit initializer list for
1046 // a complex number contains two two initializers, this extension kicks in:
1047 // it exepcts the initializer list to contain two elements convertible to
1048 // the element type of the complex type. The first element initializes
1049 // the real part, and the second element intitializes the imaginary part.
1050
1051 if (IList->getNumInits() != 2)
1052 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1053 StructuredIndex);
1054
1055 // This is an extension in C. (The builtin _Complex type does not exist
1056 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +00001057 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +00001058 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1059 << IList->getSourceRange();
1060
1061 // Initialize the complex number.
1062 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1063 InitializedEntity ElementEntity =
1064 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1065
1066 for (unsigned i = 0; i < 2; ++i) {
1067 ElementEntity.setElementIndex(Index);
1068 CheckSubElementType(ElementEntity, IList, elementType, Index,
1069 StructuredList, StructuredIndex);
1070 }
1071}
1072
1073
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001074void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001075 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001076 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001077 InitListExpr *StructuredList,
1078 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +00001079 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +00001080 if (!VerifyOnly)
1081 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001082 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +00001083 diag::warn_cxx98_compat_empty_scalar_initializer :
1084 diag::err_empty_scalar_initializer)
1085 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +00001086 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +00001087 ++Index;
1088 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +00001089 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001090 }
John McCallb934c2d2010-11-11 00:46:36 +00001091
1092 Expr *expr = IList->getInit(Index);
1093 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001094 // FIXME: This is invalid, and accepting it causes overload resolution
1095 // to pick the wrong overload in some corner cases.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001096 if (!VerifyOnly)
1097 SemaRef.Diag(SubIList->getLocStart(),
Stephen Hines651f13c2014-04-23 16:59:28 -07001098 diag::ext_many_braces_around_scalar_init)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001099 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001100
1101 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1102 StructuredIndex);
1103 return;
1104 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001105 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001106 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001107 diag::err_designator_for_scalar_init)
1108 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001109 hadError = true;
1110 ++Index;
1111 ++StructuredIndex;
1112 return;
1113 }
1114
Sebastian Redl14b0c192011-09-24 17:48:00 +00001115 if (VerifyOnly) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001116 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redl14b0c192011-09-24 17:48:00 +00001117 hadError = true;
1118 ++Index;
1119 return;
1120 }
1121
John McCallb934c2d2010-11-11 00:46:36 +00001122 ExprResult Result =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001123 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001124 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001125
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001126 Expr *ResultExpr = nullptr;
John McCallb934c2d2010-11-11 00:46:36 +00001127
1128 if (Result.isInvalid())
1129 hadError = true; // types weren't compatible.
1130 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001131 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001132
John McCallb934c2d2010-11-11 00:46:36 +00001133 if (ResultExpr != expr) {
1134 // The type was promoted, update initializer list.
1135 IList->setInit(Index, ResultExpr);
1136 }
1137 }
1138 if (hadError)
1139 ++StructuredIndex;
1140 else
1141 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1142 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001143}
1144
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001145void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1146 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001147 unsigned &Index,
1148 InitListExpr *StructuredList,
1149 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001150 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001151 // FIXME: It would be wonderful if we could point at the actual member. In
1152 // general, it would be useful to pass location information down the stack,
1153 // so that we know the location (or decl) of the "current object" being
1154 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001155 if (!VerifyOnly)
1156 SemaRef.Diag(IList->getLocStart(),
1157 diag::err_init_reference_member_uninitialized)
1158 << DeclType
1159 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001160 hadError = true;
1161 ++Index;
1162 ++StructuredIndex;
1163 return;
1164 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001165
1166 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001167 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001168 if (!VerifyOnly)
1169 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1170 << DeclType << IList->getSourceRange();
1171 hadError = true;
1172 ++Index;
1173 ++StructuredIndex;
1174 return;
1175 }
1176
1177 if (VerifyOnly) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001178 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redl14b0c192011-09-24 17:48:00 +00001179 hadError = true;
1180 ++Index;
1181 return;
1182 }
1183
1184 ExprResult Result =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001185 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1186 /*TopLevelOfInitList=*/true);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001187
1188 if (Result.isInvalid())
1189 hadError = true;
1190
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001191 expr = Result.getAs<Expr>();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001192 IList->setInit(Index, expr);
1193
1194 if (hadError)
1195 ++StructuredIndex;
1196 else
1197 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1198 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001199}
1200
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001201void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001202 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001203 unsigned &Index,
1204 InitListExpr *StructuredList,
1205 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001206 const VectorType *VT = DeclType->getAs<VectorType>();
1207 unsigned maxElements = VT->getNumElements();
1208 unsigned numEltsInit = 0;
1209 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001210
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001211 if (Index >= IList->getNumInits()) {
1212 // Make sure the element type can be value-initialized.
1213 if (VerifyOnly)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001214 CheckEmptyInitializable(
1215 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1216 IList->getLocEnd());
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001217 return;
1218 }
1219
David Blaikie4e4d0842012-03-11 07:00:24 +00001220 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001221 // If the initializing element is a vector, try to copy-initialize
1222 // instead of breaking it apart (which is doomed to failure anyway).
1223 Expr *Init = IList->getInit(Index);
1224 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001225 if (VerifyOnly) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001226 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redl14b0c192011-09-24 17:48:00 +00001227 hadError = true;
1228 ++Index;
1229 return;
1230 }
1231
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001232 ExprResult Result =
1233 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1234 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001235
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001236 Expr *ResultExpr = nullptr;
John McCall20e047a2010-10-30 00:11:39 +00001237 if (Result.isInvalid())
1238 hadError = true; // types weren't compatible.
1239 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001240 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001241
John McCall20e047a2010-10-30 00:11:39 +00001242 if (ResultExpr != Init) {
1243 // The type was promoted, update initializer list.
1244 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001245 }
1246 }
John McCall20e047a2010-10-30 00:11:39 +00001247 if (hadError)
1248 ++StructuredIndex;
1249 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001250 UpdateStructuredListElement(StructuredList, StructuredIndex,
1251 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001252 ++Index;
1253 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
John McCall20e047a2010-10-30 00:11:39 +00001256 InitializedEntity ElementEntity =
1257 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001258
John McCall20e047a2010-10-30 00:11:39 +00001259 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1260 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001261 if (Index >= IList->getNumInits()) {
1262 if (VerifyOnly)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001263 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall20e047a2010-10-30 00:11:39 +00001264 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001265 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001266
John McCall20e047a2010-10-30 00:11:39 +00001267 ElementEntity.setElementIndex(Index);
1268 CheckSubElementType(ElementEntity, IList, elementType, Index,
1269 StructuredList, StructuredIndex);
1270 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001271
1272 if (VerifyOnly)
1273 return;
1274
1275 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1276 const VectorType *T = Entity.getType()->getAs<VectorType>();
1277 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1278 T->getVectorKind() == VectorType::NeonPolyVector)) {
1279 // The ability to use vector initializer lists is a GNU vector extension
1280 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1281 // endian machines it works fine, however on big endian machines it
1282 // exhibits surprising behaviour:
1283 //
1284 // uint32x2_t x = {42, 64};
1285 // return vget_lane_u32(x, 0); // Will return 64.
1286 //
1287 // Because of this, explicitly call out that it is non-portable.
1288 //
1289 SemaRef.Diag(IList->getLocStart(),
1290 diag::warn_neon_vector_initializer_non_portable);
1291
1292 const char *typeCode;
1293 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1294
1295 if (elementType->isFloatingType())
1296 typeCode = "f";
1297 else if (elementType->isSignedIntegerType())
1298 typeCode = "s";
1299 else if (elementType->isUnsignedIntegerType())
1300 typeCode = "u";
1301 else
1302 llvm_unreachable("Invalid element type!");
1303
1304 SemaRef.Diag(IList->getLocStart(),
1305 SemaRef.Context.getTypeSize(VT) > 64 ?
1306 diag::note_neon_vector_initializer_non_portable_q :
1307 diag::note_neon_vector_initializer_non_portable)
1308 << typeCode << typeSize;
1309 }
1310
John McCall20e047a2010-10-30 00:11:39 +00001311 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001312 }
John McCall20e047a2010-10-30 00:11:39 +00001313
1314 InitializedEntity ElementEntity =
1315 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001316
John McCall20e047a2010-10-30 00:11:39 +00001317 // OpenCL initializers allows vectors to be constructed from vectors.
1318 for (unsigned i = 0; i < maxElements; ++i) {
1319 // Don't attempt to go past the end of the init list
1320 if (Index >= IList->getNumInits())
1321 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001322
John McCall20e047a2010-10-30 00:11:39 +00001323 ElementEntity.setElementIndex(Index);
1324
1325 QualType IType = IList->getInit(Index)->getType();
1326 if (!IType->isVectorType()) {
1327 CheckSubElementType(ElementEntity, IList, elementType, Index,
1328 StructuredList, StructuredIndex);
1329 ++numEltsInit;
1330 } else {
1331 QualType VecType;
1332 const VectorType *IVT = IType->getAs<VectorType>();
1333 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001334
John McCall20e047a2010-10-30 00:11:39 +00001335 if (IType->isExtVectorType())
1336 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1337 else
1338 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001339 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001340 CheckSubElementType(ElementEntity, IList, VecType, Index,
1341 StructuredList, StructuredIndex);
1342 numEltsInit += numIElts;
1343 }
1344 }
1345
1346 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001347 if (numEltsInit != maxElements) {
1348 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001349 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001350 diag::err_vector_incorrect_num_initializers)
1351 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1352 hadError = true;
1353 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001354}
1355
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001356void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001357 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001358 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001359 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001360 unsigned &Index,
1361 InitListExpr *StructuredList,
1362 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001363 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1364
Steve Naroff0cca7492008-05-01 22:18:59 +00001365 // Check for the special-case of initializing an array with a string.
1366 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001367 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1368 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001369 // We place the string literal directly into the resulting
1370 // initializer list. This is the only place where the structure
1371 // of the structured initializer list doesn't match exactly,
1372 // because doing so would involve allocating one character
1373 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001374 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001375 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1376 UpdateStructuredListElement(StructuredList, StructuredIndex,
1377 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001378 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1379 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001380 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001381 return;
1382 }
1383 }
John McCallce6c9b72011-02-21 07:22:22 +00001384 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001385 // Check for VLAs; in standard C it would be possible to check this
1386 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1387 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001388 if (!VerifyOnly)
1389 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1390 diag::err_variable_object_no_init)
1391 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001392 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 ++Index;
1394 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001395 return;
1396 }
1397
Douglas Gregor05c13a32009-01-22 00:58:24 +00001398 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001399 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1400 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001401 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001402 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001403 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001404 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001405 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001406 maxElementsKnown = true;
1407 }
1408
John McCallce6c9b72011-02-21 07:22:22 +00001409 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001410 while (Index < IList->getNumInits()) {
1411 Expr *Init = IList->getInit(Index);
1412 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001413 // If we're not the subobject that matches up with the '{' for
1414 // the designator, we shouldn't be handling the
1415 // designator. Return immediately.
1416 if (!SubobjectIsDesignatorContext)
1417 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001418
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001419 // Handle this designated initializer. elementIndex will be
1420 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001421 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001422 DeclType, nullptr, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001423 StructuredList, StructuredIndex, true,
1424 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001425 hadError = true;
1426 continue;
1427 }
1428
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001429 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001430 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001431 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001432 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001433 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001434
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001435 // If the array is of incomplete type, keep track of the number of
1436 // elements in the initializer.
1437 if (!maxElementsKnown && elementIndex > maxElements)
1438 maxElements = elementIndex;
1439
Douglas Gregor05c13a32009-01-22 00:58:24 +00001440 continue;
1441 }
1442
1443 // If we know the maximum number of elements, and we've already
1444 // hit it, stop consuming elements in the initializer list.
1445 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001446 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001447
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001448 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001450 Entity);
1451 // Check this element.
1452 CheckSubElementType(ElementEntity, IList, elementType, Index,
1453 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001454 ++elementIndex;
1455
1456 // If the array is of incomplete type, keep track of the number of
1457 // elements in the initializer.
1458 if (!maxElementsKnown && elementIndex > maxElements)
1459 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001460 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001461 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001462 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001463 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001464 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001465 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001466 // Sizing an array implicitly to zero is not allowed by ISO C,
1467 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001468 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001469 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001470 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001471
Mike Stump1eb44332009-09-09 15:08:12 +00001472 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001473 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001474 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001475 if (!hadError && VerifyOnly) {
1476 // Check if there are any members of the array that get value-initialized.
1477 // If so, check if doing that is possible.
1478 // FIXME: This needs to detect holes left by designated initializers too.
1479 if (maxElementsKnown && elementIndex < maxElements)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001480 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1481 SemaRef.Context, 0, Entity),
1482 IList->getLocEnd());
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001483 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001484}
1485
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001486bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1487 Expr *InitExpr,
1488 FieldDecl *Field,
1489 bool TopLevelObject) {
1490 // Handle GNU flexible array initializers.
1491 unsigned FlexArrayDiag;
1492 if (isa<InitListExpr>(InitExpr) &&
1493 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1494 // Empty flexible array init always allowed as an extension
1495 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001496 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001497 // Disallow flexible array init in C++; it is not required for gcc
1498 // compatibility, and it needs work to IRGen correctly in general.
1499 FlexArrayDiag = diag::err_flexible_array_init;
1500 } else if (!TopLevelObject) {
1501 // Disallow flexible array init on non-top-level object
1502 FlexArrayDiag = diag::err_flexible_array_init;
1503 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1504 // Disallow flexible array init on anything which is not a variable.
1505 FlexArrayDiag = diag::err_flexible_array_init;
1506 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1507 // Disallow flexible array init on local variables.
1508 FlexArrayDiag = diag::err_flexible_array_init;
1509 } else {
1510 // Allow other cases.
1511 FlexArrayDiag = diag::ext_flexible_array_init;
1512 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001513
1514 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001515 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001516 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001517 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001518 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1519 << Field;
1520 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001521
1522 return FlexArrayDiag != diag::ext_flexible_array_init;
1523}
1524
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001525void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001526 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001527 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001528 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001529 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001530 unsigned &Index,
1531 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001532 unsigned &StructuredIndex,
1533 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001534 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Eli Friedmanb85f7072008-05-19 19:16:24 +00001536 // If the record is invalid, some of it's members are invalid. To avoid
1537 // confusion, we forgo checking the intializer for the entire record.
1538 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001539 // Assume it was supposed to consume a single initializer.
1540 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001541 hadError = true;
1542 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001543 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001544
1545 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001546 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001547
1548 // If there's a default initializer, use it.
1549 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1550 if (VerifyOnly)
1551 return;
1552 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1553 Field != FieldEnd; ++Field) {
1554 if (Field->hasInClassInitializer()) {
1555 StructuredList->setInitializedFieldInUnion(*Field);
1556 // FIXME: Actually build a CXXDefaultInitExpr?
1557 return;
1558 }
1559 }
1560 }
1561
Stephen Hines176edba2014-12-01 14:53:08 -08001562 // Value-initialize the first member of the union that isn't an unnamed
1563 // bitfield.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001564 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1565 Field != FieldEnd; ++Field) {
Stephen Hines176edba2014-12-01 14:53:08 -08001566 if (!Field->isUnnamedBitfield()) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001567 if (VerifyOnly)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001568 CheckEmptyInitializable(
1569 InitializedEntity::InitializeMember(*Field, &Entity),
1570 IList->getLocEnd());
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001571 else
David Blaikie581deb32012-06-06 20:45:41 +00001572 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001573 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001574 }
1575 }
1576 return;
1577 }
1578
Douglas Gregor05c13a32009-01-22 00:58:24 +00001579 // If structDecl is a forward declaration, this loop won't do
1580 // anything except look at designated initializers; That's okay,
1581 // because an error should get printed out elsewhere. It might be
1582 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001583 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001584 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001585 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001586 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001587 while (Index < IList->getNumInits()) {
1588 Expr *Init = IList->getInit(Index);
1589
1590 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001591 // If we're not the subobject that matches up with the '{' for
1592 // the designator, we shouldn't be handling the
1593 // designator. Return immediately.
1594 if (!SubobjectIsDesignatorContext)
1595 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001596
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001597 // Handle this designated initializer. Field will be updated to
1598 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001599 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001600 DeclType, &Field, nullptr, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001601 StructuredList, StructuredIndex,
1602 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001603 hadError = true;
1604
Douglas Gregordfb5e592009-02-12 19:00:39 +00001605 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001606
1607 // Disable check for missing fields when designators are used.
1608 // This matches gcc behaviour.
1609 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001610 continue;
1611 }
1612
1613 if (Field == FieldEnd) {
1614 // We've run out of fields. We're done.
1615 break;
1616 }
1617
Douglas Gregordfb5e592009-02-12 19:00:39 +00001618 // We've already initialized a member of a union. We're done.
1619 if (InitializedSomething && DeclType->isUnionType())
1620 break;
1621
Douglas Gregor44b43212008-12-11 16:49:14 +00001622 // If we've hit the flexible array member at the end, we're done.
1623 if (Field->getType()->isIncompleteArrayType())
1624 break;
1625
Douglas Gregor0bb76892009-01-29 16:53:55 +00001626 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001627 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001628 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001629 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001630 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001631
Douglas Gregor54001c12011-06-29 21:51:31 +00001632 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001633 bool InvalidUse;
1634 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001635 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001636 else
David Blaikie581deb32012-06-06 20:45:41 +00001637 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001638 IList->getInit(Index)->getLocStart());
1639 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001640 ++Index;
1641 ++Field;
1642 hadError = true;
1643 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001644 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001645
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001646 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001647 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001648 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1649 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001650 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001651
Sebastian Redl14b0c192011-09-24 17:48:00 +00001652 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001653 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001654 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001655 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001656
1657 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001658 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001659
John McCall80639de2010-03-11 19:32:38 +00001660 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001661 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1662 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1663 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001664 // It is possible we have one or more unnamed bitfields remaining.
1665 // Find first (if any) named field and emit warning.
1666 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1667 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001668 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001669 SemaRef.Diag(IList->getSourceRange().getEnd(),
Stephen Hines651f13c2014-04-23 16:59:28 -07001670 diag::warn_missing_field_initializers) << *it;
John McCall80639de2010-03-11 19:32:38 +00001671 break;
1672 }
1673 }
1674 }
1675
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001676 // Check that any remaining fields can be value-initialized.
1677 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1678 !Field->getType()->isIncompleteArrayType()) {
1679 // FIXME: Should check for holes left by designated initializers too.
1680 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001681 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001682 CheckEmptyInitializable(
1683 InitializedEntity::InitializeMember(*Field, &Entity),
1684 IList->getLocEnd());
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001685 }
1686 }
1687
Mike Stump1eb44332009-09-09 15:08:12 +00001688 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001689 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001690 return;
1691
David Blaikie581deb32012-06-06 20:45:41 +00001692 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001693 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001694 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001695 ++Index;
1696 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001697 }
1698
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001699 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001700 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001702 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001704 StructuredList, StructuredIndex);
1705 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001706 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001707 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001708}
Steve Naroff0cca7492008-05-01 22:18:59 +00001709
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001710/// \brief Expand a field designator that refers to a member of an
1711/// anonymous struct or union into a series of field designators that
1712/// refers to the field within the appropriate subobject.
1713///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001714static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001715 DesignatedInitExpr *DIE,
1716 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001717 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001718 typedef DesignatedInitExpr::Designator Designator;
1719
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001720 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001721 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001722 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1723 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1724 if (PI + 1 == PE)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001725 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001726 DIE->getDesignator(DesigIdx)->getDotLoc(),
1727 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1728 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001729 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1730 SourceLocation(), SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001731 assert(isa<FieldDecl>(*PI));
1732 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001733 }
1734
1735 // Expand the current designator into the set of replacement
1736 // designators, so we have a full subobject path down to where the
1737 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001738 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001739 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001740}
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Sebastian Redl14b0c192011-09-24 17:48:00 +00001742static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1743 DesignatedInitExpr *DIE) {
1744 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1745 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1746 for (unsigned I = 0; I < NumIndexExprs; ++I)
1747 IndexExprs[I] = DIE->getSubExpr(I + 1);
1748 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001749 DIE->size(), IndexExprs,
1750 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001751 DIE->usesGNUSyntax(), DIE->getInit());
1752}
1753
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001754namespace {
1755
1756// Callback to only accept typo corrections that are for field members of
1757// the given struct or union.
1758class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1759 public:
1760 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1761 : Record(RD) {}
1762
Stephen Hines651f13c2014-04-23 16:59:28 -07001763 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001764 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1765 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1766 }
1767
1768 private:
1769 RecordDecl *Record;
1770};
1771
1772}
1773
Douglas Gregor05c13a32009-01-22 00:58:24 +00001774/// @brief Check the well-formedness of a C99 designated initializer.
1775///
1776/// Determines whether the designated initializer @p DIE, which
1777/// resides at the given @p Index within the initializer list @p
1778/// IList, is well-formed for a current object of type @p DeclType
1779/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001780/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001781/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001782///
1783/// @param IList The initializer list in which this designated
1784/// initializer occurs.
1785///
Douglas Gregor71199712009-04-15 04:56:10 +00001786/// @param DIE The designated initializer expression.
1787///
1788/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001789///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001790/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001791/// into which the designation in @p DIE should refer.
1792///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001793/// @param NextField If non-NULL and the first designator in @p DIE is
1794/// a field, this will be set to the field declaration corresponding
1795/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001796///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001797/// @param NextElementIndex If non-NULL and the first designator in @p
1798/// DIE is an array designator or GNU array-range designator, this
1799/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001800///
1801/// @param Index Index into @p IList where the designated initializer
1802/// @p DIE occurs.
1803///
Douglas Gregor4c678342009-01-28 21:54:33 +00001804/// @param StructuredList The initializer list expression that
1805/// describes all of the subobject initializers in the order they'll
1806/// actually be initialized.
1807///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001808/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001809bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001810InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001811 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001812 DesignatedInitExpr *DIE,
1813 unsigned DesigIdx,
1814 QualType &CurrentObjectType,
1815 RecordDecl::field_iterator *NextField,
1816 llvm::APSInt *NextElementIndex,
1817 unsigned &Index,
1818 InitListExpr *StructuredList,
1819 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001820 bool FinishSubobjectInit,
1821 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001822 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001823 // Check the actual initialization for the designated object type.
1824 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001825
1826 // Temporarily remove the designator expression from the
1827 // initializer list that the child calls see, so that we don't try
1828 // to re-process the designator.
1829 unsigned OldIndex = Index;
1830 IList->setInit(OldIndex, DIE->getInit());
1831
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001832 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001833 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001834
1835 // Restore the designated initializer expression in the syntactic
1836 // form of the initializer list.
1837 if (IList->getInit(OldIndex) != DIE->getInit())
1838 DIE->setInit(IList->getInit(OldIndex));
1839 IList->setInit(OldIndex, DIE);
1840
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001841 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001842 }
1843
Douglas Gregor71199712009-04-15 04:56:10 +00001844 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001845 bool IsFirstDesignator = (DesigIdx == 0);
1846 if (!VerifyOnly) {
1847 assert((IsFirstDesignator || StructuredList) &&
1848 "Need a non-designated initializer list to start from");
1849
1850 // Determine the structural initializer list that corresponds to the
1851 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001852 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001853 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1854 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001855 SourceRange(D->getLocStart(),
1856 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001857 assert(StructuredList && "Expected a structured initializer list");
1858 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001859
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001860 if (D->isFieldDesignator()) {
1861 // C99 6.7.8p7:
1862 //
1863 // If a designator has the form
1864 //
1865 // . identifier
1866 //
1867 // then the current object (defined below) shall have
1868 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001869 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001870 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001871 if (!RT) {
1872 SourceLocation Loc = D->getDotLoc();
1873 if (Loc.isInvalid())
1874 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001875 if (!VerifyOnly)
1876 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001877 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001878 ++Index;
1879 return true;
1880 }
1881
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001882 FieldDecl *KnownField = D->getField();
Stephen Hines176edba2014-12-01 14:53:08 -08001883 if (!KnownField) {
1884 IdentifierInfo *FieldName = D->getFieldName();
1885 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1886 for (NamedDecl *ND : Lookup) {
1887 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
1888 KnownField = FD;
1889 break;
1890 }
1891 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001892 // In verify mode, don't modify the original.
1893 if (VerifyOnly)
1894 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Stephen Hines176edba2014-12-01 14:53:08 -08001895 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Picheta0e27f02010-12-22 03:46:10 +00001896 D = DIE->getDesignator(DesigIdx);
Stephen Hines176edba2014-12-01 14:53:08 -08001897 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Picheta0e27f02010-12-22 03:46:10 +00001898 break;
1899 }
1900 }
Stephen Hines176edba2014-12-01 14:53:08 -08001901 if (!KnownField) {
1902 if (VerifyOnly) {
1903 ++Index;
1904 return true; // No typo correction when just trying this out.
1905 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001906
Stephen Hines176edba2014-12-01 14:53:08 -08001907 // Name lookup found something, but it wasn't a field.
1908 if (!Lookup.empty()) {
1909 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1910 << FieldName;
1911 SemaRef.Diag(Lookup.front()->getLocation(),
1912 diag::note_field_designator_found);
1913 ++Index;
1914 return true;
1915 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001916
Stephen Hines176edba2014-12-01 14:53:08 -08001917 // Name lookup didn't find anything.
1918 // Determine whether this was a typo for another field name.
Richard Smith2d670972013-08-17 00:46:16 +00001919 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1920 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Stephen Hines176edba2014-12-01 14:53:08 -08001921 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
1922 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
1923 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smith2d670972013-08-17 00:46:16 +00001924 SemaRef.diagnoseTypo(
1925 Corrected,
1926 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
Stephen Hines176edba2014-12-01 14:53:08 -08001927 << FieldName << CurrentObjectType);
1928 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramera41ee492011-09-25 02:41:26 +00001929 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001930 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08001931 // Typo correction didn't find anything.
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001932 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1933 << FieldName << CurrentObjectType;
1934 ++Index;
1935 return true;
1936 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001937 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001938 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001939
Stephen Hines176edba2014-12-01 14:53:08 -08001940 unsigned FieldIndex = 0;
1941 for (auto *FI : RT->getDecl()->fields()) {
1942 if (FI->isUnnamedBitfield())
1943 continue;
1944 if (KnownField == FI)
1945 break;
1946 ++FieldIndex;
1947 }
1948
1949 RecordDecl::field_iterator Field =
1950 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
1951
Douglas Gregor4c678342009-01-28 21:54:33 +00001952 // All of the fields of a union are located at the same place in
1953 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001954 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001955 FieldIndex = 0;
Matthew Curtis4e499522013-10-03 12:14:24 +00001956 if (!VerifyOnly) {
1957 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1958 if (CurrentField && CurrentField != *Field) {
1959 assert(StructuredList->getNumInits() == 1
1960 && "A union should never have more than one initializer!");
1961
1962 // we're about to throw away an initializer, emit warning
1963 SemaRef.Diag(D->getFieldLoc(),
1964 diag::warn_initializer_overrides)
1965 << D->getSourceRange();
1966 Expr *ExistingInit = StructuredList->getInit(0);
1967 SemaRef.Diag(ExistingInit->getLocStart(),
1968 diag::note_previous_initializer)
1969 << /*FIXME:has side effects=*/0
1970 << ExistingInit->getSourceRange();
1971
1972 // remove existing initializer
1973 StructuredList->resizeInits(SemaRef.Context, 0);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001974 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis4e499522013-10-03 12:14:24 +00001975 }
1976
David Blaikie581deb32012-06-06 20:45:41 +00001977 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis4e499522013-10-03 12:14:24 +00001978 }
Douglas Gregor0bb76892009-01-29 16:53:55 +00001979 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001980
Douglas Gregor54001c12011-06-29 21:51:31 +00001981 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001982 bool InvalidUse;
1983 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001984 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001985 else
David Blaikie581deb32012-06-06 20:45:41 +00001986 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001987 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001988 ++Index;
1989 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001990 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001991
Sebastian Redl14b0c192011-09-24 17:48:00 +00001992 if (!VerifyOnly) {
1993 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001994 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Sebastian Redl14b0c192011-09-24 17:48:00 +00001996 // Make sure that our non-designated initializer list has space
1997 // for a subobject corresponding to this field.
1998 if (FieldIndex >= StructuredList->getNumInits())
1999 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2000 }
Douglas Gregor4c678342009-01-28 21:54:33 +00002001
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002002 // This designator names a flexible array member.
2003 if (Field->getType()->isIncompleteArrayType()) {
2004 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00002005 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002006 // We can't designate an object within the flexible array
2007 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00002008 if (!VerifyOnly) {
2009 DesignatedInitExpr::Designator *NextD
2010 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00002011 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002012 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00002013 << SourceRange(NextD->getLocStart(),
2014 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00002015 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00002016 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002017 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002018 Invalid = true;
2019 }
2020
Chris Lattner9046c222010-10-10 17:49:49 +00002021 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2022 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002023 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002024 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002025 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002026 diag::err_flexible_array_init_needs_braces)
2027 << DIE->getInit()->getSourceRange();
2028 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00002029 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002030 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002031 Invalid = true;
2032 }
2033
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00002034 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00002035 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00002036 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002037 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002038
2039 if (Invalid) {
2040 ++Index;
2041 return true;
2042 }
2043
2044 // Initialize the array.
2045 bool prevHadError = hadError;
2046 unsigned newStructuredIndex = FieldIndex;
2047 unsigned OldIndex = Index;
2048 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002049
2050 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00002051 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002052 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002053 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002054
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002055 IList->setInit(OldIndex, DIE);
2056 if (hadError && !prevHadError) {
2057 ++Field;
2058 ++FieldIndex;
2059 if (NextField)
2060 *NextField = Field;
2061 StructuredIndex = FieldIndex;
2062 return true;
2063 }
2064 } else {
2065 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00002066 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002067 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002068
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002069 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00002070 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002071 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002072 FieldType, nullptr, nullptr, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002073 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002074 true, false))
2075 return true;
2076 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002077
2078 // Find the position of the next field to be initialized in this
2079 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002080 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00002081 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002082
2083 // If this the first designator, our caller will continue checking
2084 // the rest of this struct/class/union subobject.
2085 if (IsFirstDesignator) {
2086 if (NextField)
2087 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00002088 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002089 return false;
2090 }
2091
Douglas Gregor34e79462009-01-28 23:36:17 +00002092 if (!FinishSubobjectInit)
2093 return false;
2094
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002095 // We've already initialized something in the union; we're done.
2096 if (RT->getDecl()->isUnion())
2097 return hadError;
2098
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002099 // Check the remaining fields within this class/struct/union subobject.
2100 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002101
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002102 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002103 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002104 return hadError && !prevHadError;
2105 }
2106
2107 // C99 6.7.8p6:
2108 //
2109 // If a designator has the form
2110 //
2111 // [ constant-expression ]
2112 //
2113 // then the current object (defined below) shall have array
2114 // type and the expression shall be an integer constant
2115 // expression. If the array is of unknown size, any
2116 // nonnegative value is valid.
2117 //
2118 // Additionally, cope with the GNU extension that permits
2119 // designators of the form
2120 //
2121 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002122 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002123 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002124 if (!VerifyOnly)
2125 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2126 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002127 ++Index;
2128 return true;
2129 }
2130
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002131 Expr *IndexExpr = nullptr;
Douglas Gregor34e79462009-01-28 23:36:17 +00002132 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2133 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002134 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002135 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002136 DesignatedEndIndex = DesignatedStartIndex;
2137 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002138 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002139
Mike Stump1eb44332009-09-09 15:08:12 +00002140 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002141 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002142 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002143 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002144 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002145
Chris Lattnere0fd8322011-02-19 22:28:58 +00002146 // Codegen can't handle evaluating array range designators that have side
2147 // effects, because we replicate the AST value for each initialized element.
2148 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2149 // elements with something that has a side effect, so codegen can emit an
2150 // "error unsupported" error instead of miscompiling the app.
2151 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002152 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002153 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002154 }
2155
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002156 if (isa<ConstantArrayType>(AT)) {
2157 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002158 DesignatedStartIndex
2159 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002160 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002161 DesignatedEndIndex
2162 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002163 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2164 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002165 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002166 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002167 diag::err_array_designator_too_large)
2168 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2169 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002170 ++Index;
2171 return true;
2172 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002173 } else {
2174 // Make sure the bit-widths and signedness match.
2175 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002176 DesignatedEndIndex
2177 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002178 else if (DesignatedStartIndex.getBitWidth() <
2179 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002180 DesignatedStartIndex
2181 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002182 DesignatedStartIndex.setIsUnsigned(true);
2183 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002184 }
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Eli Friedman188ddb12013-06-11 21:48:11 +00002186 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2187 // We're modifying a string literal init; we have to decompose the string
2188 // so we can modify the individual characters.
2189 ASTContext &Context = SemaRef.Context;
2190 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2191
2192 // Compute the character type
2193 QualType CharTy = AT->getElementType();
2194
2195 // Compute the type of the integer literals.
2196 QualType PromotedCharTy = CharTy;
2197 if (CharTy->isPromotableIntegerType())
2198 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2199 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2200
2201 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2202 // Get the length of the string.
2203 uint64_t StrLen = SL->getLength();
2204 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2205 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2206 StructuredList->resizeInits(Context, StrLen);
2207
2208 // Build a literal for each character in the string, and put them into
2209 // the init list.
2210 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2211 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2212 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002213 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002214 if (CharTy != PromotedCharTy)
2215 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002216 Init, nullptr, VK_RValue);
Eli Friedman188ddb12013-06-11 21:48:11 +00002217 StructuredList->updateInit(Context, i, Init);
2218 }
2219 } else {
2220 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2221 std::string Str;
2222 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2223
2224 // Get the length of the string.
2225 uint64_t StrLen = Str.size();
2226 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2227 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2228 StructuredList->resizeInits(Context, StrLen);
2229
2230 // Build a literal for each character in the string, and put them into
2231 // the init list.
2232 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2233 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2234 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002235 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002236 if (CharTy != PromotedCharTy)
2237 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002238 Init, nullptr, VK_RValue);
Eli Friedman188ddb12013-06-11 21:48:11 +00002239 StructuredList->updateInit(Context, i, Init);
2240 }
2241 }
2242 }
2243
Douglas Gregor4c678342009-01-28 21:54:33 +00002244 // Make sure that our non-designated initializer list has space
2245 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002246 if (!VerifyOnly &&
2247 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002248 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002249 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002250
Douglas Gregor34e79462009-01-28 23:36:17 +00002251 // Repeatedly perform subobject initializations in the range
2252 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002253
Douglas Gregor34e79462009-01-28 23:36:17 +00002254 // Move to the next designator
2255 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2256 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002257
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002258 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002259 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002260
Douglas Gregor34e79462009-01-28 23:36:17 +00002261 while (DesignatedStartIndex <= DesignatedEndIndex) {
2262 // Recurse to check later designated subobjects.
2263 QualType ElementType = AT->getElementType();
2264 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002265
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002266 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002267 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002268 ElementType, nullptr, nullptr, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002269 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002270 (DesignatedStartIndex == DesignatedEndIndex),
2271 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002272 return true;
2273
2274 // Move to the next index in the array that we'll be initializing.
2275 ++DesignatedStartIndex;
2276 ElementIndex = DesignatedStartIndex.getZExtValue();
2277 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002278
2279 // If this the first designator, our caller will continue checking
2280 // the rest of this array subobject.
2281 if (IsFirstDesignator) {
2282 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002283 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002284 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002285 return false;
2286 }
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Douglas Gregor34e79462009-01-28 23:36:17 +00002288 if (!FinishSubobjectInit)
2289 return false;
2290
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002291 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002292 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002293 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002294 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002295 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002296 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002297}
2298
Douglas Gregor4c678342009-01-28 21:54:33 +00002299// Get the structured initializer list for a subobject of type
2300// @p CurrentObjectType.
2301InitListExpr *
2302InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2303 QualType CurrentObjectType,
2304 InitListExpr *StructuredList,
2305 unsigned StructuredIndex,
2306 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002307 if (VerifyOnly)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002308 return nullptr; // No structured list in verification-only mode.
2309 Expr *ExistingInit = nullptr;
Douglas Gregor4c678342009-01-28 21:54:33 +00002310 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002311 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002312 else if (StructuredIndex < StructuredList->getNumInits())
2313 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Douglas Gregor4c678342009-01-28 21:54:33 +00002315 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2316 return Result;
2317
2318 if (ExistingInit) {
2319 // We are creating an initializer list that initializes the
2320 // subobjects of the current object, but there was already an
2321 // initialization that completely initialized the current
2322 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002323 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002324 // struct X { int a, b; };
2325 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002326 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002327 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2328 // designated initializer re-initializes the whole
2329 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002330 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002331 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002332 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002333 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002334 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002335 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002336 << ExistingInit->getSourceRange();
2337 }
2338
Mike Stump1eb44332009-09-09 15:08:12 +00002339 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002340 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002341 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002342 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002343
Eli Friedman5c89c392012-02-23 02:25:10 +00002344 QualType ResultType = CurrentObjectType;
2345 if (!ResultType->isArrayType())
2346 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2347 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002348
Douglas Gregorfa219202009-03-20 23:58:33 +00002349 // Pre-allocate storage for the structured initializer list.
2350 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002351 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002352 bool GotNumInits = false;
2353 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002354 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002355 GotNumInits = true;
2356 } else if (Index < IList->getNumInits()) {
2357 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002358 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002359 GotNumInits = true;
2360 }
Douglas Gregor08457732009-03-21 18:13:52 +00002361 }
2362
Mike Stump1eb44332009-09-09 15:08:12 +00002363 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002364 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2365 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2366 NumElements = CAType->getSize().getZExtValue();
2367 // Simple heuristic so that we don't allocate a very large
2368 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002369 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002370 NumElements = 0;
2371 }
John McCall183700f2009-09-21 23:43:11 +00002372 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002373 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002374 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002375 RecordDecl *RDecl = RType->getDecl();
2376 if (RDecl->isUnion())
2377 NumElements = 1;
2378 else
Stephen Hines651f13c2014-04-23 16:59:28 -07002379 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002380 }
2381
Ted Kremenek709210f2010-04-13 23:39:13 +00002382 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002383
Douglas Gregor4c678342009-01-28 21:54:33 +00002384 // Link this new initializer list into the structured initializer
2385 // lists.
2386 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002387 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002388 else {
2389 Result->setSyntacticForm(IList);
2390 SyntacticToSemantic[IList] = Result;
2391 }
2392
2393 return Result;
2394}
2395
2396/// Update the initializer at index @p StructuredIndex within the
2397/// structured initializer list to the value @p expr.
2398void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2399 unsigned &StructuredIndex,
2400 Expr *expr) {
2401 // No structured initializer list to update
2402 if (!StructuredList)
2403 return;
2404
Ted Kremenek709210f2010-04-13 23:39:13 +00002405 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2406 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002407 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002408 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002409 diag::warn_initializer_overrides)
2410 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002411 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002412 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002413 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002414 << PrevInit->getSourceRange();
2415 }
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Douglas Gregor4c678342009-01-28 21:54:33 +00002417 ++StructuredIndex;
2418}
2419
Douglas Gregor05c13a32009-01-22 00:58:24 +00002420/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002421/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002422/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002423/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002424/// failure. Returns the index expression, possibly with an implicit cast
2425/// added, on success. If everything went okay, Value will receive the
2426/// value of the constant expression.
2427static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002428CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002429 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002430
2431 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002432 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2433 if (Result.isInvalid())
2434 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002435
Chris Lattner3bf68932009-04-25 21:59:05 +00002436 if (Value.isSigned() && Value.isNegative())
2437 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002438 << Value.toString(10) << Index->getSourceRange();
2439
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002440 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002441 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002442}
2443
John McCall60d7b3a2010-08-24 06:29:42 +00002444ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002445 SourceLocation Loc,
2446 bool GNUSyntax,
2447 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002448 typedef DesignatedInitExpr::Designator ASTDesignator;
2449
2450 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002451 SmallVector<ASTDesignator, 32> Designators;
2452 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002453
2454 // Build designators and check array designator expressions.
2455 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2456 const Designator &D = Desig.getDesignator(Idx);
2457 switch (D.getKind()) {
2458 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002459 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002460 D.getFieldLoc()));
2461 break;
2462
2463 case Designator::ArrayDesignator: {
2464 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2465 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002466 if (!Index->isTypeDependent() && !Index->isValueDependent())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002467 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smith282e7e62012-02-04 09:53:13 +00002468 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002469 Invalid = true;
2470 else {
2471 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002472 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002473 D.getRBracketLoc()));
2474 InitExpressions.push_back(Index);
2475 }
2476 break;
2477 }
2478
2479 case Designator::ArrayRangeDesignator: {
2480 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2481 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2482 llvm::APSInt StartValue;
2483 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002484 bool StartDependent = StartIndex->isTypeDependent() ||
2485 StartIndex->isValueDependent();
2486 bool EndDependent = EndIndex->isTypeDependent() ||
2487 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002488 if (!StartDependent)
2489 StartIndex =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002490 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smith282e7e62012-02-04 09:53:13 +00002491 if (!EndDependent)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002492 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smith282e7e62012-02-04 09:53:13 +00002493
2494 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002495 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002496 else {
2497 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002498 if (StartDependent || EndDependent) {
2499 // Nothing to compute.
2500 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002501 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002502 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002503 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002504
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002505 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002506 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002507 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002508 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2509 Invalid = true;
2510 } else {
2511 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002512 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002513 D.getEllipsisLoc(),
2514 D.getRBracketLoc()));
2515 InitExpressions.push_back(StartIndex);
2516 InitExpressions.push_back(EndIndex);
2517 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002518 }
2519 break;
2520 }
2521 }
2522 }
2523
2524 if (Invalid || Init.isInvalid())
2525 return ExprError();
2526
2527 // Clear out the expressions within the designation.
2528 Desig.ClearExprs(*this);
2529
2530 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002531 = DesignatedInitExpr::Create(Context,
2532 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002533 InitExpressions, Loc, GNUSyntax,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002534 Init.getAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002535
David Blaikie4e4d0842012-03-11 07:00:24 +00002536 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002537 Diag(DIE->getLocStart(), diag::ext_designated_init)
2538 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002539
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002540 return DIE;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002541}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002542
Douglas Gregor20093b42009-12-09 23:02:17 +00002543//===----------------------------------------------------------------------===//
2544// Initialization entity
2545//===----------------------------------------------------------------------===//
2546
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002547InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002548 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002549 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002550{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002551 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2552 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002553 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002554 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002555 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002556 Type = VT->getElementType();
2557 } else {
2558 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2559 assert(CT && "Unexpected type");
2560 Kind = EK_ComplexElement;
2561 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002562 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002563}
2564
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002565InitializedEntity
2566InitializedEntity::InitializeBase(ASTContext &Context,
2567 const CXXBaseSpecifier *Base,
2568 bool IsInheritedVirtualBase) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002569 InitializedEntity Result;
2570 Result.Kind = EK_Base;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002571 Result.Parent = nullptr;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002572 Result.Base = reinterpret_cast<uintptr_t>(Base);
2573 if (IsInheritedVirtualBase)
2574 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002575
Douglas Gregord6542d82009-12-22 15:35:07 +00002576 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002577 return Result;
2578}
2579
Douglas Gregor99a2e602009-12-16 01:38:02 +00002580DeclarationName InitializedEntity::getName() const {
2581 switch (getKind()) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002582 case EK_Parameter:
2583 case EK_Parameter_CF_Audited: {
John McCallf85e1932011-06-15 23:02:42 +00002584 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2585 return (D ? D->getDeclName() : DeclarationName());
2586 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002587
2588 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002589 case EK_Member:
2590 return VariableOrMember->getDeclName();
2591
Douglas Gregor47736542012-02-15 16:57:26 +00002592 case EK_LambdaCapture:
Bill Wendling2434dcf2013-12-05 05:25:04 +00002593 return DeclarationName(Capture.VarID);
Douglas Gregor47736542012-02-15 16:57:26 +00002594
Douglas Gregor99a2e602009-12-16 01:38:02 +00002595 case EK_Result:
2596 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002597 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002598 case EK_Temporary:
2599 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002600 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002601 case EK_ArrayElement:
2602 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002603 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002604 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002605 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002606 case EK_RelatedResult:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002607 return DeclarationName();
2608 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002609
David Blaikie7530c032012-01-17 06:56:22 +00002610 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002611}
2612
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002613DeclaratorDecl *InitializedEntity::getDecl() const {
2614 switch (getKind()) {
2615 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002616 case EK_Member:
2617 return VariableOrMember;
2618
John McCallf85e1932011-06-15 23:02:42 +00002619 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002620 case EK_Parameter_CF_Audited:
John McCallf85e1932011-06-15 23:02:42 +00002621 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2622
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002623 case EK_Result:
2624 case EK_Exception:
2625 case EK_New:
2626 case EK_Temporary:
2627 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002628 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002629 case EK_ArrayElement:
2630 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002631 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002632 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002633 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002634 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002635 case EK_RelatedResult:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002636 return nullptr;
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002637 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002638
David Blaikie7530c032012-01-17 06:56:22 +00002639 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002640}
2641
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002642bool InitializedEntity::allowsNRVO() const {
2643 switch (getKind()) {
2644 case EK_Result:
2645 case EK_Exception:
2646 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002647
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002648 case EK_Variable:
2649 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002650 case EK_Parameter_CF_Audited:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002651 case EK_Member:
2652 case EK_New:
2653 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002654 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002655 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002656 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002657 case EK_ArrayElement:
2658 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002659 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002660 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002661 case EK_LambdaCapture:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002662 case EK_RelatedResult:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002663 break;
2664 }
2665
2666 return false;
2667}
2668
Richard Smith211c8dd2013-06-05 00:46:14 +00002669unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smitha4bb99c2013-06-12 21:51:50 +00002670 assert(getParent() != this);
Richard Smith211c8dd2013-06-05 00:46:14 +00002671 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2672 for (unsigned I = 0; I != Depth; ++I)
2673 OS << "`-";
2674
2675 switch (getKind()) {
2676 case EK_Variable: OS << "Variable"; break;
2677 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002678 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2679 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002680 case EK_Result: OS << "Result"; break;
2681 case EK_Exception: OS << "Exception"; break;
2682 case EK_Member: OS << "Member"; break;
2683 case EK_New: OS << "New"; break;
2684 case EK_Temporary: OS << "Temporary"; break;
2685 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002686 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002687 case EK_Base: OS << "Base"; break;
2688 case EK_Delegating: OS << "Delegating"; break;
2689 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2690 case EK_VectorElement: OS << "VectorElement " << Index; break;
2691 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2692 case EK_BlockElement: OS << "Block"; break;
2693 case EK_LambdaCapture:
2694 OS << "LambdaCapture ";
Bill Wendling2434dcf2013-12-05 05:25:04 +00002695 OS << DeclarationName(Capture.VarID);
Richard Smith211c8dd2013-06-05 00:46:14 +00002696 break;
2697 }
2698
2699 if (Decl *D = getDecl()) {
2700 OS << " ";
2701 cast<NamedDecl>(D)->printQualifiedName(OS);
2702 }
2703
2704 OS << " '" << getType().getAsString() << "'\n";
2705
2706 return Depth + 1;
2707}
2708
2709void InitializedEntity::dump() const {
2710 dumpImpl(llvm::errs());
2711}
2712
Douglas Gregor20093b42009-12-09 23:02:17 +00002713//===----------------------------------------------------------------------===//
2714// Initialization sequence
2715//===----------------------------------------------------------------------===//
2716
2717void InitializationSequence::Step::Destroy() {
2718 switch (Kind) {
2719 case SK_ResolveAddressOfOverloadedFunction:
2720 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002721 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002722 case SK_CastDerivedToBaseLValue:
2723 case SK_BindReference:
2724 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002725 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002726 case SK_UserConversion:
2727 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002728 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002729 case SK_QualificationConversionLValue:
Stephen Hines176edba2014-12-01 14:53:08 -08002730 case SK_AtomicConversion:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002731 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002732 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002733 case SK_UnwrapInitList:
2734 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002735 case SK_ConstructorInitialization:
Stephen Hines176edba2014-12-01 14:53:08 -08002736 case SK_ConstructorInitializationFromList:
Douglas Gregor71d17402009-12-15 00:01:57 +00002737 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002738 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002739 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002740 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002741 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002742 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002743 case SK_PassByIndirectCopyRestore:
2744 case SK_PassByIndirectRestore:
2745 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002746 case SK_StdInitializerList:
Stephen Hines176edba2014-12-01 14:53:08 -08002747 case SK_StdInitializerListConstructorCall:
Guy Benyei21f18c42013-02-07 10:55:47 +00002748 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002749 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002750 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002751
Douglas Gregor20093b42009-12-09 23:02:17 +00002752 case SK_ConversionSequence:
Richard Smith13b228d2013-09-21 21:19:19 +00002753 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor20093b42009-12-09 23:02:17 +00002754 delete ICS;
2755 }
2756}
2757
Douglas Gregorb70cf442010-03-26 20:14:36 +00002758bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002759 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002760}
2761
2762bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002763 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002764 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002765
Douglas Gregorb70cf442010-03-26 20:14:36 +00002766 switch (getFailureKind()) {
2767 case FK_TooManyInitsForReference:
2768 case FK_ArrayNeedsInitList:
2769 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002770 case FK_ArrayNeedsInitListOrWideStringLiteral:
2771 case FK_NarrowStringIntoWideCharArray:
2772 case FK_WideStringIntoCharArray:
2773 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002774 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2775 case FK_NonConstLValueReferenceBindingToTemporary:
2776 case FK_NonConstLValueReferenceBindingToUnrelated:
2777 case FK_RValueReferenceBindingToLValue:
2778 case FK_ReferenceInitDropsQualifiers:
2779 case FK_ReferenceInitFailed:
2780 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002781 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002782 case FK_TooManyInitsForScalar:
2783 case FK_ReferenceBindingToInitList:
2784 case FK_InitListBadDestinationType:
2785 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002786 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002787 case FK_ArrayTypeMismatch:
2788 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002789 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002790 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002791 case FK_PlaceholderType:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002792 case FK_ExplicitConstructor:
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 case FK_ReferenceInitOverloadFailed:
2796 case FK_UserConversionOverloadFailed:
2797 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002798 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002799 return FailedOverloadResult == OR_Ambiguous;
2800 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002801
David Blaikie7530c032012-01-17 06:56:22 +00002802 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002803}
2804
Douglas Gregord6e44a32010-04-16 22:09:46 +00002805bool InitializationSequence::isConstructorInitialization() const {
2806 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2807}
2808
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002809void
2810InitializationSequence
2811::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2812 DeclAccessPair Found,
2813 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002814 Step S;
2815 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2816 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002817 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002818 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002819 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002820 Steps.push_back(S);
2821}
2822
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002823void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002824 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002825 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002826 switch (VK) {
2827 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2828 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2829 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002830 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002831 S.Type = BaseType;
2832 Steps.push_back(S);
2833}
2834
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002835void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002836 bool BindingTemporary) {
2837 Step S;
2838 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2839 S.Type = T;
2840 Steps.push_back(S);
2841}
2842
Douglas Gregor523d46a2010-04-18 07:40:54 +00002843void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2844 Step S;
2845 S.Kind = SK_ExtraneousCopyToTemporary;
2846 S.Type = T;
2847 Steps.push_back(S);
2848}
2849
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002850void
2851InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2852 DeclAccessPair FoundDecl,
2853 QualType T,
2854 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002855 Step S;
2856 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002857 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002858 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002859 S.Function.Function = Function;
2860 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002861 Steps.push_back(S);
2862}
2863
2864void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002865 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002866 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002867 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002868 switch (VK) {
2869 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002870 S.Kind = SK_QualificationConversionRValue;
2871 break;
John McCall5baba9d2010-08-25 10:28:54 +00002872 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002873 S.Kind = SK_QualificationConversionXValue;
2874 break;
John McCall5baba9d2010-08-25 10:28:54 +00002875 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002876 S.Kind = SK_QualificationConversionLValue;
2877 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002878 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002879 S.Type = Ty;
2880 Steps.push_back(S);
2881}
2882
Stephen Hines176edba2014-12-01 14:53:08 -08002883void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
2884 Step S;
2885 S.Kind = SK_AtomicConversion;
2886 S.Type = Ty;
2887 Steps.push_back(S);
2888}
2889
Jordan Rose1fd1e282013-04-11 00:58:58 +00002890void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2891 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2892
2893 Step S;
2894 S.Kind = SK_LValueToRValue;
2895 S.Type = Ty;
2896 Steps.push_back(S);
2897}
2898
Douglas Gregor20093b42009-12-09 23:02:17 +00002899void InitializationSequence::AddConversionSequenceStep(
Richard Smith13b228d2013-09-21 21:19:19 +00002900 const ImplicitConversionSequence &ICS, QualType T,
2901 bool TopLevelOfInitList) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002902 Step S;
Richard Smith13b228d2013-09-21 21:19:19 +00002903 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2904 : SK_ConversionSequence;
Douglas Gregor20093b42009-12-09 23:02:17 +00002905 S.Type = T;
2906 S.ICS = new ImplicitConversionSequence(ICS);
2907 Steps.push_back(S);
2908}
2909
Douglas Gregord87b61f2009-12-10 17:56:55 +00002910void InitializationSequence::AddListInitializationStep(QualType T) {
2911 Step S;
2912 S.Kind = SK_ListInitialization;
2913 S.Type = T;
2914 Steps.push_back(S);
2915}
2916
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002917void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002918InitializationSequence
2919::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2920 AccessSpecifier Access,
2921 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002922 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002923 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002924 Step S;
Stephen Hines176edba2014-12-01 14:53:08 -08002925 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
2926 : SK_ConstructorInitializationFromList
2927 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002928 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002929 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002930 S.Function.Function = Constructor;
2931 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002932 Steps.push_back(S);
2933}
2934
Douglas Gregor71d17402009-12-15 00:01:57 +00002935void InitializationSequence::AddZeroInitializationStep(QualType T) {
2936 Step S;
2937 S.Kind = SK_ZeroInitialization;
2938 S.Type = T;
2939 Steps.push_back(S);
2940}
2941
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002942void InitializationSequence::AddCAssignmentStep(QualType T) {
2943 Step S;
2944 S.Kind = SK_CAssignment;
2945 S.Type = T;
2946 Steps.push_back(S);
2947}
2948
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002949void InitializationSequence::AddStringInitStep(QualType T) {
2950 Step S;
2951 S.Kind = SK_StringInit;
2952 S.Type = T;
2953 Steps.push_back(S);
2954}
2955
Douglas Gregor569c3162010-08-07 11:51:51 +00002956void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2957 Step S;
2958 S.Kind = SK_ObjCObjectConversion;
2959 S.Type = T;
2960 Steps.push_back(S);
2961}
2962
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002963void InitializationSequence::AddArrayInitStep(QualType T) {
2964 Step S;
2965 S.Kind = SK_ArrayInit;
2966 S.Type = T;
2967 Steps.push_back(S);
2968}
2969
Richard Smith0f163e92012-02-15 22:38:09 +00002970void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2971 Step S;
2972 S.Kind = SK_ParenthesizedArrayInit;
2973 S.Type = T;
2974 Steps.push_back(S);
2975}
2976
John McCallf85e1932011-06-15 23:02:42 +00002977void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2978 bool shouldCopy) {
2979 Step s;
2980 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2981 : SK_PassByIndirectRestore);
2982 s.Type = type;
2983 Steps.push_back(s);
2984}
2985
2986void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2987 Step S;
2988 S.Kind = SK_ProduceObjCObject;
2989 S.Type = T;
2990 Steps.push_back(S);
2991}
2992
Sebastian Redl2b916b82012-01-17 22:49:42 +00002993void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2994 Step S;
2995 S.Kind = SK_StdInitializerList;
2996 S.Type = T;
2997 Steps.push_back(S);
2998}
2999
Guy Benyei21f18c42013-02-07 10:55:47 +00003000void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3001 Step S;
3002 S.Kind = SK_OCLSamplerInit;
3003 S.Type = T;
3004 Steps.push_back(S);
3005}
3006
Guy Benyeie6b9d802013-01-20 12:31:11 +00003007void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3008 Step S;
3009 S.Kind = SK_OCLZeroEvent;
3010 S.Type = T;
3011 Steps.push_back(S);
3012}
3013
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003014void InitializationSequence::RewrapReferenceInitList(QualType T,
3015 InitListExpr *Syntactic) {
3016 assert(Syntactic->getNumInits() == 1 &&
3017 "Can only rewrap trivial init lists.");
3018 Step S;
3019 S.Kind = SK_UnwrapInitList;
3020 S.Type = Syntactic->getInit(0)->getType();
3021 Steps.insert(Steps.begin(), S);
3022
3023 S.Kind = SK_RewrapInitList;
3024 S.Type = T;
3025 S.WrappingSyntacticList = Syntactic;
3026 Steps.push_back(S);
3027}
3028
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003029void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00003030 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00003031 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00003032 this->Failure = Failure;
3033 this->FailedOverloadResult = Result;
3034}
3035
3036//===----------------------------------------------------------------------===//
3037// Attempt initialization
3038//===----------------------------------------------------------------------===//
3039
John McCallf85e1932011-06-15 23:02:42 +00003040static void MaybeProduceObjCObject(Sema &S,
3041 InitializationSequence &Sequence,
3042 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003043 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00003044
3045 /// When initializing a parameter, produce the value if it's marked
3046 /// __attribute__((ns_consumed)).
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00003047 if (Entity.isParameterKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003048 if (!Entity.isParameterConsumed())
3049 return;
3050
3051 assert(Entity.getType()->isObjCRetainableType() &&
3052 "consuming an object of unretainable type?");
3053 Sequence.AddProduceObjCObjectStep(Entity.getType());
3054
3055 /// When initializing a return value, if the return type is a
3056 /// retainable type, then returns need to immediately retain the
3057 /// object. If an autorelease is required, it will be done at the
3058 /// last instant.
3059 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3060 if (!Entity.getType()->isObjCRetainableType())
3061 return;
3062
3063 Sequence.AddProduceObjCObjectStep(Entity.getType());
3064 }
3065}
3066
Richard Smith7c3e6152013-06-12 22:31:48 +00003067static void TryListInitialization(Sema &S,
3068 const InitializedEntity &Entity,
3069 const InitializationKind &Kind,
3070 InitListExpr *InitList,
3071 InitializationSequence &Sequence);
3072
Richard Smithf4bb8d02012-07-05 08:39:21 +00003073/// \brief When initializing from init list via constructor, handle
3074/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00003075///
Richard Smithf4bb8d02012-07-05 08:39:21 +00003076/// \return true if we have handled initialization of an object of type
3077/// std::initializer_list<T>, false otherwise.
3078static bool TryInitializerListConstruction(Sema &S,
3079 InitListExpr *List,
3080 QualType DestType,
3081 InitializationSequence &Sequence) {
3082 QualType E;
3083 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00003084 return false;
3085
Richard Smith7c3e6152013-06-12 22:31:48 +00003086 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3087 Sequence.setIncompleteTypeFailure(E);
3088 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003089 }
Richard Smith7c3e6152013-06-12 22:31:48 +00003090
3091 // Try initializing a temporary array from the init list.
3092 QualType ArrayType = S.Context.getConstantArrayType(
3093 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3094 List->getNumInits()),
3095 clang::ArrayType::Normal, 0);
3096 InitializedEntity HiddenArray =
3097 InitializedEntity::InitializeTemporary(ArrayType);
3098 InitializationKind Kind =
3099 InitializationKind::CreateDirectList(List->getExprLoc());
3100 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3101 if (Sequence)
3102 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003103 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003104}
3105
Sebastian Redl96715b22012-02-04 21:27:39 +00003106static OverloadingResult
3107ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003108 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00003109 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003110 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00003111 OverloadCandidateSet::iterator &Best,
3112 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003113 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003114 CandidateSet.clear();
3115
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003116 for (ArrayRef<NamedDecl *>::iterator
3117 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003118 NamedDecl *D = *Con;
3119 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3120 bool SuppressUserConversions = false;
3121
3122 // Find the constructor (which may be a template).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003123 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl96715b22012-02-04 21:27:39 +00003124 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3125 if (ConstructorTmpl)
3126 Constructor = cast<CXXConstructorDecl>(
3127 ConstructorTmpl->getTemplatedDecl());
3128 else {
3129 Constructor = cast<CXXConstructorDecl>(D);
3130
Richard Smith867521c2013-09-21 21:23:47 +00003131 // C++11 [over.best.ics]p4:
3132 // However, when considering the argument of a constructor or
3133 // user-defined conversion function that is a candidate:
3134 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3135 // in the second step of a class copy-initialization,
3136 // -- by 13.3.1.7 when passing the initializer list as a single
3137 // argument or when the initializer list has exactly one elementand
3138 // a conversion to some class X or reference to (possibly
3139 // cv-qualified) X is considered for the first parameter of a
3140 // constructor of X, or
3141 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3142 // only standard conversion sequences and ellipsis conversion sequences
3143 // are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003144 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003145 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00003146 SuppressUserConversions = true;
3147 }
3148
3149 if (!Constructor->isInvalidDecl() &&
3150 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003151 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003152 if (ConstructorTmpl)
3153 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003154 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003155 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00003156 else {
3157 // C++ [over.match.copy]p1:
3158 // - When initializing a temporary to be bound to the first parameter
3159 // of a constructor that takes a reference to possibly cv-qualified
3160 // T as its first argument, called with a single argument in the
3161 // context of direct-initialization, explicit conversion functions
3162 // are also considered.
3163 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003164 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00003165 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003166 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00003167 SuppressUserConversions,
3168 /*PartialOverloading=*/false,
3169 /*AllowExplicit=*/AllowExplicitConv);
3170 }
Sebastian Redl96715b22012-02-04 21:27:39 +00003171 }
3172 }
3173
3174 // Perform overload resolution and return the result.
3175 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3176}
3177
Sebastian Redl10f04a62011-12-22 14:44:04 +00003178/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3179/// enumerates the constructors of the initialized entity and performs overload
3180/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00003181/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00003182/// class type.
3183static void TryConstructorInitialization(Sema &S,
3184 const InitializedEntity &Entity,
3185 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003186 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003187 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00003188 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003189 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00003190 "InitListSyntax must come with a single initializer list argument.");
3191
Sebastian Redl10f04a62011-12-22 14:44:04 +00003192 // The type we're constructing needs to be complete.
3193 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003194 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00003195 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003196 }
3197
3198 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3199 assert(DestRecordType && "Constructor initialization requires record type");
3200 CXXRecordDecl *DestRecordDecl
3201 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3202
Sebastian Redl96715b22012-02-04 21:27:39 +00003203 // Build the candidate set directly in the initialization sequence
3204 // structure, so that it will persist if we fail.
3205 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3206
3207 // Determine whether we are allowed to call explicit constructors or
3208 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003209 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003210 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00003211
Sebastian Redl10f04a62011-12-22 14:44:04 +00003212 // - Otherwise, if T is a class type, constructors are considered. The
3213 // applicable constructors are enumerated, and the best one is chosen
3214 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00003215 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003216 // The container holding the constructors can under certain conditions
3217 // be changed while iterating (e.g. because of deserialization).
3218 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003219 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00003220
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003221 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003222 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003223 bool AsInitializerList = false;
3224
3225 // C++11 [over.match.list]p1:
3226 // When objects of non-aggregate type T are list-initialized, overload
3227 // resolution selects the constructor in two phases:
3228 // - Initially, the candidate functions are the initializer-list
3229 // constructors of the class T and the argument list consists of the
3230 // initializer list as a single argument.
3231 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003232 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003233 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003234
3235 // If the initializer list has no elements and T has a default constructor,
3236 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003237 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003238 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003239 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003240 CopyInitialization, AllowExplicit,
3241 /*OnlyListConstructor=*/true,
3242 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003243
3244 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003245 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003246 }
3247
3248 // C++11 [over.match.list]p1:
3249 // - If no viable initializer-list constructor is found, overload resolution
3250 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003251 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003252 // elements of the initializer list.
3253 if (Result == OR_No_Viable_Function) {
3254 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003255 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003256 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003257 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003258 /*OnlyListConstructors=*/false,
3259 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003260 }
3261 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003262 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003263 InitializationSequence::FK_ListConstructorOverloadFailed :
3264 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003265 Result);
3266 return;
3267 }
3268
Richard Smithf4bb8d02012-07-05 08:39:21 +00003269 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003270 // If a program calls for the default initialization of an object
3271 // of a const-qualified type T, T shall be a class type with a
3272 // user-provided default constructor.
3273 if (Kind.getKind() == InitializationKind::IK_Default &&
3274 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003275 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003276 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3277 return;
3278 }
3279
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003280 // C++11 [over.match.list]p1:
3281 // In copy-list-initialization, if an explicit constructor is chosen, the
3282 // initializer is ill-formed.
3283 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3284 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3285 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3286 return;
3287 }
3288
Sebastian Redl10f04a62011-12-22 14:44:04 +00003289 // Add the constructor initialization step. Any cv-qualification conversion is
3290 // subsumed by the initialization.
3291 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003292 Sequence.AddConstructorInitializationStep(CtorDecl,
3293 Best->FoundDecl.getAccess(),
3294 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003295 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003296}
3297
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003298static bool
3299ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3300 Expr *Initializer,
3301 QualType &SourceType,
3302 QualType &UnqualifiedSourceType,
3303 QualType UnqualifiedTargetType,
3304 InitializationSequence &Sequence) {
3305 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3306 S.Context.OverloadTy) {
3307 DeclAccessPair Found;
3308 bool HadMultipleCandidates = false;
3309 if (FunctionDecl *Fn
3310 = S.ResolveAddressOfOverloadedFunction(Initializer,
3311 UnqualifiedTargetType,
3312 false, Found,
3313 &HadMultipleCandidates)) {
3314 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3315 HadMultipleCandidates);
3316 SourceType = Fn->getType();
3317 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3318 } else if (!UnqualifiedTargetType->isRecordType()) {
3319 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3320 return true;
3321 }
3322 }
3323 return false;
3324}
3325
3326static void TryReferenceInitializationCore(Sema &S,
3327 const InitializedEntity &Entity,
3328 const InitializationKind &Kind,
3329 Expr *Initializer,
3330 QualType cv1T1, QualType T1,
3331 Qualifiers T1Quals,
3332 QualType cv2T2, QualType T2,
3333 Qualifiers T2Quals,
3334 InitializationSequence &Sequence);
3335
Richard Smithf4bb8d02012-07-05 08:39:21 +00003336static void TryValueInitialization(Sema &S,
3337 const InitializedEntity &Entity,
3338 const InitializationKind &Kind,
3339 InitializationSequence &Sequence,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003340 InitListExpr *InitList = nullptr);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003341
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003342/// \brief Attempt list initialization of a reference.
3343static void TryReferenceListInitialization(Sema &S,
3344 const InitializedEntity &Entity,
3345 const InitializationKind &Kind,
3346 InitListExpr *InitList,
Richard Smithb6e38082013-06-08 00:02:08 +00003347 InitializationSequence &Sequence) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003348 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003349 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003350 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3351 return;
3352 }
3353
3354 QualType DestType = Entity.getType();
3355 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3356 Qualifiers T1Quals;
3357 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3358
3359 // Reference initialization via an initializer list works thus:
3360 // If the initializer list consists of a single element that is
3361 // reference-related to the referenced type, bind directly to that element
3362 // (possibly creating temporaries).
3363 // Otherwise, initialize a temporary with the initializer list and
3364 // bind to that.
3365 if (InitList->getNumInits() == 1) {
3366 Expr *Initializer = InitList->getInit(0);
3367 QualType cv2T2 = Initializer->getType();
3368 Qualifiers T2Quals;
3369 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3370
3371 // If this fails, creating a temporary wouldn't work either.
3372 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3373 T1, Sequence))
3374 return;
3375
3376 SourceLocation DeclLoc = Initializer->getLocStart();
3377 bool dummy1, dummy2, dummy3;
3378 Sema::ReferenceCompareResult RefRelationship
3379 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3380 dummy2, dummy3);
3381 if (RefRelationship >= Sema::Ref_Related) {
3382 // Try to bind the reference here.
3383 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3384 T1Quals, cv2T2, T2, T2Quals, Sequence);
3385 if (Sequence)
3386 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3387 return;
3388 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003389
3390 // Update the initializer if we've resolved an overloaded function.
3391 if (Sequence.step_begin() != Sequence.step_end())
3392 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003393 }
3394
3395 // Not reference-related. Create a temporary and bind to that.
3396 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3397
3398 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3399 if (Sequence) {
3400 if (DestType->isRValueReferenceType() ||
3401 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3402 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3403 else
3404 Sequence.SetFailed(
3405 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3406 }
3407}
3408
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003409/// \brief Attempt list initialization (C++0x [dcl.init.list])
3410static void TryListInitialization(Sema &S,
3411 const InitializedEntity &Entity,
3412 const InitializationKind &Kind,
3413 InitListExpr *InitList,
3414 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003415 QualType DestType = Entity.getType();
3416
Sebastian Redl14b0c192011-09-24 17:48:00 +00003417 // C++ doesn't allow scalar initialization with more than one argument.
3418 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003419 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003420 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3421 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3422 return;
3423 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003424 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003425 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003426 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003427 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003428 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003429 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003430 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003431 return;
3432 }
3433
Richard Smithf4bb8d02012-07-05 08:39:21 +00003434 // C++11 [dcl.init.list]p3:
3435 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003436 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003437 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003438 // - Otherwise, if the initializer list has no elements and T is a
3439 // class type with a default constructor, the object is
3440 // value-initialized.
3441 if (InitList->getNumInits() == 0) {
3442 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003443 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003444 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3445 return;
3446 }
3447 }
3448
3449 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3450 // an initializer_list object constructed [...]
3451 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3452 return;
3453
3454 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003455 Expr *InitListAsExpr = InitList;
3456 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003457 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003458 } else
3459 Sequence.SetFailed(
3460 InitializationSequence::FK_InitListBadDestinationType);
3461 return;
3462 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003463 }
Richard Smithb390e492013-09-21 21:55:46 +00003464 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3465 InitList->getNumInits() == 1 &&
3466 InitList->getInit(0)->getType()->isRecordType()) {
3467 // - Otherwise, if the initializer list has a single element of type E
3468 // [...references are handled above...], the object or reference is
3469 // initialized from that element; if a narrowing conversion is required
3470 // to convert the element to T, the program is ill-formed.
3471 //
3472 // Per core-24034, this is direct-initialization if we were performing
3473 // direct-list-initialization and copy-initialization otherwise.
3474 // We can't use InitListChecker for this, because it always performs
3475 // copy-initialization. This only matters if we might use an 'explicit'
3476 // conversion operator, so we only need to handle the cases where the source
3477 // is of record type.
3478 InitializationKind SubKind =
3479 Kind.getKind() == InitializationKind::IK_DirectList
3480 ? InitializationKind::CreateDirect(Kind.getLocation(),
3481 InitList->getLBraceLoc(),
3482 InitList->getRBraceLoc())
3483 : Kind;
3484 Expr *SubInit[1] = { InitList->getInit(0) };
3485 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3486 /*TopLevelOfInitList*/true);
3487 if (Sequence)
3488 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3489 return;
3490 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003491
Sebastian Redl14b0c192011-09-24 17:48:00 +00003492 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00003493 DestType, /*VerifyOnly=*/true);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003494 if (CheckInitList.HadError()) {
3495 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3496 return;
3497 }
3498
3499 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003500 Sequence.AddListInitializationStep(DestType);
3501}
Douglas Gregor20093b42009-12-09 23:02:17 +00003502
3503/// \brief Try a reference initialization that involves calling a conversion
3504/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003505static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3506 const InitializedEntity &Entity,
3507 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003508 Expr *Initializer,
3509 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003510 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003511 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003512 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3513 QualType T1 = cv1T1.getUnqualifiedType();
3514 QualType cv2T2 = Initializer->getType();
3515 QualType T2 = cv2T2.getUnqualifiedType();
3516
3517 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003518 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003519 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003520 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003521 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003522 ObjCConversion,
3523 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003524 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003525 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003526 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003527 (void)ObjCLifetimeConversion;
3528
Douglas Gregor20093b42009-12-09 23:02:17 +00003529 // Build the candidate set directly in the initialization sequence
3530 // structure, so that it will persist if we fail.
3531 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3532 CandidateSet.clear();
3533
3534 // Determine whether we are allowed to call explicit constructors or
3535 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003536 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith867521c2013-09-21 21:23:47 +00003537 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3538
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003539 const RecordType *T1RecordType = nullptr;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003540 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3541 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003542 // The type we're converting to is a class type. Enumerate its constructors
3543 // to see if there is a suitable conversion.
3544 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003545
David Blaikie3bc93e32012-12-19 00:45:41 +00003546 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003547 // The container holding the constructors can under certain conditions
3548 // be changed while iterating (e.g. because of deserialization).
3549 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003550 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00003551 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003552 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3553 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003554 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3555
Douglas Gregor20093b42009-12-09 23:02:17 +00003556 // Find the constructor (which may be a template).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003557 CXXConstructorDecl *Constructor = nullptr;
John McCall9aa472c2010-03-19 07:35:19 +00003558 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003559 if (ConstructorTmpl)
3560 Constructor = cast<CXXConstructorDecl>(
3561 ConstructorTmpl->getTemplatedDecl());
3562 else
John McCall9aa472c2010-03-19 07:35:19 +00003563 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003564
Douglas Gregor20093b42009-12-09 23:02:17 +00003565 if (!Constructor->isInvalidDecl() &&
3566 Constructor->isConvertingConstructor(AllowExplicit)) {
3567 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003568 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003569 /*ExplicitArgs*/ nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003570 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003571 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003572 else
John McCall9aa472c2010-03-19 07:35:19 +00003573 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003574 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003575 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003576 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003578 }
John McCall572fc622010-08-17 07:23:57 +00003579 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3580 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003581
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003582 const RecordType *T2RecordType = nullptr;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003583 if ((T2RecordType = T2->getAs<RecordType>()) &&
3584 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003585 // The type we're converting from is a class type, enumerate its conversion
3586 // functions.
3587 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3588
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003589 std::pair<CXXRecordDecl::conversion_iterator,
3590 CXXRecordDecl::conversion_iterator>
3591 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3592 for (CXXRecordDecl::conversion_iterator
3593 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003594 NamedDecl *D = *I;
3595 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3596 if (isa<UsingShadowDecl>(D))
3597 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003598
Douglas Gregor20093b42009-12-09 23:02:17 +00003599 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3600 CXXConversionDecl *Conv;
3601 if (ConvTemplate)
3602 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3603 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003604 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003605
Douglas Gregor20093b42009-12-09 23:02:17 +00003606 // If the conversion function doesn't return a reference type,
3607 // it can't be considered for this conversion unless we're allowed to
3608 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003609 // FIXME: Do we need to make sure that we only consider conversion
3610 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003611 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003612 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003613 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3614 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003615 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003616 ActingDC, Initializer,
Stephen Hines651f13c2014-04-23 16:59:28 -07003617 DestType, CandidateSet,
3618 /*AllowObjCConversionOnExplicit=*/
3619 false);
Douglas Gregor20093b42009-12-09 23:02:17 +00003620 else
John McCall9aa472c2010-03-19 07:35:19 +00003621 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Stephen Hines651f13c2014-04-23 16:59:28 -07003622 Initializer, DestType, CandidateSet,
3623 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00003624 }
3625 }
3626 }
John McCall572fc622010-08-17 07:23:57 +00003627 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3628 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003629
Douglas Gregor20093b42009-12-09 23:02:17 +00003630 SourceLocation DeclLoc = Initializer->getLocStart();
3631
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003632 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003633 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003634 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003635 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003636 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003637
Douglas Gregor20093b42009-12-09 23:02:17 +00003638 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003639 // This is the overload that will be used for this initialization step if we
3640 // use this initialization. Mark it as referenced.
3641 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003642
Eli Friedman03981012009-12-11 02:42:07 +00003643 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003644 if (isa<CXXConversionDecl>(Function))
Stephen Hines651f13c2014-04-23 16:59:28 -07003645 T2 = Function->getReturnType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003646 else
3647 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003648
3649 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003650 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003651 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003652 T2.getNonLValueExprType(S.Context),
3653 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003654
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003656 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003657 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003658 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003659 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003660 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003661 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003662
Douglas Gregor20093b42009-12-09 23:02:17 +00003663 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003664 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003665 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003666 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003667 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003668 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003669 NewDerivedToBase, NewObjCConversion,
3670 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003671 if (NewRefRelationship == Sema::Ref_Incompatible) {
3672 // If the type we've converted to is not reference-related to the
3673 // type we're looking for, then there is another conversion step
3674 // we need to perform to produce a temporary of the right type
3675 // that we'll be binding to.
3676 ImplicitConversionSequence ICS;
3677 ICS.setStandard();
3678 ICS.Standard = Best->FinalConversion;
3679 T2 = ICS.Standard.getToType(2);
3680 Sequence.AddConversionSequenceStep(ICS, T2);
3681 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003682 Sequence.AddDerivedToBaseCastStep(
3683 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003685 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003686 else if (NewObjCConversion)
3687 Sequence.AddObjCObjectConversionStep(
3688 S.Context.getQualifiedType(T1,
3689 T2.getNonReferenceType().getQualifiers()));
3690
Douglas Gregor20093b42009-12-09 23:02:17 +00003691 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003692 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003693
Douglas Gregor20093b42009-12-09 23:02:17 +00003694 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3695 return OR_Success;
3696}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003697
Richard Smith83da2e72011-10-19 16:55:56 +00003698static void CheckCXX98CompatAccessibleCopy(Sema &S,
3699 const InitializedEntity &Entity,
3700 Expr *CurInitExpr);
3701
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003702/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3703static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003704 const InitializedEntity &Entity,
3705 const InitializationKind &Kind,
3706 Expr *Initializer,
3707 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003708 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003709 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003710 Qualifiers T1Quals;
3711 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003712 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003713 Qualifiers T2Quals;
3714 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003715
Douglas Gregor20093b42009-12-09 23:02:17 +00003716 // If the initializer is the address of an overloaded function, try
3717 // to resolve the overloaded function. If all goes well, T2 is the
3718 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003719 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3720 T1, Sequence))
3721 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003722
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003723 // Delegate everything else to a subfunction.
3724 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3725 T1Quals, cv2T2, T2, T2Quals, Sequence);
3726}
3727
Jordan Rose1fd1e282013-04-11 00:58:58 +00003728/// Converts the target of reference initialization so that it has the
3729/// appropriate qualifiers and value kind.
3730///
3731/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3732/// \code
3733/// int x;
3734/// const int &r = x;
3735/// \endcode
3736///
3737/// In this case the reference is binding to a bitfield lvalue, which isn't
3738/// valid. Perform a load to create a lifetime-extended temporary instead.
3739/// \code
3740/// const int &r = someStruct.bitfield;
3741/// \endcode
3742static ExprValueKind
3743convertQualifiersAndValueKindIfNecessary(Sema &S,
3744 InitializationSequence &Sequence,
3745 Expr *Initializer,
3746 QualType cv1T1,
3747 Qualifiers T1Quals,
3748 Qualifiers T2Quals,
3749 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003750 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003751 Initializer->refersToVectorElement();
3752
3753 if (IsNonAddressableType) {
3754 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3755 // lvalue reference to a non-volatile const type, or the reference shall be
3756 // an rvalue reference.
3757 //
3758 // If not, we can't make a temporary and bind to that. Give up and allow the
3759 // error to be diagnosed later.
3760 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3761 assert(Initializer->isGLValue());
3762 return Initializer->getValueKind();
3763 }
3764
3765 // Force a load so we can materialize a temporary.
3766 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3767 return VK_RValue;
3768 }
3769
3770 if (T1Quals != T2Quals) {
3771 Sequence.AddQualificationConversionStep(cv1T1,
3772 Initializer->getValueKind());
3773 }
3774
3775 return Initializer->getValueKind();
3776}
3777
3778
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003779/// \brief Reference initialization without resolving overloaded functions.
3780static void TryReferenceInitializationCore(Sema &S,
3781 const InitializedEntity &Entity,
3782 const InitializationKind &Kind,
3783 Expr *Initializer,
3784 QualType cv1T1, QualType T1,
3785 Qualifiers T1Quals,
3786 QualType cv2T2, QualType T2,
3787 Qualifiers T2Quals,
3788 InitializationSequence &Sequence) {
3789 QualType DestType = Entity.getType();
3790 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003791 // Compute some basic properties of the types and the initializer.
3792 bool isLValueRef = DestType->isLValueReferenceType();
3793 bool isRValueRef = !isLValueRef;
3794 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003795 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003796 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003797 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003798 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003799 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003800 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003801
Douglas Gregor20093b42009-12-09 23:02:17 +00003802 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003803 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003804 // "cv2 T2" as follows:
3805 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003807 // expression
Richard Smith867521c2013-09-21 21:23:47 +00003808 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redl4680bf22010-06-30 18:13:39 +00003809 // there are no function rvalues in C++, rvalue refs to functions are treated
3810 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003811 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003812 bool T1Function = T1->isFunctionType();
3813 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003815 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003817 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003818 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003819 // reference-compatible with "cv2 T2," or
3820 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003821 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003822 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003823 // can occur. However, we do pay attention to whether it is a bit-field
3824 // to decide whether we're actually binding to a temporary created from
3825 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003826 if (DerivedToBase)
3827 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003828 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003829 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003830 else if (ObjCConversion)
3831 Sequence.AddObjCObjectConversionStep(
3832 S.Context.getQualifiedType(T1, T2Quals));
3833
Jordan Rose1fd1e282013-04-11 00:58:58 +00003834 ExprValueKind ValueKind =
3835 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3836 cv1T1, T1Quals, T2Quals,
3837 isLValueRef);
3838 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003839 return;
3840 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003841
3842 // - has a class type (i.e., T2 is a class type), where T1 is not
3843 // reference-related to T2, and can be implicitly converted to an
3844 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3845 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003846 // applicable conversion functions (13.3.1.6) and choosing the best
3847 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003848 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith867521c2013-09-21 21:23:47 +00003849 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003850 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3851 (isLValueRef || InitCategory.isRValue())) {
Richard Smith867521c2013-09-21 21:23:47 +00003852 ConvOvlResult = TryRefInitWithConversionFunction(
3853 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00003854 if (ConvOvlResult == OR_Success)
3855 return;
Richard Smith867521c2013-09-21 21:23:47 +00003856 if (ConvOvlResult != OR_No_Viable_Function)
John McCall1d318332010-01-12 00:44:57 +00003857 Sequence.SetOverloadFailure(
Richard Smith867521c2013-09-21 21:23:47 +00003858 InitializationSequence::FK_ReferenceInitOverloadFailed,
3859 ConvOvlResult);
Douglas Gregor20093b42009-12-09 23:02:17 +00003860 }
3861 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003862
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003864 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003865 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003866 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003867 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3868 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3869 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003870 Sequence.SetOverloadFailure(
3871 InitializationSequence::FK_ReferenceInitOverloadFailed,
3872 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003873 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003874 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003875 ? (RefRelationship == Sema::Ref_Related
3876 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3877 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3878 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003879
Douglas Gregor20093b42009-12-09 23:02:17 +00003880 return;
3881 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003882
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003883 // - If the initializer expression
3884 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3885 // "cv1 T1" is reference-compatible with "cv2 T2"
3886 // Note: functions are handled below.
3887 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003888 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003889 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003890 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003891 (InitCategory.isXValue() ||
3892 (InitCategory.isPRValue() && T2->isRecordType()) ||
3893 (InitCategory.isPRValue() && T2->isArrayType()))) {
3894 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3895 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003896 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3897 // compiler the freedom to perform a copy here or bind to the
3898 // object, while C++0x requires that we bind directly to the
3899 // object. Hence, we always bind to the object without making an
3900 // extra copy. However, in C++03 requires that we check for the
3901 // presence of a suitable copy constructor:
3902 //
3903 // The constructor that would be used to make the copy shall
3904 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003905 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003906 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003907 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003908 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003909 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003910
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003911 if (DerivedToBase)
3912 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3913 ValueKind);
3914 else if (ObjCConversion)
3915 Sequence.AddObjCObjectConversionStep(
3916 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003917
Jordan Rose1fd1e282013-04-11 00:58:58 +00003918 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3919 Initializer, cv1T1,
3920 T1Quals, T2Quals,
3921 isLValueRef);
3922
3923 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003924 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003925 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003926
3927 // - has a class type (i.e., T2 is a class type), where T1 is not
3928 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003929 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3930 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith867521c2013-09-21 21:23:47 +00003931 //
3932 // DR1287 removes the "implicitly" here.
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003933 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003934 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith867521c2013-09-21 21:23:47 +00003935 ConvOvlResult = TryRefInitWithConversionFunction(
3936 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00003937 if (ConvOvlResult)
3938 Sequence.SetOverloadFailure(
Richard Smith867521c2013-09-21 21:23:47 +00003939 InitializationSequence::FK_ReferenceInitOverloadFailed,
3940 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003941
Douglas Gregor20093b42009-12-09 23:02:17 +00003942 return;
3943 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944
Douglas Gregordefa32e2013-03-26 23:59:23 +00003945 if ((RefRelationship == Sema::Ref_Compatible ||
3946 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3947 isRValueRef && InitCategory.isLValue()) {
3948 Sequence.SetFailed(
3949 InitializationSequence::FK_RValueReferenceBindingToLValue);
3950 return;
3951 }
3952
Douglas Gregor20093b42009-12-09 23:02:17 +00003953 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3954 return;
3955 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003956
3957 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003958 // from the initializer expression using the rules for a non-reference
Richard Smith4e47ecb2013-06-13 00:57:57 +00003959 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003960 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003961
John McCall369371c2010-06-04 02:29:22 +00003962 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3963
Richard Smith4e47ecb2013-06-13 00:57:57 +00003964 // FIXME: Why do we use an implicit conversion here rather than trying
3965 // copy-initialization?
John McCallf85e1932011-06-15 23:02:42 +00003966 ImplicitConversionSequence ICS
3967 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith4e47ecb2013-06-13 00:57:57 +00003968 /*SuppressUserConversions=*/false,
3969 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003970 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003971 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3972 /*AllowObjCWritebackConversion=*/false);
3973
3974 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003975 // FIXME: Use the conversion function set stored in ICS to turn
3976 // this into an overloading ambiguity diagnostic. However, we need
3977 // to keep that set as an OverloadCandidateSet rather than as some
3978 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003979 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3980 Sequence.SetOverloadFailure(
3981 InitializationSequence::FK_ReferenceInitOverloadFailed,
3982 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003983 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3984 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003985 else
3986 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003987 return;
John McCallf85e1932011-06-15 23:02:42 +00003988 } else {
3989 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003990 }
3991
3992 // [...] If T1 is reference-related to T2, cv1 must be the
3993 // same cv-qualification as, or greater cv-qualification
3994 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003995 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3996 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003997 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003998 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003999 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4000 return;
4001 }
4002
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004003 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00004004 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004005 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00004006 InitCategory.isLValue()) {
4007 Sequence.SetFailed(
4008 InitializationSequence::FK_RValueReferenceBindingToLValue);
4009 return;
4010 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004011
Douglas Gregor20093b42009-12-09 23:02:17 +00004012 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4013 return;
4014}
4015
4016/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004017/// (C++ [dcl.init.string], C99 6.7.8).
4018static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004019 const InitializedEntity &Entity,
4020 const InitializationKind &Kind,
4021 Expr *Initializer,
4022 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004023 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00004024}
4025
Douglas Gregor71d17402009-12-15 00:01:57 +00004026/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004027static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00004028 const InitializedEntity &Entity,
4029 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00004030 InitializationSequence &Sequence,
4031 InitListExpr *InitList) {
4032 assert((!InitList || InitList->getNumInits() == 0) &&
4033 "Shouldn't use value-init for non-empty init lists");
4034
Richard Smith1d0c9a82012-02-14 21:14:13 +00004035 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00004036 //
4037 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00004038 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004039
Douglas Gregor71d17402009-12-15 00:01:57 +00004040 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00004041 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004042
Douglas Gregor71d17402009-12-15 00:01:57 +00004043 if (const RecordType *RT = T->getAs<RecordType>()) {
4044 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00004045 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00004046 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00004047 // C++98:
4048 // -- if T is a class type (clause 9) with a user-declared constructor
4049 // (12.1), then the default constructor for T is called (and the
4050 // initialization is ill-formed if T has no accessible default
4051 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00004052 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00004053 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00004054 } else {
4055 // C++11:
4056 // -- if T is a class type (clause 9) with either no default constructor
4057 // (12.1 [class.ctor]) or a default constructor that is user-provided
4058 // or deleted, then the object is default-initialized;
4059 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4060 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00004061 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00004062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063
Richard Smith1d0c9a82012-02-14 21:14:13 +00004064 // -- if T is a (possibly cv-qualified) non-union class type without a
4065 // user-provided or deleted default constructor, then the object is
4066 // zero-initialized and, if T has a non-trivial default constructor,
4067 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00004068 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4069 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00004070 if (NeedZeroInitialization)
4071 Sequence.AddZeroInitializationStep(Entity.getType());
4072
Richard Smithd5bc8672012-12-08 02:01:17 +00004073 // C++03:
4074 // -- if T is a non-union class type without a user-declared constructor,
4075 // then every non-static data member and base class component of T is
4076 // value-initialized;
4077 // [...] A program that calls for [...] value-initialization of an
4078 // entity of reference type is ill-formed.
4079 //
4080 // C++11 doesn't need this handling, because value-initialization does not
4081 // occur recursively there, and the implicit default constructor is
4082 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00004083 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00004084 ClassDecl->hasUninitializedReferenceMember()) {
4085 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4086 return;
4087 }
4088
Richard Smithf4bb8d02012-07-05 08:39:21 +00004089 // If this is list-value-initialization, pass the empty init list on when
4090 // building the constructor call. This affects the semantics of a few
4091 // things (such as whether an explicit default constructor can be called).
4092 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004093 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00004094 bool InitListSyntax = InitList;
4095
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004096 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4097 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00004098 }
4099 }
4100
Douglas Gregord6542d82009-12-22 15:35:07 +00004101 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00004102}
4103
Douglas Gregor99a2e602009-12-16 01:38:02 +00004104/// \brief Attempt default initialization (C++ [dcl.init]p6).
4105static void TryDefaultInitialization(Sema &S,
4106 const InitializedEntity &Entity,
4107 const InitializationKind &Kind,
4108 InitializationSequence &Sequence) {
4109 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110
Douglas Gregor99a2e602009-12-16 01:38:02 +00004111 // C++ [dcl.init]p6:
4112 // To default-initialize an object of type T means:
4113 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00004114 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4115
Douglas Gregor99a2e602009-12-16 01:38:02 +00004116 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4117 // constructor for T is called (and the initialization is ill-formed if
4118 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00004119 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00004120 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004121 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004123
Douglas Gregor99a2e602009-12-16 01:38:02 +00004124 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004125
Douglas Gregor99a2e602009-12-16 01:38:02 +00004126 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004127 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00004128 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00004129 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004130 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00004131 return;
4132 }
4133
4134 // If the destination type has a lifetime property, zero-initialize it.
4135 if (DestType.getQualifiers().hasObjCLifetime()) {
4136 Sequence.AddZeroInitializationStep(Entity.getType());
4137 return;
4138 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004139}
4140
Douglas Gregor20093b42009-12-09 23:02:17 +00004141/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4142/// which enumerates all conversion functions and performs overload resolution
4143/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144static void TryUserDefinedConversion(Sema &S,
Stephen Hines176edba2014-12-01 14:53:08 -08004145 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00004146 const InitializationKind &Kind,
4147 Expr *Initializer,
Richard Smith13b228d2013-09-21 21:19:19 +00004148 InitializationSequence &Sequence,
4149 bool TopLevelOfInitList) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004150 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4151 QualType SourceType = Initializer->getType();
4152 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4153 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004154
Douglas Gregor4a520a22009-12-14 17:27:33 +00004155 // Build the candidate set directly in the initialization sequence
4156 // structure, so that it will persist if we fail.
4157 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4158 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004159
Douglas Gregor4a520a22009-12-14 17:27:33 +00004160 // Determine whether we are allowed to call explicit constructors or
4161 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00004162 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163
Douglas Gregor4a520a22009-12-14 17:27:33 +00004164 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4165 // The type we're converting to is a class type. Enumerate its constructors
4166 // to see if there is a suitable conversion.
4167 CXXRecordDecl *DestRecordDecl
4168 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004169
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004170 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004171 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004172 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004173 // The container holding the constructors can under certain conditions
4174 // be changed while iterating. To be safe we copy the lookup results
4175 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004176 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004177 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004178 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004179 Con != ConEnd; ++Con) {
4180 NamedDecl *D = *Con;
4181 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004182
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004183 // Find the constructor (which may be a template).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004184 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004185 FunctionTemplateDecl *ConstructorTmpl
4186 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004187 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004188 Constructor = cast<CXXConstructorDecl>(
4189 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00004190 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004191 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004192
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004193 if (!Constructor->isInvalidDecl() &&
4194 Constructor->isConvertingConstructor(AllowExplicit)) {
4195 if (ConstructorTmpl)
4196 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004197 /*ExplicitArgs*/ nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004198 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004199 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004200 else
4201 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004202 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004203 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004204 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004205 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004206 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004207 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004208
4209 SourceLocation DeclLoc = Initializer->getLocStart();
4210
Douglas Gregor4a520a22009-12-14 17:27:33 +00004211 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4212 // The type we're converting from is a class type, enumerate its conversion
4213 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004214
Eli Friedman33c2da92009-12-20 22:12:03 +00004215 // We can only enumerate the conversion functions for a complete type; if
4216 // the type isn't complete, simply skip this step.
4217 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4218 CXXRecordDecl *SourceRecordDecl
4219 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004220
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004221 std::pair<CXXRecordDecl::conversion_iterator,
4222 CXXRecordDecl::conversion_iterator>
4223 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4224 for (CXXRecordDecl::conversion_iterator
4225 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00004226 NamedDecl *D = *I;
4227 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4228 if (isa<UsingShadowDecl>(D))
4229 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004230
Eli Friedman33c2da92009-12-20 22:12:03 +00004231 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4232 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00004233 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00004234 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00004235 else
John McCall32daa422010-03-31 01:36:47 +00004236 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004237
Eli Friedman33c2da92009-12-20 22:12:03 +00004238 if (AllowExplicit || !Conv->isExplicit()) {
4239 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00004240 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00004241 ActingDC, Initializer, DestType,
Stephen Hines651f13c2014-04-23 16:59:28 -07004242 CandidateSet, AllowExplicit);
Eli Friedman33c2da92009-12-20 22:12:03 +00004243 else
John McCall9aa472c2010-03-19 07:35:19 +00004244 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Stephen Hines651f13c2014-04-23 16:59:28 -07004245 Initializer, DestType, CandidateSet,
4246 AllowExplicit);
Eli Friedman33c2da92009-12-20 22:12:03 +00004247 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004248 }
4249 }
4250 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004251
4252 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004253 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004254 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004255 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004256 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004257 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004258 Result);
4259 return;
4260 }
John McCall1d318332010-01-12 00:44:57 +00004261
Douglas Gregor4a520a22009-12-14 17:27:33 +00004262 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004263 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004264 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265
Douglas Gregor4a520a22009-12-14 17:27:33 +00004266 if (isa<CXXConstructorDecl>(Function)) {
4267 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004268 // subsumed by the initialization. Per DR5, the created temporary is of the
4269 // cv-unqualified type of the destination.
4270 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4271 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004272 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004273 return;
4274 }
4275
4276 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004277 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004278 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004279 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004280 // the resulting temporary object (possible to create an object of
4281 // a base class type). That copy is not a separate conversion, so
4282 // we just make a note of the actual destination type (possibly a
4283 // base class of the type returned by the conversion function) and
4284 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004285 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4286 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004287 return;
4288 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004289
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004290 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4291 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004293 // If the conversion following the call to the conversion function
4294 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004295 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4296 Best->FinalConversion.Third) {
4297 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004298 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004299 ICS.Standard = Best->FinalConversion;
Richard Smith13b228d2013-09-21 21:19:19 +00004300 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004301 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004302}
4303
Richard Smith87c29322013-06-20 02:18:31 +00004304/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4305/// a function with a pointer return type contains a 'return false;' statement.
4306/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4307/// code using that header.
4308///
4309/// Work around this by treating 'return false;' as zero-initializing the result
4310/// if it's used in a pointer-returning function in a system header.
4311static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4312 const InitializedEntity &Entity,
4313 const Expr *Init) {
4314 return S.getLangOpts().CPlusPlus11 &&
4315 Entity.getKind() == InitializedEntity::EK_Result &&
4316 Entity.getType()->isPointerType() &&
4317 isa<CXXBoolLiteralExpr>(Init) &&
4318 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4319 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4320}
4321
John McCallf85e1932011-06-15 23:02:42 +00004322/// The non-zero enum values here are indexes into diagnostic alternatives.
4323enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4324
4325/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004326static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004327 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004328 // Skip parens.
4329 e = e->IgnoreParens();
4330
4331 // Skip address-of nodes.
4332 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4333 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004334 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4335 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004336
4337 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004338 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4339 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004340 case CK_Dependent:
4341 case CK_BitCast:
4342 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004343 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004344 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004345
4346 case CK_ArrayToPointerDecay:
4347 return IIK_nonscalar;
4348
4349 case CK_NullToPointer:
4350 return IIK_okay;
4351
4352 default:
4353 break;
4354 }
4355
4356 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004357 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004358 // set isWeakAccess to true, to mean that there will be an implicit
4359 // load which requires a cleanup.
4360 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4361 isWeakAccess = true;
4362
John McCallc03fa492011-06-27 23:59:58 +00004363 if (!isAddressOf) return IIK_nonlocal;
4364
John McCallf4b88a42012-03-10 09:33:50 +00004365 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4366 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004367
4368 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004369
4370 // If we have a conditional operator, check both sides.
4371 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004372 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4373 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004374 return iik;
4375
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004376 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004377
4378 // These are never scalar.
4379 } else if (isa<ArraySubscriptExpr>(e)) {
4380 return IIK_nonscalar;
4381
4382 // Otherwise, it needs to be a null pointer constant.
4383 } else {
4384 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4385 ? IIK_okay : IIK_nonlocal);
4386 }
4387
4388 return IIK_nonlocal;
4389}
4390
4391/// Check whether the given expression is a valid operand for an
4392/// indirect copy/restore.
4393static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4394 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004395 bool isWeakAccess = false;
4396 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4397 // If isWeakAccess to true, there will be an implicit
4398 // load which requires a cleanup.
4399 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4400 S.ExprNeedsCleanups = true;
4401
John McCallf85e1932011-06-15 23:02:42 +00004402 if (iik == IIK_okay) return;
4403
4404 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4405 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4406 << src->getSourceRange();
4407}
4408
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004409/// \brief Determine whether we have compatible array types for the
4410/// purposes of GNU by-copy array initialization.
4411static bool hasCompatibleArrayTypes(ASTContext &Context,
4412 const ArrayType *Dest,
4413 const ArrayType *Source) {
4414 // If the source and destination array types are equivalent, we're
4415 // done.
4416 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4417 return true;
4418
4419 // Make sure that the element types are the same.
4420 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4421 return false;
4422
4423 // The only mismatch we allow is when the destination is an
4424 // incomplete array type and the source is a constant array type.
4425 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4426}
4427
John McCallf85e1932011-06-15 23:02:42 +00004428static bool tryObjCWritebackConversion(Sema &S,
4429 InitializationSequence &Sequence,
4430 const InitializedEntity &Entity,
4431 Expr *Initializer) {
4432 bool ArrayDecay = false;
4433 QualType ArgType = Initializer->getType();
4434 QualType ArgPointee;
4435 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4436 ArrayDecay = true;
4437 ArgPointee = ArgArrayType->getElementType();
4438 ArgType = S.Context.getPointerType(ArgPointee);
4439 }
4440
4441 // Handle write-back conversion.
4442 QualType ConvertedArgType;
4443 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4444 ConvertedArgType))
4445 return false;
4446
4447 // We should copy unless we're passing to an argument explicitly
4448 // marked 'out'.
4449 bool ShouldCopy = true;
4450 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4451 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4452
4453 // Do we need an lvalue conversion?
4454 if (ArrayDecay || Initializer->isGLValue()) {
4455 ImplicitConversionSequence ICS;
4456 ICS.setStandard();
4457 ICS.Standard.setAsIdentityConversion();
4458
4459 QualType ResultType;
4460 if (ArrayDecay) {
4461 ICS.Standard.First = ICK_Array_To_Pointer;
4462 ResultType = S.Context.getPointerType(ArgPointee);
4463 } else {
4464 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4465 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4466 }
4467
4468 Sequence.AddConversionSequenceStep(ICS, ResultType);
4469 }
4470
4471 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4472 return true;
4473}
4474
Guy Benyei21f18c42013-02-07 10:55:47 +00004475static bool TryOCLSamplerInitialization(Sema &S,
4476 InitializationSequence &Sequence,
4477 QualType DestType,
4478 Expr *Initializer) {
4479 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4480 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4481 return false;
4482
4483 Sequence.AddOCLSamplerInitStep(DestType);
4484 return true;
4485}
4486
Guy Benyeie6b9d802013-01-20 12:31:11 +00004487//
4488// OpenCL 1.2 spec, s6.12.10
4489//
4490// The event argument can also be used to associate the
4491// async_work_group_copy with a previous async copy allowing
4492// an event to be shared by multiple async copies; otherwise
4493// event should be zero.
4494//
4495static bool TryOCLZeroEventInitialization(Sema &S,
4496 InitializationSequence &Sequence,
4497 QualType DestType,
4498 Expr *Initializer) {
4499 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4500 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4501 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4502 return false;
4503
4504 Sequence.AddOCLZeroEventStep(DestType);
4505 return true;
4506}
4507
Douglas Gregor20093b42009-12-09 23:02:17 +00004508InitializationSequence::InitializationSequence(Sema &S,
4509 const InitializedEntity &Entity,
4510 const InitializationKind &Kind,
Richard Smith13b228d2013-09-21 21:19:19 +00004511 MultiExprArg Args,
4512 bool TopLevelOfInitList)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004513 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smithb390e492013-09-21 21:55:46 +00004514 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4515}
4516
4517void InitializationSequence::InitializeFrom(Sema &S,
4518 const InitializedEntity &Entity,
4519 const InitializationKind &Kind,
4520 MultiExprArg Args,
4521 bool TopLevelOfInitList) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004522 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004523
John McCall76da55d2013-04-16 07:28:30 +00004524 // Eliminate non-overload placeholder types in the arguments. We
4525 // need to do this before checking whether types are dependent
4526 // because lowering a pseudo-object expression might well give us
4527 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004528 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004529 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4530 // FIXME: should we be doing this here?
4531 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4532 if (result.isInvalid()) {
4533 SetFailed(FK_PlaceholderType);
4534 return;
4535 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004536 Args[I] = result.get();
John McCall76da55d2013-04-16 07:28:30 +00004537 }
4538
Douglas Gregor20093b42009-12-09 23:02:17 +00004539 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540 // The semantics of initializers are as follows. The destination type is
4541 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004542 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004543 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004544 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004545 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004546
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004547 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004548 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004549 SequenceKind = DependentSequence;
4550 return;
4551 }
4552
Sebastian Redl7491c492011-06-05 13:59:11 +00004553 // Almost everything is a normal sequence.
4554 setSequenceKind(NormalSequence);
4555
Douglas Gregor20093b42009-12-09 23:02:17 +00004556 QualType SourceType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004557 Expr *Initializer = nullptr;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004558 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004559 Initializer = Args[0];
Stephen Hines651f13c2014-04-23 16:59:28 -07004560 if (S.getLangOpts().ObjC1) {
4561 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4562 DestType, Initializer->getType(),
4563 Initializer) ||
4564 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4565 Args[0] = Initializer;
Stephen Hines651f13c2014-04-23 16:59:28 -07004566 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004567 if (!isa<InitListExpr>(Initializer))
4568 SourceType = Initializer->getType();
4569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004570
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004571 // - If the initializer is a (non-parenthesized) braced-init-list, the
4572 // object is list-initialized (8.5.4).
4573 if (Kind.getKind() != InitializationKind::IK_Direct) {
4574 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4575 TryListInitialization(S, Entity, Kind, InitList, *this);
4576 return;
4577 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004578 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004579
Douglas Gregor20093b42009-12-09 23:02:17 +00004580 // - If the destination type is a reference type, see 8.5.3.
4581 if (DestType->isReferenceType()) {
4582 // C++0x [dcl.init.ref]p1:
4583 // A variable declared to be a T& or T&&, that is, "reference to type T"
4584 // (8.3.2), shall be initialized by an object, or function, of type T or
4585 // by an object that can be converted into a T.
4586 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004587 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004588 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004589 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004590 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004591 return;
4592 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004593
Douglas Gregor20093b42009-12-09 23:02:17 +00004594 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004595 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004596 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004597 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004598 return;
4599 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004600
Douglas Gregor99a2e602009-12-16 01:38:02 +00004601 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004602 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004603 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004604 return;
4605 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004606
John McCallce6c9b72011-02-21 07:22:22 +00004607 // - If the destination type is an array of characters, an array of
4608 // char16_t, an array of char32_t, or an array of wchar_t, and the
4609 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004610 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004611 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004612 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004613 if (Initializer && isa<VariableArrayType>(DestAT)) {
4614 SetFailed(FK_VariableLengthArrayHasInitializer);
4615 return;
4616 }
4617
Hans Wennborg0ff50742013-05-15 11:03:04 +00004618 if (Initializer) {
4619 switch (IsStringInit(Initializer, DestAT, Context)) {
4620 case SIF_None:
4621 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4622 return;
4623 case SIF_NarrowStringIntoWideChar:
4624 SetFailed(FK_NarrowStringIntoWideCharArray);
4625 return;
4626 case SIF_WideStringIntoChar:
4627 SetFailed(FK_WideStringIntoCharArray);
4628 return;
4629 case SIF_IncompatWideStringIntoWideChar:
4630 SetFailed(FK_IncompatWideStringIntoWideChar);
4631 return;
4632 case SIF_Other:
4633 break;
4634 }
John McCallce6c9b72011-02-21 07:22:22 +00004635 }
4636
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004637 // Note: as an GNU C extension, we allow initialization of an
4638 // array from a compound literal that creates an array of the same
4639 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004640 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004641 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4642 Initializer->getType()->isArrayType()) {
4643 const ArrayType *SourceAT
4644 = Context.getAsArrayType(Initializer->getType());
4645 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004646 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004647 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004648 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004649 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004650 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004651 }
Richard Smith0f163e92012-02-15 22:38:09 +00004652 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004653 // Note: as a GNU C++ extension, we allow list-initialization of a
4654 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004655 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004656 Entity.getKind() == InitializedEntity::EK_Member &&
4657 Initializer && isa<InitListExpr>(Initializer)) {
4658 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4659 *this);
4660 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004661 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004662 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004663 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4664 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004665 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004666 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004667
Douglas Gregor20093b42009-12-09 23:02:17 +00004668 return;
4669 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004670
John McCallf85e1932011-06-15 23:02:42 +00004671 // Determine whether we should consider writeback conversions for
4672 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004673 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004674 Entity.isParameterKind();
John McCallf85e1932011-06-15 23:02:42 +00004675
4676 // We're at the end of the line for C: it's either a write-back conversion
4677 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004678 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004679 // If allowed, check whether this is an Objective-C writeback conversion.
4680 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004681 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004682 return;
4683 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004684
4685 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4686 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004687
4688 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4689 return;
4690
John McCallf85e1932011-06-15 23:02:42 +00004691 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004692 AddCAssignmentStep(DestType);
4693 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004694 return;
4695 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004696
David Blaikie4e4d0842012-03-11 07:00:24 +00004697 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004698
Douglas Gregor20093b42009-12-09 23:02:17 +00004699 // - If the destination type is a (possibly cv-qualified) class type:
4700 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004701 // - If the initialization is direct-initialization, or if it is
4702 // copy-initialization where the cv-unqualified version of the
4703 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004704 // class of the destination, constructors are considered. [...]
4705 if (Kind.getKind() == InitializationKind::IK_Direct ||
4706 (Kind.getKind() == InitializationKind::IK_Copy &&
4707 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4708 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004709 TryConstructorInitialization(S, Entity, Kind, Args,
Stephen Hines176edba2014-12-01 14:53:08 -08004710 DestType, *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004711 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004712 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004713 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004714 // used) to a derived class thereof are enumerated as described in
4715 // 13.3.1.4, and the best one is chosen through overload resolution
4716 // (13.3).
4717 else
Stephen Hines176edba2014-12-01 14:53:08 -08004718 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smith13b228d2013-09-21 21:19:19 +00004719 TopLevelOfInitList);
Douglas Gregor20093b42009-12-09 23:02:17 +00004720 return;
4721 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004722
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004723 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004724 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004725 return;
4726 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004727 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728
4729 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004730 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004731 if (!SourceType.isNull() && SourceType->isRecordType()) {
Stephen Hines176edba2014-12-01 14:53:08 -08004732 // For a conversion to _Atomic(T) from either T or a class type derived
4733 // from T, initialize the T object then convert to _Atomic type.
4734 bool NeedAtomicConversion = false;
4735 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4736 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4737 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4738 DestType = Atomic->getValueType();
4739 NeedAtomicConversion = true;
4740 }
4741 }
4742
4743 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smith13b228d2013-09-21 21:19:19 +00004744 TopLevelOfInitList);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004745 MaybeProduceObjCObject(S, *this, Entity);
Stephen Hines176edba2014-12-01 14:53:08 -08004746 if (!Failed() && NeedAtomicConversion)
4747 AddAtomicConversionStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00004748 return;
4749 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750
Douglas Gregor20093b42009-12-09 23:02:17 +00004751 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004752 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004753 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004754 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004755 // destination type; no user-defined conversions are considered.
Stephen Hines176edba2014-12-01 14:53:08 -08004756
John McCallf85e1932011-06-15 23:02:42 +00004757 ImplicitConversionSequence ICS
Stephen Hines176edba2014-12-01 14:53:08 -08004758 = S.TryImplicitConversion(Initializer, DestType,
John McCallf85e1932011-06-15 23:02:42 +00004759 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004760 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004761 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004762 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4763 allowObjCWritebackConversion);
Stephen Hines176edba2014-12-01 14:53:08 -08004764
4765 if (ICS.isStandard() &&
John McCallf85e1932011-06-15 23:02:42 +00004766 ICS.Standard.Second == ICK_Writeback_Conversion) {
4767 // Objective-C ARC writeback conversion.
4768
4769 // We should copy unless we're passing to an argument explicitly
4770 // marked 'out'.
4771 bool ShouldCopy = true;
4772 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4773 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4774
4775 // If there was an lvalue adjustment, add it as a separate conversion.
4776 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4777 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4778 ImplicitConversionSequence LvalueICS;
4779 LvalueICS.setStandard();
4780 LvalueICS.Standard.setAsIdentityConversion();
4781 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4782 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004783 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004784 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004785
Stephen Hines176edba2014-12-01 14:53:08 -08004786 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004787 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004788 DeclAccessPair dap;
Richard Smith87c29322013-06-20 02:18:31 +00004789 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4790 AddZeroInitializationStep(Entity.getType());
4791 } else if (Initializer->getType() == Context.OverloadTy &&
4792 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4793 false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004794 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004795 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004796 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004797 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08004798 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCall856d3792011-06-16 23:24:51 +00004799
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004800 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004801 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004802}
4803
4804InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004805 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004806 StepEnd = Steps.end();
4807 Step != StepEnd; ++Step)
4808 Step->Destroy();
4809}
4810
4811//===----------------------------------------------------------------------===//
4812// Perform initialization
4813//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004814static Sema::AssignmentAction
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004815getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004816 switch(Entity.getKind()) {
4817 case InitializedEntity::EK_Variable:
4818 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004819 case InitializedEntity::EK_Exception:
4820 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004821 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004822 return Sema::AA_Initializing;
4823
4824 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004825 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004826 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4827 return Sema::AA_Sending;
4828
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004829 return Sema::AA_Passing;
4830
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004831 case InitializedEntity::EK_Parameter_CF_Audited:
4832 if (Entity.getDecl() &&
4833 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4834 return Sema::AA_Sending;
4835
4836 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4837
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004838 case InitializedEntity::EK_Result:
4839 return Sema::AA_Returning;
4840
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004841 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf5200d62013-07-11 19:13:34 +00004842 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004843 // FIXME: Can we tell apart casting vs. converting?
4844 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004845
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004846 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004847 case InitializedEntity::EK_ArrayElement:
4848 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004849 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004850 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004851 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004852 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004853 return Sema::AA_Initializing;
4854 }
4855
David Blaikie7530c032012-01-17 06:56:22 +00004856 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004857}
4858
Richard Smith774d8b42013-01-08 00:08:23 +00004859/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004860/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004861static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004862 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004863 case InitializedEntity::EK_ArrayElement:
4864 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004865 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004866 case InitializedEntity::EK_New:
4867 case InitializedEntity::EK_Variable:
4868 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004869 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004870 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004871 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004872 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004873 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004874 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004875 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004876 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004877
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004878 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004879 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004880 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004881 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004882 return true;
4883 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004884
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004885 llvm_unreachable("missed an InitializedEntity kind?");
4886}
4887
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004888/// \brief Whether the given entity, when initialized with an object
4889/// created for that initialization, requires destruction.
4890static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4891 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004892 case InitializedEntity::EK_Result:
4893 case InitializedEntity::EK_New:
4894 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004895 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004896 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004897 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004898 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004899 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004900 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004901
Richard Smith774d8b42013-01-08 00:08:23 +00004902 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004903 case InitializedEntity::EK_Variable:
4904 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004905 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004906 case InitializedEntity::EK_Temporary:
4907 case InitializedEntity::EK_ArrayElement:
4908 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004909 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004910 case InitializedEntity::EK_RelatedResult:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004911 return true;
4912 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004913
4914 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004915}
4916
Richard Smith83da2e72011-10-19 16:55:56 +00004917/// \brief Look for copy and move constructors and constructor templates, for
4918/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4919static void LookupCopyAndMoveConstructors(Sema &S,
4920 OverloadCandidateSet &CandidateSet,
4921 CXXRecordDecl *Class,
4922 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004923 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004924 // The container holding the constructors can under certain conditions
4925 // be changed while iterating (e.g. because of deserialization).
4926 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004927 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004928 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004929 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4930 NamedDecl *D = *CI;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004931 CXXConstructorDecl *Constructor = nullptr;
Richard Smith83da2e72011-10-19 16:55:56 +00004932
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004933 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004934 // Handle copy/moveconstructors, only.
4935 if (!Constructor || Constructor->isInvalidDecl() ||
4936 !Constructor->isCopyOrMoveConstructor() ||
4937 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4938 continue;
4939
4940 DeclAccessPair FoundDecl
4941 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4942 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004943 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004944 continue;
4945 }
4946
4947 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004948 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004949 if (ConstructorTmpl->isInvalidDecl())
4950 continue;
4951
4952 Constructor = cast<CXXConstructorDecl>(
4953 ConstructorTmpl->getTemplatedDecl());
4954 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4955 continue;
4956
4957 // FIXME: Do we need to limit this to copy-constructor-like
4958 // candidates?
4959 DeclAccessPair FoundDecl
4960 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004961 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004962 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004963 }
4964}
4965
4966/// \brief Get the location at which initialization diagnostics should appear.
4967static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4968 Expr *Initializer) {
4969 switch (Entity.getKind()) {
4970 case InitializedEntity::EK_Result:
4971 return Entity.getReturnLoc();
4972
4973 case InitializedEntity::EK_Exception:
4974 return Entity.getThrowLoc();
4975
4976 case InitializedEntity::EK_Variable:
4977 return Entity.getDecl()->getLocation();
4978
Douglas Gregor47736542012-02-15 16:57:26 +00004979 case InitializedEntity::EK_LambdaCapture:
4980 return Entity.getCaptureLoc();
4981
Richard Smith83da2e72011-10-19 16:55:56 +00004982 case InitializedEntity::EK_ArrayElement:
4983 case InitializedEntity::EK_Member:
4984 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004985 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith83da2e72011-10-19 16:55:56 +00004986 case InitializedEntity::EK_Temporary:
4987 case InitializedEntity::EK_New:
4988 case InitializedEntity::EK_Base:
4989 case InitializedEntity::EK_Delegating:
4990 case InitializedEntity::EK_VectorElement:
4991 case InitializedEntity::EK_ComplexElement:
4992 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004993 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004994 case InitializedEntity::EK_RelatedResult:
Richard Smith83da2e72011-10-19 16:55:56 +00004995 return Initializer->getLocStart();
4996 }
4997 llvm_unreachable("missed an InitializedEntity kind?");
4998}
4999
Douglas Gregor523d46a2010-04-18 07:40:54 +00005000/// \brief Make a (potentially elidable) temporary copy of the object
5001/// provided by the given initializer by calling the appropriate copy
5002/// constructor.
5003///
5004/// \param S The Sema object used for type-checking.
5005///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00005006/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00005007/// the type of the initializer expression or a superclass thereof.
5008///
James Dennett1dfbd922012-06-14 21:40:34 +00005009/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00005010///
5011/// \param CurInit The initializer expression.
5012///
5013/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5014/// is permitted in C++03 (but not C++0x) when binding a reference to
5015/// an rvalue.
5016///
5017/// \returns An expression that copies the initializer expression into
5018/// a temporary object, or an error expression if a copy could not be
5019/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00005020static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005021 QualType T,
5022 const InitializedEntity &Entity,
5023 ExprResult CurInit,
5024 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005025 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00005026 Expr *CurInitExpr = (Expr *)CurInit.get();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005027 CXXRecordDecl *Class = nullptr;
Douglas Gregor523d46a2010-04-18 07:40:54 +00005028 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00005029 Class = cast<CXXRecordDecl>(Record->getDecl());
5030 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005031 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00005032
Douglas Gregorf5d8f462011-01-21 18:05:27 +00005033 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00005034 // When certain criteria are met, an implementation is allowed to
5035 // omit the copy/move construction of a class object, even if the
5036 // copy/move constructor and/or destructor for the object have
5037 // side effects. [...]
5038 // - when a temporary class object that has not been bound to a
5039 // reference (12.2) would be copied/moved to a class object
5040 // with the same cv-unqualified type, the copy/move operation
5041 // can be omitted by constructing the temporary object
5042 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005043 //
Douglas Gregor2f599792010-04-02 18:24:57 +00005044 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00005045 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005046 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00005047 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00005048 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00005049 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00005050
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005051 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00005052 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005053 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00005054
Douglas Gregorcc15f012011-01-21 19:38:21 +00005055 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00005056 // Only consider constructors and constructor templates. Per
5057 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5058 // is direct-initialization.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005059 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith83da2e72011-10-19 16:55:56 +00005060 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005061
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005062 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5063
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005064 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00005065 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005066 case OR_Success:
5067 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005068
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005069 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00005070 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5071 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5072 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00005073 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005074 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005075 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00005076 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00005077 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005078 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005079
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005080 case OR_Ambiguous:
5081 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00005082 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005083 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005084 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00005085 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005086
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005087 case OR_Deleted:
5088 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00005089 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005090 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00005091 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00005092 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005093 }
5094
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005095 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005096 SmallVector<Expr*, 8> ConstructorArgs;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005097 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00005098
Anders Carlsson9a68a672010-04-21 18:47:17 +00005099 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00005100 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00005101
5102 if (IsExtraneousCopy) {
5103 // If this is a totally extraneous copy for C++03 reference
5104 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00005105 // expression. We don't generate an (elided) copy operation here
5106 // because doing so would require us to pass down a flag to avoid
5107 // infinite recursion, where each step adds another extraneous,
5108 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00005109
Douglas Gregor2559a702010-04-18 07:57:34 +00005110 // Instantiate the default arguments of any extra parameters in
5111 // the selected copy constructor, as if we were going to create a
5112 // proper call to the copy constructor.
5113 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5114 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5115 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005116 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00005117 break;
5118
5119 // Build the default argument expression; we don't actually care
5120 // if this succeeds or not, because this routine will complain
5121 // if there was a problem.
5122 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5123 }
5124
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005125 return CurInitExpr;
Douglas Gregor523d46a2010-04-18 07:40:54 +00005126 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005127
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005128 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00005129 // constructor call (we might have derived-to-base conversions, or
5130 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005131 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005132 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005133
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005134 // Actually perform the constructor call.
5135 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005136 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005137 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005138 /*ListInit*/ false,
Stephen Hines176edba2014-12-01 14:53:08 -08005139 /*StdInitListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005140 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005141 CXXConstructExpr::CK_Complete,
5142 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005143
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005144 // If we're supposed to bind temporaries, do so.
5145 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005146 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005147 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005148}
Douglas Gregor20093b42009-12-09 23:02:17 +00005149
Richard Smith83da2e72011-10-19 16:55:56 +00005150/// \brief Check whether elidable copy construction for binding a reference to
5151/// a temporary would have succeeded if we were building in C++98 mode, for
5152/// -Wc++98-compat.
5153static void CheckCXX98CompatAccessibleCopy(Sema &S,
5154 const InitializedEntity &Entity,
5155 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00005156 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00005157
5158 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5159 if (!Record)
5160 return;
5161
5162 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005163 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smith83da2e72011-10-19 16:55:56 +00005164 return;
5165
5166 // Find constructors which would have been considered.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005167 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith83da2e72011-10-19 16:55:56 +00005168 LookupCopyAndMoveConstructors(
5169 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5170
5171 // Perform overload resolution.
5172 OverloadCandidateSet::iterator Best;
5173 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5174
5175 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5176 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5177 << CurInitExpr->getSourceRange();
5178
5179 switch (OR) {
5180 case OR_Success:
5181 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00005182 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00005183 // FIXME: Check default arguments as far as that's possible.
5184 break;
5185
5186 case OR_No_Viable_Function:
5187 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005188 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005189 break;
5190
5191 case OR_Ambiguous:
5192 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005193 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005194 break;
5195
5196 case OR_Deleted:
5197 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005198 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00005199 break;
5200 }
5201}
5202
Douglas Gregora41a8c52010-04-22 00:20:18 +00005203void InitializationSequence::PrintInitLocationNote(Sema &S,
5204 const InitializedEntity &Entity) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005205 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregora41a8c52010-04-22 00:20:18 +00005206 if (Entity.getDecl()->getLocation().isInvalid())
5207 return;
5208
5209 if (Entity.getDecl()->getDeclName())
5210 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5211 << Entity.getDecl()->getDeclName();
5212 else
5213 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5214 }
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005215 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5216 Entity.getMethodDecl())
5217 S.Diag(Entity.getMethodDecl()->getLocation(),
5218 diag::note_method_return_type_change)
5219 << Entity.getMethodDecl()->getDeclName();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005220}
5221
Sebastian Redl3b802322011-07-14 19:07:55 +00005222static bool isReferenceBinding(const InitializationSequence::Step &s) {
5223 return s.Kind == InitializationSequence::SK_BindReference ||
5224 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5225}
5226
Jordan Rose2624b812013-05-06 16:48:12 +00005227/// Returns true if the parameters describe a constructor initialization of
5228/// an explicit temporary object, e.g. "Point(x, y)".
5229static bool isExplicitTemporary(const InitializedEntity &Entity,
5230 const InitializationKind &Kind,
5231 unsigned NumArgs) {
5232 switch (Entity.getKind()) {
5233 case InitializedEntity::EK_Temporary:
5234 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005235 case InitializedEntity::EK_RelatedResult:
Jordan Rose2624b812013-05-06 16:48:12 +00005236 break;
5237 default:
5238 return false;
5239 }
5240
5241 switch (Kind.getKind()) {
5242 case InitializationKind::IK_DirectList:
5243 return true;
5244 // FIXME: Hack to work around cast weirdness.
5245 case InitializationKind::IK_Direct:
5246 case InitializationKind::IK_Value:
5247 return NumArgs != 1;
5248 default:
5249 return false;
5250 }
5251}
5252
Sebastian Redl10f04a62011-12-22 14:44:04 +00005253static ExprResult
5254PerformConstructorInitialization(Sema &S,
5255 const InitializedEntity &Entity,
5256 const InitializationKind &Kind,
5257 MultiExprArg Args,
5258 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005259 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005260 bool IsListInitialization,
Stephen Hines176edba2014-12-01 14:53:08 -08005261 bool IsStdInitListInitialization,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005262 SourceLocation LBraceLoc,
5263 SourceLocation RBraceLoc) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005264 unsigned NumArgs = Args.size();
5265 CXXConstructorDecl *Constructor
5266 = cast<CXXConstructorDecl>(Step.Function.Function);
5267 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5268
5269 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005270 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005271 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5272 ? Kind.getEqualLoc()
5273 : Kind.getLocation();
5274
5275 if (Kind.getKind() == InitializationKind::IK_Default) {
5276 // Force even a trivial, implicit default constructor to be
5277 // semantically checked. We do this explicitly because we don't build
5278 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00005279 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00005280 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00005281 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005282 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5283 }
5284
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005285 ExprResult CurInit((Expr *)nullptr);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005286
Douglas Gregored878af2012-02-24 23:56:31 +00005287 // C++ [over.match.copy]p1:
5288 // - When initializing a temporary to be bound to the first parameter
5289 // of a constructor that takes a reference to possibly cv-qualified
5290 // T as its first argument, called with a single argument in the
5291 // context of direct-initialization, explicit conversion functions
5292 // are also considered.
5293 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5294 Args.size() == 1 &&
5295 Constructor->isCopyOrMoveConstructor();
5296
Sebastian Redl10f04a62011-12-22 14:44:04 +00005297 // Determine the arguments required to actually perform the constructor
5298 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005299 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00005300 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00005301 AllowExplicitConv,
5302 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005303 return ExprError();
5304
5305
Jordan Rose2624b812013-05-06 16:48:12 +00005306 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005307 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00005308 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005309 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5310 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005311
5312 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5313 if (!TSInfo)
5314 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella1245a542013-09-07 05:49:53 +00005315 SourceRange ParenOrBraceRange =
5316 (Kind.getKind() == InitializationKind::IK_DirectList)
5317 ? SourceRange(LBraceLoc, RBraceLoc)
5318 : Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005319
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005320 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5321 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5322 HadMultipleCandidates, IsListInitialization,
Stephen Hines176edba2014-12-01 14:53:08 -08005323 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005324 } else {
5325 CXXConstructExpr::ConstructionKind ConstructKind =
5326 CXXConstructExpr::CK_Complete;
5327
5328 if (Entity.getKind() == InitializedEntity::EK_Base) {
5329 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5330 CXXConstructExpr::CK_VirtualBase :
5331 CXXConstructExpr::CK_NonVirtualBase;
5332 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5333 ConstructKind = CXXConstructExpr::CK_Delegating;
5334 }
5335
Stephen Hines651f13c2014-04-23 16:59:28 -07005336 // Only get the parenthesis or brace range if it is a list initialization or
5337 // direct construction.
5338 SourceRange ParenOrBraceRange;
5339 if (IsListInitialization)
5340 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5341 else if (Kind.getKind() == InitializationKind::IK_Direct)
5342 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005343
5344 // If the entity allows NRVO, mark the construction as elidable
5345 // unconditionally.
5346 if (Entity.allowsNRVO())
5347 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5348 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005349 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005350 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005351 IsListInitialization,
Stephen Hines176edba2014-12-01 14:53:08 -08005352 IsStdInitListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005353 ConstructorInitRequiresZeroInit,
5354 ConstructKind,
Stephen Hines651f13c2014-04-23 16:59:28 -07005355 ParenOrBraceRange);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005356 else
5357 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5358 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005359 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005360 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005361 IsListInitialization,
Stephen Hines176edba2014-12-01 14:53:08 -08005362 IsStdInitListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005363 ConstructorInitRequiresZeroInit,
5364 ConstructKind,
Stephen Hines651f13c2014-04-23 16:59:28 -07005365 ParenOrBraceRange);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005366 }
5367 if (CurInit.isInvalid())
5368 return ExprError();
5369
5370 // Only check access if all of that succeeded.
5371 S.CheckConstructorAccess(Loc, Constructor, Entity,
5372 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005373 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5374 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005375
5376 if (shouldBindAsTemporary(Entity))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005377 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redl10f04a62011-12-22 14:44:04 +00005378
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005379 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005380}
5381
Richard Smith36d02af2012-06-04 22:27:30 +00005382/// Determine whether the specified InitializedEntity definitely has a lifetime
5383/// longer than the current full-expression. Conservatively returns false if
5384/// it's unclear.
5385static bool
5386InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5387 const InitializedEntity *Top = &Entity;
5388 while (Top->getParent())
5389 Top = Top->getParent();
5390
5391 switch (Top->getKind()) {
5392 case InitializedEntity::EK_Variable:
5393 case InitializedEntity::EK_Result:
5394 case InitializedEntity::EK_Exception:
5395 case InitializedEntity::EK_Member:
5396 case InitializedEntity::EK_New:
5397 case InitializedEntity::EK_Base:
5398 case InitializedEntity::EK_Delegating:
5399 return true;
5400
5401 case InitializedEntity::EK_ArrayElement:
5402 case InitializedEntity::EK_VectorElement:
5403 case InitializedEntity::EK_BlockElement:
5404 case InitializedEntity::EK_ComplexElement:
5405 // Could not determine what the full initialization is. Assume it might not
5406 // outlive the full-expression.
5407 return false;
5408
5409 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005410 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith36d02af2012-06-04 22:27:30 +00005411 case InitializedEntity::EK_Temporary:
5412 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005413 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005414 case InitializedEntity::EK_RelatedResult:
Richard Smith36d02af2012-06-04 22:27:30 +00005415 // The entity being initialized might not outlive the full-expression.
5416 return false;
5417 }
5418
5419 llvm_unreachable("unknown entity kind");
5420}
5421
Richard Smith211c8dd2013-06-05 00:46:14 +00005422/// Determine the declaration which an initialized entity ultimately refers to,
5423/// for the purpose of lifetime-extending a temporary bound to a reference in
5424/// the initialization of \p Entity.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005425static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5426 const InitializedEntity *Entity,
5427 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005428 // C++11 [class.temporary]p5:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005429 switch (Entity->getKind()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005430 case InitializedEntity::EK_Variable:
5431 // The temporary [...] persists for the lifetime of the reference
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005432 return Entity;
Richard Smith211c8dd2013-06-05 00:46:14 +00005433
5434 case InitializedEntity::EK_Member:
5435 // For subobjects, we look at the complete object.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005436 if (Entity->getParent())
5437 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5438 Entity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005439
5440 // except:
5441 // -- A temporary bound to a reference member in a constructor's
5442 // ctor-initializer persists until the constructor exits.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005443 return Entity;
Richard Smith211c8dd2013-06-05 00:46:14 +00005444
5445 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005446 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith211c8dd2013-06-05 00:46:14 +00005447 // -- A temporary bound to a reference parameter in a function call
5448 // persists until the completion of the full-expression containing
5449 // the call.
5450 case InitializedEntity::EK_Result:
5451 // -- The lifetime of a temporary bound to the returned value in a
5452 // function return statement is not extended; the temporary is
5453 // destroyed at the end of the full-expression in the return statement.
5454 case InitializedEntity::EK_New:
5455 // -- A temporary bound to a reference in a new-initializer persists
5456 // until the completion of the full-expression containing the
5457 // new-initializer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005458 return nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00005459
5460 case InitializedEntity::EK_Temporary:
5461 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005462 case InitializedEntity::EK_RelatedResult:
Richard Smith211c8dd2013-06-05 00:46:14 +00005463 // We don't yet know the storage duration of the surrounding temporary.
5464 // Assume it's got full-expression duration for now, it will patch up our
5465 // storage duration if that's not correct.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005466 return nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00005467
5468 case InitializedEntity::EK_ArrayElement:
5469 // For subobjects, we look at the complete object.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005470 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5471 FallbackDecl);
Richard Smith211c8dd2013-06-05 00:46:14 +00005472
5473 case InitializedEntity::EK_Base:
5474 case InitializedEntity::EK_Delegating:
5475 // We can reach this case for aggregate initialization in a constructor:
5476 // struct A { int &&r; };
5477 // struct B : A { B() : A{0} {} };
5478 // In this case, use the innermost field decl as the context.
5479 return FallbackDecl;
5480
5481 case InitializedEntity::EK_BlockElement:
5482 case InitializedEntity::EK_LambdaCapture:
5483 case InitializedEntity::EK_Exception:
5484 case InitializedEntity::EK_VectorElement:
5485 case InitializedEntity::EK_ComplexElement:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005486 return nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00005487 }
Benjamin Kramer6f773e82013-06-05 15:37:50 +00005488 llvm_unreachable("unknown entity kind");
Richard Smith211c8dd2013-06-05 00:46:14 +00005489}
5490
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005491static void performLifetimeExtension(Expr *Init,
5492 const InitializedEntity *ExtendingEntity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005493
5494/// Update a glvalue expression that is used as the initializer of a reference
5495/// to note that its lifetime is extended.
Richard Smithd6b69872013-06-15 00:30:29 +00005496/// \return \c true if any temporary had its lifetime extended.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005497static bool
5498performReferenceExtension(Expr *Init,
5499 const InitializedEntity *ExtendingEntity) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005500 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5501 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5502 // This is just redundant braces around an initializer. Step over it.
5503 Init = ILE->getInit(0);
5504 }
5505 }
5506
Richard Smithd6b69872013-06-15 00:30:29 +00005507 // Walk past any constructs which we can lifetime-extend across.
5508 Expr *Old;
5509 do {
5510 Old = Init;
5511
5512 // Step over any subobject adjustments; we may have a materialized
5513 // temporary inside them.
5514 SmallVector<const Expr *, 2> CommaLHSs;
5515 SmallVector<SubobjectAdjustment, 2> Adjustments;
5516 Init = const_cast<Expr *>(
5517 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5518
5519 // Per current approach for DR1376, look through casts to reference type
5520 // when performing lifetime extension.
5521 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5522 if (CE->getSubExpr()->isGLValue())
5523 Init = CE->getSubExpr();
5524
5525 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5526 // It's unclear if binding a reference to that xvalue extends the array
5527 // temporary.
5528 } while (Init != Old);
5529
Richard Smith211c8dd2013-06-05 00:46:14 +00005530 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5531 // Update the storage duration of the materialized temporary.
5532 // FIXME: Rebuild the expression instead of mutating it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005533 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5534 ExtendingEntity->allocateManglingNumber());
5535 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smithd6b69872013-06-15 00:30:29 +00005536 return true;
Richard Smith211c8dd2013-06-05 00:46:14 +00005537 }
Richard Smithd6b69872013-06-15 00:30:29 +00005538
5539 return false;
Richard Smith211c8dd2013-06-05 00:46:14 +00005540}
5541
5542/// Update a prvalue expression that is going to be materialized as a
5543/// lifetime-extended temporary.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005544static void performLifetimeExtension(Expr *Init,
5545 const InitializedEntity *ExtendingEntity) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005546 // Dig out the expression which constructs the extended temporary.
5547 SmallVector<const Expr *, 2> CommaLHSs;
5548 SmallVector<SubobjectAdjustment, 2> Adjustments;
5549 Init = const_cast<Expr *>(
5550 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5551
Richard Smith8a07cd32013-06-12 20:42:33 +00005552 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5553 Init = BTE->getSubExpr();
5554
Richard Smith7c3e6152013-06-12 22:31:48 +00005555 if (CXXStdInitializerListExpr *ILE =
Richard Smithd6b69872013-06-15 00:30:29 +00005556 dyn_cast<CXXStdInitializerListExpr>(Init)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005557 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smithd6b69872013-06-15 00:30:29 +00005558 return;
5559 }
Richard Smith7c3e6152013-06-12 22:31:48 +00005560
Richard Smith211c8dd2013-06-05 00:46:14 +00005561 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith7c3e6152013-06-12 22:31:48 +00005562 if (ILE->getType()->isArrayType()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005563 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005564 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005565 return;
5566 }
5567
Richard Smith7c3e6152013-06-12 22:31:48 +00005568 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005569 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5570
5571 // If we lifetime-extend a braced initializer which is initializing an
5572 // aggregate, and that aggregate contains reference members which are
5573 // bound to temporaries, those temporaries are also lifetime-extended.
5574 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5575 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005576 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005577 else {
5578 unsigned Index = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07005579 for (const auto *I : RD->fields()) {
Richard Smith3c3af142013-07-01 06:08:20 +00005580 if (Index >= ILE->getNumInits())
5581 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005582 if (I->isUnnamedBitfield())
5583 continue;
Richard Smith5771aab2013-06-27 22:54:33 +00005584 Expr *SubInit = ILE->getInit(Index);
Richard Smith211c8dd2013-06-05 00:46:14 +00005585 if (I->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005586 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith5771aab2013-06-27 22:54:33 +00005587 else if (isa<InitListExpr>(SubInit) ||
5588 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smith211c8dd2013-06-05 00:46:14 +00005589 // This may be either aggregate-initialization of a member or
5590 // initialization of a std::initializer_list object. Either way,
5591 // we should recursively lifetime-extend that initializer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005592 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smith211c8dd2013-06-05 00:46:14 +00005593 ++Index;
5594 }
5595 }
5596 }
5597 }
5598}
5599
Richard Smith7c3e6152013-06-12 22:31:48 +00005600static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5601 const Expr *Init, bool IsInitializerList,
5602 const ValueDecl *ExtendingDecl) {
5603 // Warn if a field lifetime-extends a temporary.
5604 if (isa<FieldDecl>(ExtendingDecl)) {
5605 if (IsInitializerList) {
5606 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5607 << /*at end of constructor*/true;
5608 return;
5609 }
5610
5611 bool IsSubobjectMember = false;
5612 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5613 Ent = Ent->getParent()) {
5614 if (Ent->getKind() != InitializedEntity::EK_Base) {
5615 IsSubobjectMember = true;
5616 break;
5617 }
5618 }
5619 S.Diag(Init->getExprLoc(),
5620 diag::warn_bind_ref_member_to_temporary)
5621 << ExtendingDecl << Init->getSourceRange()
5622 << IsSubobjectMember << IsInitializerList;
5623 if (IsSubobjectMember)
5624 S.Diag(ExtendingDecl->getLocation(),
5625 diag::note_ref_subobject_of_member_declared_here);
5626 else
5627 S.Diag(ExtendingDecl->getLocation(),
5628 diag::note_ref_or_ptr_member_declared_here)
5629 << /*is pointer*/false;
5630 }
5631}
5632
Richard Smith13b228d2013-09-21 21:19:19 +00005633static void DiagnoseNarrowingInInitList(Sema &S,
5634 const ImplicitConversionSequence &ICS,
5635 QualType PreNarrowingType,
5636 QualType EntityType,
5637 const Expr *PostInit);
5638
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005639ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005640InitializationSequence::Perform(Sema &S,
5641 const InitializedEntity &Entity,
5642 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005643 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005644 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005645 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005646 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005647 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005648 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005649
Sebastian Redl7491c492011-06-05 13:59:11 +00005650 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005651 // If the declaration is a non-dependent, incomplete array type
5652 // that has an initializer, then its type will be completed once
5653 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005654 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005655 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005656 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005657 if (const IncompleteArrayType *ArrayT
5658 = S.Context.getAsIncompleteArrayType(DeclType)) {
5659 // FIXME: We don't currently have the ability to accurately
5660 // compute the length of an initializer list without
5661 // performing full type-checking of the initializer list
5662 // (since we have to determine where braces are implicitly
5663 // introduced and such). So, we fall back to making the array
5664 // type a dependently-sized array type with no specified
5665 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005666 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005667 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005668
Douglas Gregord87b61f2009-12-10 17:56:55 +00005669 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005670 if (DeclaratorDecl *DD = Entity.getDecl()) {
5671 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5672 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005673 if (IncompleteArrayTypeLoc ArrayLoc =
5674 TL.getAs<IncompleteArrayTypeLoc>())
5675 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005676 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005677 }
5678
5679 *ResultType
5680 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005681 /*NumElts=*/nullptr,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005682 ArrayT->getSizeModifier(),
5683 ArrayT->getIndexTypeCVRQualifiers(),
5684 Brackets);
5685 }
5686
5687 }
5688 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005689 if (Kind.getKind() == InitializationKind::IK_Direct &&
5690 !Kind.isExplicitCast()) {
5691 // Rebuild the ParenListExpr.
5692 SourceRange ParenRange = Kind.getParenRange();
5693 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005694 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005695 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005696 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005697 Kind.isExplicitCast() ||
5698 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005699 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005700 }
5701
Sebastian Redl7491c492011-06-05 13:59:11 +00005702 // No steps means no initialization.
5703 if (Steps.empty())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005704 return ExprResult((Expr *)nullptr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005705
Richard Smith80ad52f2013-01-02 11:42:31 +00005706 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005707 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005708 !Entity.isParameterKind()) {
Richard Smith03544fc2012-04-19 06:58:00 +00005709 // Produce a C++98 compatibility warning if we are initializing a reference
5710 // from an initializer list. For parameters, we produce a better warning
5711 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005712 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005713 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5714 << Init->getSourceRange();
5715 }
5716
Richard Smith36d02af2012-06-04 22:27:30 +00005717 // Diagnose cases where we initialize a pointer to an array temporary, and the
5718 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005719 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005720 Entity.getType()->isPointerType() &&
5721 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005722 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005723 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5724 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5725 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5726 << Init->getSourceRange();
5727 }
5728
Douglas Gregord6542d82009-12-22 15:35:07 +00005729 QualType DestType = Entity.getType().getNonReferenceType();
5730 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005731 // the same as Entity.getDecl()->getType() in cases involving type merging,
5732 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005733 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005734 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005735 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005736
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005737 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005738
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005739 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005740 // grab the only argument out the Args and place it into the "current"
5741 // initializer.
5742 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005743 case SK_ResolveAddressOfOverloadedFunction:
5744 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005745 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005746 case SK_CastDerivedToBaseLValue:
5747 case SK_BindReference:
5748 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005749 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005750 case SK_UserConversion:
5751 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005752 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005753 case SK_QualificationConversionRValue:
Stephen Hines176edba2014-12-01 14:53:08 -08005754 case SK_AtomicConversion:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005755 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005756 case SK_ConversionSequence:
Richard Smith13b228d2013-09-21 21:19:19 +00005757 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005758 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005759 case SK_UnwrapInitList:
5760 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005761 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005762 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005763 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005764 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005765 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005766 case SK_PassByIndirectCopyRestore:
5767 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005768 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005769 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005770 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005771 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005772 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005773 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005774 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005775 break;
John McCallf6a16482010-12-04 03:47:34 +00005776 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005777
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005778 case SK_ConstructorInitialization:
Stephen Hines176edba2014-12-01 14:53:08 -08005779 case SK_ConstructorInitializationFromList:
5780 case SK_StdInitializerListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005781 case SK_ZeroInitialization:
5782 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005783 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005784
5785 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005786 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005787 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005788 for (step_iterator Step = step_begin(), StepEnd = step_end();
5789 Step != StepEnd; ++Step) {
5790 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005791 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005792
John Wiegley429bb272011-04-08 18:41:53 +00005793 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005794
Douglas Gregor20093b42009-12-09 23:02:17 +00005795 switch (Step->Kind) {
5796 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005797 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005798 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005799 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005800 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5801 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005802 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005803 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005804 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005805 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005806
Douglas Gregor20093b42009-12-09 23:02:17 +00005807 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005808 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005809 case SK_CastDerivedToBaseLValue: {
5810 // We have a derived-to-base cast that produces either an rvalue or an
5811 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005812
John McCallf871d0c2010-08-07 06:22:56 +00005813 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005814
Douglas Gregor20093b42009-12-09 23:02:17 +00005815 // Casts to inaccessible base classes are allowed with C-style casts.
5816 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5817 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005818 CurInit.get()->getLocStart(),
5819 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005820 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005821 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005822
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005823 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5824 QualType T = SourceType;
5825 if (const PointerType *Pointer = T->getAs<PointerType>())
5826 T = Pointer->getPointeeType();
5827 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005828 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005829 cast<CXXRecordDecl>(RecordTy->getDecl()));
5830 }
5831
John McCall5baba9d2010-08-25 10:28:54 +00005832 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005833 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005834 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005835 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005836 VK_XValue :
5837 VK_RValue);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005838 CurInit =
5839 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5840 CurInit.get(), &BasePath, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005841 break;
5842 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005843
Douglas Gregor20093b42009-12-09 23:02:17 +00005844 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005845 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5846 if (CurInit.get()->refersToBitField()) {
5847 // We don't necessarily have an unambiguous source bit-field.
5848 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005849 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005850 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005851 << (BitField ? BitField->getDeclName() : DeclarationName())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005852 << (BitField != nullptr)
John Wiegley429bb272011-04-08 18:41:53 +00005853 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005854 if (BitField)
5855 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5856
John McCallf312b1e2010-08-26 23:41:50 +00005857 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005858 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005859
John Wiegley429bb272011-04-08 18:41:53 +00005860 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005861 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005862 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5863 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005864 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005865 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005866 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005867 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005868
Douglas Gregor20093b42009-12-09 23:02:17 +00005869 // Reference binding does not have any corresponding ASTs.
5870
5871 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005872 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005873 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005874
Richard Smithd6b69872013-06-15 00:30:29 +00005875 // Even though we didn't materialize a temporary, the binding may still
5876 // extend the lifetime of a temporary. This happens if we bind a reference
5877 // to the result of a cast to reference type.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005878 if (const InitializedEntity *ExtendingEntity =
5879 getEntityForTemporaryLifetimeExtension(&Entity))
5880 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5881 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5882 /*IsInitializerList=*/false,
5883 ExtendingEntity->getDecl());
Richard Smithd6b69872013-06-15 00:30:29 +00005884
Douglas Gregor20093b42009-12-09 23:02:17 +00005885 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005886
Richard Smith211c8dd2013-06-05 00:46:14 +00005887 case SK_BindReferenceToTemporary: {
Jordan Rose1fd1e282013-04-11 00:58:58 +00005888 // Make sure the "temporary" is actually an rvalue.
5889 assert(CurInit.get()->isRValue() && "not a temporary");
5890
Douglas Gregor20093b42009-12-09 23:02:17 +00005891 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005892 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005893 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005894
Douglas Gregor03e80032011-06-21 17:03:29 +00005895 // Materialize the temporary into memory.
Richard Smith8a07cd32013-06-12 20:42:33 +00005896 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smith211c8dd2013-06-05 00:46:14 +00005897 Entity.getType().getNonReferenceType(), CurInit.get(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005898 Entity.getType()->isLValueReferenceType());
5899
5900 // Maybe lifetime-extend the temporary's subobjects to match the
5901 // entity's lifetime.
5902 if (const InitializedEntity *ExtendingEntity =
5903 getEntityForTemporaryLifetimeExtension(&Entity))
5904 if (performReferenceExtension(MTE, ExtendingEntity))
5905 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5906 ExtendingEntity->getDecl());
Douglas Gregord7b23162011-06-22 16:12:01 +00005907
5908 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith8a07cd32013-06-12 20:42:33 +00005909 // need cleanups. Likewise if we're extending this temporary to automatic
5910 // storage duration -- we need to register its cleanup during the
5911 // full-expression's cleanups.
5912 if ((S.getLangOpts().ObjCAutoRefCount &&
5913 MTE->getType()->isObjCLifetimeType()) ||
5914 (MTE->getStorageDuration() == SD_Automatic &&
5915 MTE->getType().isDestructedType()))
Douglas Gregord7b23162011-06-22 16:12:01 +00005916 S.ExprNeedsCleanups = true;
Richard Smith8a07cd32013-06-12 20:42:33 +00005917
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005918 CurInit = MTE;
Douglas Gregor20093b42009-12-09 23:02:17 +00005919 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005920 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005921
Douglas Gregor523d46a2010-04-18 07:40:54 +00005922 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005923 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005924 /*IsExtraneousCopy=*/true);
5925 break;
5926
Douglas Gregor20093b42009-12-09 23:02:17 +00005927 case SK_UserConversion: {
5928 // We have a user-defined conversion that invokes either a constructor
5929 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005930 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005931 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005932 FunctionDecl *Fn = Step->Function.Function;
5933 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005934 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005935 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005936 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005937 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005938 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005939 SourceLocation Loc = CurInit.get()->getLocStart();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005940 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005941
Douglas Gregor20093b42009-12-09 23:02:17 +00005942 // Determine the arguments required to actually perform the constructor
5943 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005944 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005945 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005946 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005947 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005948 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005949
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005950 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005951 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005952 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005953 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005954 /*ListInit*/ false,
Stephen Hines176edba2014-12-01 14:53:08 -08005955 /*StdInitListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005956 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005957 CXXConstructExpr::CK_Complete,
5958 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005959 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005960 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005961
Anders Carlsson9a68a672010-04-21 18:47:17 +00005962 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005963 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005964 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5965 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005966
John McCall2de56d12010-08-25 11:45:40 +00005967 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005968 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5969 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5970 S.IsDerivedFrom(SourceType, Class))
5971 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005972
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005973 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005974 } else {
5975 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005976 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005977 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCall9aa472c2010-03-19 07:35:19 +00005978 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005979 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5980 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005981
5982 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005983 // derived-to-base conversion? I believe the answer is "no", because
5984 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005985 ExprResult CurInitExprRes =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005986 S.PerformObjectArgumentInitialization(CurInit.get(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005987 /*Qualifier=*/nullptr,
John Wiegley429bb272011-04-08 18:41:53 +00005988 FoundFn, Conversion);
5989 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005990 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005991 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005992
Douglas Gregor20093b42009-12-09 23:02:17 +00005993 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005994 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5995 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005996 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005997 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005998
John McCall2de56d12010-08-25 11:45:40 +00005999 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006000
Stephen Hines651f13c2014-04-23 16:59:28 -07006001 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00006002 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006003
Sebastian Redl3b802322011-07-14 19:07:55 +00006004 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00006005 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6006
6007 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00006008 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00006009 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006010 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00006011 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00006012 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00006013 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00006014 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00006015 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6016 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00006017 }
6018 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006019
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006020 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6021 CastKind, CurInit.get(), nullptr,
6022 CurInit.get()->getValueKind());
Abramo Bagnara960809e2011-11-16 22:46:05 +00006023 if (MaybeBindToTemp)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006024 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00006025 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00006026 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006027 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00006028 break;
6029 }
Sebastian Redl906082e2010-07-20 04:20:21 +00006030
Douglas Gregor20093b42009-12-09 23:02:17 +00006031 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00006032 case SK_QualificationConversionXValue:
6033 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00006034 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00006035 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00006036 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00006037 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00006038 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00006039 VK_XValue :
6040 VK_RValue);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006041 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00006042 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006043 }
6044
Stephen Hines176edba2014-12-01 14:53:08 -08006045 case SK_AtomicConversion: {
6046 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6047 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6048 CK_NonAtomicToAtomic, VK_RValue);
6049 break;
6050 }
6051
Jordan Rose1fd1e282013-04-11 00:58:58 +00006052 case SK_LValueToRValue: {
6053 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006054 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6055 CK_LValueToRValue, CurInit.get(),
6056 /*BasePath=*/nullptr, VK_RValue);
Jordan Rose1fd1e282013-04-11 00:58:58 +00006057 break;
6058 }
6059
Richard Smith13b228d2013-09-21 21:19:19 +00006060 case SK_ConversionSequence:
6061 case SK_ConversionSequenceNoNarrowing: {
6062 Sema::CheckedConversionKind CCK
John McCallf85e1932011-06-15 23:02:42 +00006063 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6064 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00006065 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00006066 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00006067 ExprResult CurInitExprRes =
6068 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00006069 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00006070 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006071 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006072 CurInit = CurInitExprRes;
Richard Smith13b228d2013-09-21 21:19:19 +00006073
6074 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6075 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6076 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6077 CurInit.get());
Douglas Gregor20093b42009-12-09 23:02:17 +00006078 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00006079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006080
Douglas Gregord87b61f2009-12-10 17:56:55 +00006081 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00006082 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smith7c3e6152013-06-12 22:31:48 +00006083 // If we're not initializing the top-level entity, we need to create an
6084 // InitializeTemporary entity for our target type.
6085 QualType Ty = Step->Type;
6086 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006087 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00006088 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6089 InitListChecker PerformInitList(S, InitEntity,
Richard Smith40cba902013-06-06 11:41:05 +00006090 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006091 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00006092 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00006093
Richard Smith7c3e6152013-06-12 22:31:48 +00006094 // Hack: We must update *ResultType if available in order to set the
6095 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6096 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6097 if (ResultType &&
6098 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006099 if ((*ResultType)->isRValueReferenceType())
6100 Ty = S.Context.getRValueReferenceType(Ty);
6101 else if ((*ResultType)->isLValueReferenceType())
6102 Ty = S.Context.getLValueReferenceType(Ty,
6103 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6104 *ResultType = Ty;
6105 }
6106
6107 InitListExpr *StructuredInitList =
6108 PerformInitList.getFullyStructuredList();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006109 CurInit.get();
Richard Smith802e2262013-02-02 01:13:06 +00006110 CurInit = shouldBindAsTemporary(InitEntity)
6111 ? S.MaybeBindToTemporary(StructuredInitList)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006112 : StructuredInitList;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006113 break;
6114 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006115
Stephen Hines176edba2014-12-01 14:53:08 -08006116 case SK_ConstructorInitializationFromList: {
Sebastian Redl168319c2012-02-12 16:37:24 +00006117 // When an initializer list is passed for a parameter of type "reference
6118 // to object", we don't get an EK_Temporary entity, but instead an
6119 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00006120 // FIXME: This is a hack. What we really should do is create a user
6121 // conversion step for this case, but this makes it considerably more
6122 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00006123 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6124 Entity.getType().getNonReferenceType());
6125 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00006126 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006127 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00006128 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6129 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00006130 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00006131 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6132 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006133 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00006134 ConstructorInitRequiresZeroInit,
Stephen Hines176edba2014-12-01 14:53:08 -08006135 /*IsListInitialization*/true,
6136 /*IsStdInitListInit*/false,
Enea Zaffanella1245a542013-09-07 05:49:53 +00006137 InitList->getLBraceLoc(),
6138 InitList->getRBraceLoc());
Sebastian Redl10f04a62011-12-22 14:44:04 +00006139 break;
6140 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006141
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006142 case SK_UnwrapInitList:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006143 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006144 break;
6145
6146 case SK_RewrapInitList: {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006147 Expr *E = CurInit.get();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006148 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6149 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00006150 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006151 ILE->setSyntacticForm(Syntactic);
6152 ILE->setType(E->getType());
6153 ILE->setValueKind(E->getValueKind());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006154 CurInit = ILE;
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006155 break;
6156 }
6157
Stephen Hines176edba2014-12-01 14:53:08 -08006158 case SK_ConstructorInitialization:
6159 case SK_StdInitializerListConstructorCall: {
Sebastian Redlbac5cf42012-02-19 12:27:56 +00006160 // When an initializer list is passed for a parameter of type "reference
6161 // to object", we don't get an EK_Temporary entity, but instead an
6162 // EK_Parameter entity with reference type.
6163 // FIXME: This is a hack. What we really should do is create a user
6164 // conversion step for this case, but this makes it considerably more
6165 // complicated. For now, this will do.
6166 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6167 Entity.getType().getNonReferenceType());
6168 bool UseTemporary = Entity.getType()->isReferenceType();
Stephen Hines176edba2014-12-01 14:53:08 -08006169 bool IsStdInitListInit =
6170 Step->Kind == SK_StdInitializerListConstructorCall;
6171 CurInit = PerformConstructorInitialization(
6172 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6173 ConstructorInitRequiresZeroInit,
6174 /*IsListInitialization*/IsStdInitListInit,
6175 /*IsStdInitListInitialization*/IsStdInitListInit,
6176 /*LBraceLoc*/SourceLocation(),
6177 /*RBraceLoc*/SourceLocation());
Douglas Gregor51c56d62009-12-14 20:49:26 +00006178 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00006179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006180
Douglas Gregor71d17402009-12-15 00:01:57 +00006181 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00006182 step_iterator NextStep = Step;
6183 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006184 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00006185 (NextStep->Kind == SK_ConstructorInitialization ||
Stephen Hines176edba2014-12-01 14:53:08 -08006186 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00006187 // The need for zero-initialization is recorded directly into
6188 // the call to the object's constructor within the next step.
6189 ConstructorInitRequiresZeroInit = true;
6190 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006191 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00006192 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00006193 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6194 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006195 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00006196 Kind.getRange().getBegin());
6197
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006198 CurInit = new (S.Context) CXXScalarValueInitExpr(
6199 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6200 Kind.getRange().getEnd());
Douglas Gregor16006c92009-12-16 18:50:27 +00006201 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006202 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor16006c92009-12-16 18:50:27 +00006203 }
Douglas Gregor71d17402009-12-15 00:01:57 +00006204 break;
6205 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006206
6207 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00006208 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006209 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006210 Sema::AssignConvertType ConvTy =
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00006211 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6212 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley429bb272011-04-08 18:41:53 +00006213 if (Result.isInvalid())
6214 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006215 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00006216
6217 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006218 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00006219 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006220 Entity.isParameterKind() &&
John Wiegley429bb272011-04-08 18:41:53 +00006221 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00006222 == Sema::Compatible)
6223 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00006224 if (CurInitExprRes.isInvalid())
6225 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006226 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00006227
Douglas Gregora41a8c52010-04-22 00:20:18 +00006228 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006229 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6230 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00006231 CurInit.get(),
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00006232 getAssignmentAction(Entity, true),
Douglas Gregora41a8c52010-04-22 00:20:18 +00006233 &Complained)) {
6234 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00006235 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00006236 } else if (Complained)
6237 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006238 break;
6239 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006240
6241 case SK_StringInit: {
6242 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00006243 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00006244 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006245 break;
6246 }
Douglas Gregor569c3162010-08-07 11:51:51 +00006247
6248 case SK_ObjCObjectConversion:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006249 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00006250 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00006251 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00006252 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006253
6254 case SK_ArrayInit:
6255 // Okay: we checked everything before creating this step. Note that
6256 // this is a GNU extension.
6257 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00006258 << Step->Type << CurInit.get()->getType()
6259 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006260
6261 // If the destination type is an incomplete array type, update the
6262 // type accordingly.
6263 if (ResultType) {
6264 if (const IncompleteArrayType *IncompleteDest
6265 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6266 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00006267 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006268 *ResultType = S.Context.getConstantArrayType(
6269 IncompleteDest->getElementType(),
6270 ConstantSource->getSize(),
6271 ArrayType::Normal, 0);
6272 }
6273 }
6274 }
John McCallf85e1932011-06-15 23:02:42 +00006275 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006276
Richard Smith0f163e92012-02-15 22:38:09 +00006277 case SK_ParenthesizedArrayInit:
6278 // Okay: we checked everything before creating this step. Note that
6279 // this is a GNU extension.
6280 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6281 << CurInit.get()->getSourceRange();
6282 break;
6283
John McCallf85e1932011-06-15 23:02:42 +00006284 case SK_PassByIndirectCopyRestore:
6285 case SK_PassByIndirectRestore:
6286 checkIndirectCopyRestoreSource(S, CurInit.get());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006287 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6288 CurInit.get(), Step->Type,
6289 Step->Kind == SK_PassByIndirectCopyRestore);
John McCallf85e1932011-06-15 23:02:42 +00006290 break;
6291
6292 case SK_ProduceObjCObject:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006293 CurInit =
6294 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6295 CurInit.get(), nullptr, VK_RValue);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006296 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006297
6298 case SK_StdInitializerList: {
Richard Smith7c3e6152013-06-12 22:31:48 +00006299 S.Diag(CurInit.get()->getExprLoc(),
6300 diag::warn_cxx98_compat_initializer_list_init)
6301 << CurInit.get()->getSourceRange();
Sebastian Redl28357452012-03-05 19:35:43 +00006302
Richard Smith7c3e6152013-06-12 22:31:48 +00006303 // Materialize the temporary into memory.
6304 MaterializeTemporaryExpr *MTE = new (S.Context)
6305 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006306 /*BoundToLvalueReference=*/false);
6307
6308 // Maybe lifetime-extend the array temporary's subobjects to match the
6309 // entity's lifetime.
6310 if (const InitializedEntity *ExtendingEntity =
6311 getEntityForTemporaryLifetimeExtension(&Entity))
6312 if (performReferenceExtension(MTE, ExtendingEntity))
6313 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6314 /*IsInitializerList=*/true,
6315 ExtendingEntity->getDecl());
Richard Smith7c3e6152013-06-12 22:31:48 +00006316
6317 // Wrap it in a construction of a std::initializer_list<T>.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006318 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smith7c3e6152013-06-12 22:31:48 +00006319
6320 // Bind the result, in case the library has given initializer_list a
6321 // non-trivial destructor.
6322 if (shouldBindAsTemporary(Entity))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006323 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redl2b916b82012-01-17 22:49:42 +00006324 break;
6325 }
Richard Smith7c3e6152013-06-12 22:31:48 +00006326
Guy Benyei21f18c42013-02-07 10:55:47 +00006327 case SK_OCLSamplerInit: {
6328 assert(Step->Type->isSamplerT() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07006329 "Sampler initialization on non-sampler type.");
Guy Benyei21f18c42013-02-07 10:55:47 +00006330
6331 QualType SourceType = CurInit.get()->getType();
Guy Benyei21f18c42013-02-07 10:55:47 +00006332
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006333 if (Entity.isParameterKind()) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006334 if (!SourceType->isSamplerT())
6335 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6336 << SourceType;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006337 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006338 llvm_unreachable("Invalid EntityKind!");
6339 }
6340
6341 break;
6342 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00006343 case SK_OCLZeroEvent: {
6344 assert(Step->Type->isEventT() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07006345 "Event initialization on non-event type.");
Guy Benyeie6b9d802013-01-20 12:31:11 +00006346
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006347 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyeie6b9d802013-01-20 12:31:11 +00006348 CK_ZeroToOCLEvent,
6349 CurInit.get()->getValueKind());
6350 break;
6351 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006352 }
6353 }
John McCall15d7d122010-11-11 03:21:53 +00006354
6355 // Diagnose non-fatal problems with the completed initialization.
6356 if (Entity.getKind() == InitializedEntity::EK_Member &&
6357 cast<FieldDecl>(Entity.getDecl())->isBitField())
6358 S.CheckBitFieldInitialization(Kind.getLocation(),
6359 cast<FieldDecl>(Entity.getDecl()),
6360 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006361
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006362 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00006363}
6364
Richard Smithd5bc8672012-12-08 02:01:17 +00006365/// Somewhere within T there is an uninitialized reference subobject.
6366/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00006367static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6368 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006369 if (T->isReferenceType()) {
6370 S.Diag(Loc, diag::err_reference_without_init)
6371 << T.getNonReferenceType();
6372 return true;
6373 }
6374
6375 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6376 if (!RD || !RD->hasUninitializedReferenceMember())
6377 return false;
6378
Stephen Hines651f13c2014-04-23 16:59:28 -07006379 for (const auto *FI : RD->fields()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006380 if (FI->isUnnamedBitfield())
6381 continue;
6382
6383 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6384 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6385 return true;
6386 }
6387 }
6388
Stephen Hines651f13c2014-04-23 16:59:28 -07006389 for (const auto &BI : RD->bases()) {
6390 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006391 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6392 return true;
6393 }
6394 }
6395
6396 return false;
6397}
6398
6399
Douglas Gregor20093b42009-12-09 23:02:17 +00006400//===----------------------------------------------------------------------===//
6401// Diagnose initialization failures
6402//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00006403
6404/// Emit notes associated with an initialization that failed due to a
6405/// "simple" conversion failure.
6406static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6407 Expr *op) {
6408 QualType destType = entity.getType();
6409 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6410 op->getType()->isObjCObjectPointerType()) {
6411
6412 // Emit a possible note about the conversion failing because the
6413 // operand is a message send with a related result type.
6414 S.EmitRelatedResultTypeNote(op);
6415
6416 // Emit a possible note about a return failing because we're
6417 // expecting a related result type.
6418 if (entity.getKind() == InitializedEntity::EK_Result)
6419 S.EmitRelatedResultTypeNoteForReturn(destType);
6420 }
6421}
6422
Bill Wendling2ca3db42013-11-22 00:01:44 +00006423static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6424 InitListExpr *InitList) {
6425 QualType DestType = Entity.getType();
6426
6427 QualType E;
6428 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6429 QualType ArrayType = S.Context.getConstantArrayType(
6430 E.withConst(),
6431 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6432 InitList->getNumInits()),
6433 clang::ArrayType::Normal, 0);
6434 InitializedEntity HiddenArray =
6435 InitializedEntity::InitializeTemporary(ArrayType);
6436 return diagnoseListInit(S, HiddenArray, InitList);
6437 }
6438
Stephen Hines176edba2014-12-01 14:53:08 -08006439 if (DestType->isReferenceType()) {
6440 // A list-initialization failure for a reference means that we tried to
6441 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
6442 // inner initialization failed.
6443 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
6444 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
6445 SourceLocation Loc = InitList->getLocStart();
6446 if (auto *D = Entity.getDecl())
6447 Loc = D->getLocation();
6448 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
6449 return;
6450 }
6451
Bill Wendling2ca3db42013-11-22 00:01:44 +00006452 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6453 /*VerifyOnly=*/false);
6454 assert(DiagnoseInitList.HadError() &&
6455 "Inconsistent init list check result.");
6456}
6457
Stephen Hines176edba2014-12-01 14:53:08 -08006458/// Prints a fixit for adding a null initializer for |Entity|. Call this only
6459/// right after emitting a diagnostic.
6460static void maybeEmitZeroInitializationFixit(Sema &S,
6461 InitializationSequence &Sequence,
6462 const InitializedEntity &Entity) {
6463 if (Entity.getKind() != InitializedEntity::EK_Variable)
6464 return;
6465
6466 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
6467 if (VD->getInit() || VD->getLocEnd().isMacroID())
6468 return;
6469
6470 QualType VariableTy = VD->getType().getCanonicalType();
6471 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
6472 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
6473
6474 S.Diag(Loc, diag::note_add_initializer)
6475 << VD << FixItHint::CreateInsertion(Loc, Init);
6476}
6477
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006478bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00006479 const InitializedEntity &Entity,
6480 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006481 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00006482 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00006483 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006484
Douglas Gregord6542d82009-12-22 15:35:07 +00006485 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00006486 switch (Failure) {
6487 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006488 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006489 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006490 // Dig out the reference subobject which is uninitialized and diagnose it.
6491 // If this is value-initialization, this could be nested some way within
6492 // the target type.
6493 assert(Kind.getKind() == InitializationKind::IK_Value ||
6494 DestType->isReferenceType());
6495 bool Diagnosed =
6496 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6497 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6498 (void)Diagnosed;
6499 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006500 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006501 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00006502 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006503
Douglas Gregor20093b42009-12-09 23:02:17 +00006504 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00006505 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00006506 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00006507 case FK_ArrayNeedsInitListOrStringLiteral:
6508 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6509 break;
6510 case FK_ArrayNeedsInitListOrWideStringLiteral:
6511 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6512 break;
6513 case FK_NarrowStringIntoWideCharArray:
6514 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6515 break;
6516 case FK_WideStringIntoCharArray:
6517 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6518 break;
6519 case FK_IncompatWideStringIntoWideChar:
6520 S.Diag(Kind.getLocation(),
6521 diag::err_array_init_incompat_wide_string_into_wchar);
6522 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006523 case FK_ArrayTypeMismatch:
6524 case FK_NonConstantArrayInit:
Bill Wendling2ca3db42013-11-22 00:01:44 +00006525 S.Diag(Kind.getLocation(),
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006526 (Failure == FK_ArrayTypeMismatch
6527 ? diag::err_array_init_different_type
6528 : diag::err_array_init_non_constant_array))
6529 << DestType.getNonReferenceType()
6530 << Args[0]->getType()
6531 << Args[0]->getSourceRange();
6532 break;
6533
John McCall73076432012-01-05 00:13:19 +00006534 case FK_VariableLengthArrayHasInitializer:
6535 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6536 << Args[0]->getSourceRange();
6537 break;
6538
John McCall6bb80172010-03-30 21:47:33 +00006539 case FK_AddressOfOverloadFailed: {
6540 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006541 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00006542 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00006543 true,
6544 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00006545 break;
John McCall6bb80172010-03-30 21:47:33 +00006546 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006547
Douglas Gregor20093b42009-12-09 23:02:17 +00006548 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00006549 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00006550 switch (FailedOverloadResult) {
6551 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006552 if (Failure == FK_UserConversionOverloadFailed)
6553 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6554 << Args[0]->getType() << DestType
6555 << Args[0]->getSourceRange();
6556 else
6557 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6558 << DestType << Args[0]->getType()
6559 << Args[0]->getSourceRange();
6560
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006561 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006562 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006563
Douglas Gregor20093b42009-12-09 23:02:17 +00006564 case OR_No_Viable_Function:
Larisse Voufo288f76a2013-06-27 03:36:30 +00006565 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo7419d012013-06-27 01:50:25 +00006566 DestType.getNonReferenceType(),
6567 diag::err_typecheck_nonviable_condition_incomplete,
6568 Args[0]->getType(), Args[0]->getSourceRange()))
6569 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6570 << Args[0]->getType() << Args[0]->getSourceRange()
6571 << DestType.getNonReferenceType();
6572
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006573 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006574 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006575
Douglas Gregor20093b42009-12-09 23:02:17 +00006576 case OR_Deleted: {
6577 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6578 << Args[0]->getType() << DestType.getNonReferenceType()
6579 << Args[0]->getSourceRange();
6580 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006581 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006582 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6583 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00006584 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00006585 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00006586 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006587 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00006588 }
6589 break;
6590 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006591
Douglas Gregor20093b42009-12-09 23:02:17 +00006592 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006593 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00006594 }
6595 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006596
Douglas Gregor20093b42009-12-09 23:02:17 +00006597 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006598 if (isa<InitListExpr>(Args[0])) {
6599 S.Diag(Kind.getLocation(),
6600 diag::err_lvalue_reference_bind_to_initlist)
6601 << DestType.getNonReferenceType().isVolatileQualified()
6602 << DestType.getNonReferenceType()
6603 << Args[0]->getSourceRange();
6604 break;
6605 }
6606 // Intentional fallthrough
6607
Douglas Gregor20093b42009-12-09 23:02:17 +00006608 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006609 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00006610 Failure == FK_NonConstLValueReferenceBindingToTemporary
6611 ? diag::err_lvalue_reference_bind_to_temporary
6612 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00006613 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00006614 << DestType.getNonReferenceType()
6615 << Args[0]->getType()
6616 << Args[0]->getSourceRange();
6617 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006618
Douglas Gregor20093b42009-12-09 23:02:17 +00006619 case FK_RValueReferenceBindingToLValue:
6620 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00006621 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00006622 << Args[0]->getSourceRange();
6623 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006624
Douglas Gregor20093b42009-12-09 23:02:17 +00006625 case FK_ReferenceInitDropsQualifiers:
6626 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6627 << DestType.getNonReferenceType()
6628 << Args[0]->getType()
6629 << Args[0]->getSourceRange();
6630 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006631
Douglas Gregor20093b42009-12-09 23:02:17 +00006632 case FK_ReferenceInitFailed:
6633 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6634 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006635 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006636 << Args[0]->getType()
6637 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006638 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006640
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006641 case FK_ConversionFailed: {
6642 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006643 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006644 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006645 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006646 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006647 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006648 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006649 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6650 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006651 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006652 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006653 }
John Wiegley429bb272011-04-08 18:41:53 +00006654
6655 case FK_ConversionFromPropertyFailed:
6656 // No-op. This error has already been reported.
6657 break;
6658
Douglas Gregord87b61f2009-12-10 17:56:55 +00006659 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006660 SourceRange R;
6661
6662 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006663 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006664 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006665 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006666 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006667
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006668 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor19311e72010-09-08 21:40:08 +00006669 if (Kind.isCStyleOrFunctionalCast())
6670 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6671 << R;
6672 else
6673 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6674 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006675 break;
6676 }
6677
6678 case FK_ReferenceBindingToInitList:
6679 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6680 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6681 break;
6682
6683 case FK_InitListBadDestinationType:
6684 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6685 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6686 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006687
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006688 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006689 case FK_ConstructorOverloadFailed: {
6690 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006691 if (Args.size())
6692 ArgsRange = SourceRange(Args.front()->getLocStart(),
6693 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006694
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006695 if (Failure == FK_ListConstructorOverloadFailed) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006696 assert(Args.size() == 1 &&
6697 "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006698 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006699 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006700 }
6701
Douglas Gregor51c56d62009-12-14 20:49:26 +00006702 // FIXME: Using "DestType" for the entity we're printing is probably
6703 // bad.
6704 switch (FailedOverloadResult) {
6705 case OR_Ambiguous:
6706 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6707 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006708 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006709 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006710
Douglas Gregor51c56d62009-12-14 20:49:26 +00006711 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006712 if (Kind.getKind() == InitializationKind::IK_Default &&
6713 (Entity.getKind() == InitializedEntity::EK_Base ||
6714 Entity.getKind() == InitializedEntity::EK_Member) &&
6715 isa<CXXConstructorDecl>(S.CurContext)) {
6716 // This is implicit default initialization of a member or
6717 // base within a constructor. If no viable function was
6718 // found, notify the user that she needs to explicitly
6719 // initialize this base/member.
6720 CXXConstructorDecl *Constructor
6721 = cast<CXXConstructorDecl>(S.CurContext);
6722 if (Entity.getKind() == InitializedEntity::EK_Base) {
6723 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006724 << (Constructor->getInheritedConstructor() ? 2 :
6725 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006726 << S.Context.getTypeDeclType(Constructor->getParent())
6727 << /*base=*/0
6728 << Entity.getType();
6729
6730 RecordDecl *BaseDecl
6731 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6732 ->getDecl();
6733 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6734 << S.Context.getTagDeclType(BaseDecl);
6735 } else {
6736 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006737 << (Constructor->getInheritedConstructor() ? 2 :
6738 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006739 << S.Context.getTypeDeclType(Constructor->getParent())
6740 << /*member=*/1
6741 << Entity.getName();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006742 S.Diag(Entity.getDecl()->getLocation(),
6743 diag::note_member_declared_at);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006744
6745 if (const RecordType *Record
6746 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006747 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006748 diag::note_previous_decl)
6749 << S.Context.getTagDeclType(Record->getDecl());
6750 }
6751 break;
6752 }
6753
Douglas Gregor51c56d62009-12-14 20:49:26 +00006754 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6755 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006756 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006757 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006758
Douglas Gregor51c56d62009-12-14 20:49:26 +00006759 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006760 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006761 OverloadingResult Ovl
6762 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006763 if (Ovl != OR_Deleted) {
6764 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6765 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006766 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006767 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006768 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006769
6770 // If this is a defaulted or implicitly-declared function, then
6771 // it was implicitly deleted. Make it clear that the deletion was
6772 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006773 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006774 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006775 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006776 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006777 else
6778 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6779 << true << DestType << ArgsRange;
6780
6781 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006782 break;
6783 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006784
Douglas Gregor51c56d62009-12-14 20:49:26 +00006785 case OR_Success:
6786 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006787 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006788 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006789 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006790
Douglas Gregor99a2e602009-12-16 01:38:02 +00006791 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006792 if (Entity.getKind() == InitializedEntity::EK_Member &&
6793 isa<CXXConstructorDecl>(S.CurContext)) {
6794 // This is implicit default-initialization of a const member in
6795 // a constructor. Complain that it needs to be explicitly
6796 // initialized.
6797 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6798 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006799 << (Constructor->getInheritedConstructor() ? 2 :
6800 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006801 << S.Context.getTypeDeclType(Constructor->getParent())
6802 << /*const=*/1
6803 << Entity.getName();
6804 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6805 << Entity.getName();
6806 } else {
6807 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Stephen Hines176edba2014-12-01 14:53:08 -08006808 << DestType << (bool)DestType->getAs<RecordType>();
6809 maybeEmitZeroInitializationFixit(S, *this, Entity);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006810 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006811 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006812
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006813 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006814 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006815 diag::err_init_incomplete_type);
6816 break;
6817
Sebastian Redl14b0c192011-09-24 17:48:00 +00006818 case FK_ListInitializationFailed: {
6819 // Run the init list checker again to emit diagnostics.
Bill Wendling2ca3db42013-11-22 00:01:44 +00006820 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6821 diagnoseListInit(S, Entity, InitList);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006822 break;
6823 }
John McCall5acb0c92011-10-17 18:40:02 +00006824
6825 case FK_PlaceholderType: {
6826 // FIXME: Already diagnosed!
6827 break;
6828 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006829
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006830 case FK_ExplicitConstructor: {
6831 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6832 << Args[0]->getSourceRange();
6833 OverloadCandidateSet::iterator Best;
6834 OverloadingResult Ovl
6835 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006836 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006837 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6838 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6839 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6840 break;
6841 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006842 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006843
Douglas Gregora41a8c52010-04-22 00:20:18 +00006844 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006845 return true;
6846}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006847
Chris Lattner5f9e2722011-07-23 10:55:15 +00006848void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006849 switch (SequenceKind) {
6850 case FailedSequence: {
6851 OS << "Failed sequence: ";
6852 switch (Failure) {
6853 case FK_TooManyInitsForReference:
6854 OS << "too many initializers for reference";
6855 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006856
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006857 case FK_ArrayNeedsInitList:
6858 OS << "array requires initializer list";
6859 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006860
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006861 case FK_ArrayNeedsInitListOrStringLiteral:
6862 OS << "array requires initializer list or string literal";
6863 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006864
Hans Wennborg0ff50742013-05-15 11:03:04 +00006865 case FK_ArrayNeedsInitListOrWideStringLiteral:
6866 OS << "array requires initializer list or wide string literal";
6867 break;
6868
6869 case FK_NarrowStringIntoWideCharArray:
6870 OS << "narrow string into wide char array";
6871 break;
6872
6873 case FK_WideStringIntoCharArray:
6874 OS << "wide string into char array";
6875 break;
6876
6877 case FK_IncompatWideStringIntoWideChar:
6878 OS << "incompatible wide string into wide char array";
6879 break;
6880
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006881 case FK_ArrayTypeMismatch:
6882 OS << "array type mismatch";
6883 break;
6884
6885 case FK_NonConstantArrayInit:
6886 OS << "non-constant array initializer";
6887 break;
6888
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006889 case FK_AddressOfOverloadFailed:
6890 OS << "address of overloaded function failed";
6891 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006892
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006893 case FK_ReferenceInitOverloadFailed:
6894 OS << "overload resolution for reference initialization failed";
6895 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006896
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006897 case FK_NonConstLValueReferenceBindingToTemporary:
6898 OS << "non-const lvalue reference bound to temporary";
6899 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006900
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006901 case FK_NonConstLValueReferenceBindingToUnrelated:
6902 OS << "non-const lvalue reference bound to unrelated type";
6903 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006904
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006905 case FK_RValueReferenceBindingToLValue:
6906 OS << "rvalue reference bound to an lvalue";
6907 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006908
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006909 case FK_ReferenceInitDropsQualifiers:
6910 OS << "reference initialization drops qualifiers";
6911 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006912
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006913 case FK_ReferenceInitFailed:
6914 OS << "reference initialization failed";
6915 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006916
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006917 case FK_ConversionFailed:
6918 OS << "conversion failed";
6919 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006920
John Wiegley429bb272011-04-08 18:41:53 +00006921 case FK_ConversionFromPropertyFailed:
6922 OS << "conversion from property failed";
6923 break;
6924
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006925 case FK_TooManyInitsForScalar:
6926 OS << "too many initializers for scalar";
6927 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006928
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006929 case FK_ReferenceBindingToInitList:
6930 OS << "referencing binding to initializer list";
6931 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006932
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006933 case FK_InitListBadDestinationType:
6934 OS << "initializer list for non-aggregate, non-scalar type";
6935 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006936
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006937 case FK_UserConversionOverloadFailed:
6938 OS << "overloading failed for user-defined conversion";
6939 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006940
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006941 case FK_ConstructorOverloadFailed:
6942 OS << "constructor overloading failed";
6943 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006944
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006945 case FK_DefaultInitOfConst:
6946 OS << "default initialization of a const variable";
6947 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006948
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006949 case FK_Incomplete:
6950 OS << "initialization of incomplete type";
6951 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006952
6953 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006954 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006955 break;
6956
John McCall73076432012-01-05 00:13:19 +00006957 case FK_VariableLengthArrayHasInitializer:
6958 OS << "variable length array has an initializer";
6959 break;
6960
John McCall5acb0c92011-10-17 18:40:02 +00006961 case FK_PlaceholderType:
6962 OS << "initializer expression isn't contextually valid";
6963 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006964
6965 case FK_ListConstructorOverloadFailed:
6966 OS << "list constructor overloading failed";
6967 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006968
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006969 case FK_ExplicitConstructor:
6970 OS << "list copy initialization chose explicit constructor";
6971 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006972 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006973 OS << '\n';
6974 return;
6975 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006976
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006977 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006978 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006979 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006980
Sebastian Redl7491c492011-06-05 13:59:11 +00006981 case NormalSequence:
6982 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006983 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006984 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006985
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006986 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6987 if (S != step_begin()) {
6988 OS << " -> ";
6989 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006990
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006991 switch (S->Kind) {
6992 case SK_ResolveAddressOfOverloadedFunction:
6993 OS << "resolve address of overloaded function";
6994 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006995
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006996 case SK_CastDerivedToBaseRValue:
6997 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6998 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006999
Sebastian Redl906082e2010-07-20 04:20:21 +00007000 case SK_CastDerivedToBaseXValue:
7001 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7002 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007003
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007004 case SK_CastDerivedToBaseLValue:
7005 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7006 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007007
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007008 case SK_BindReference:
7009 OS << "bind reference to lvalue";
7010 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007011
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007012 case SK_BindReferenceToTemporary:
7013 OS << "bind reference to a temporary";
7014 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007015
Douglas Gregor523d46a2010-04-18 07:40:54 +00007016 case SK_ExtraneousCopyToTemporary:
7017 OS << "extraneous C++03 copy to temporary";
7018 break;
7019
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007020 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00007021 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007022 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00007023
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007024 case SK_QualificationConversionRValue:
7025 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00007026 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007027
Sebastian Redl906082e2010-07-20 04:20:21 +00007028 case SK_QualificationConversionXValue:
7029 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00007030 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00007031
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007032 case SK_QualificationConversionLValue:
7033 OS << "qualification conversion (lvalue)";
7034 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007035
Stephen Hines176edba2014-12-01 14:53:08 -08007036 case SK_AtomicConversion:
7037 OS << "non-atomic-to-atomic conversion";
7038 break;
7039
Jordan Rose1fd1e282013-04-11 00:58:58 +00007040 case SK_LValueToRValue:
7041 OS << "load (lvalue to rvalue)";
7042 break;
7043
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007044 case SK_ConversionSequence:
7045 OS << "implicit conversion sequence (";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +00007046 S->ICS->dump(); // FIXME: use OS
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007047 OS << ")";
7048 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007049
Richard Smith13b228d2013-09-21 21:19:19 +00007050 case SK_ConversionSequenceNoNarrowing:
7051 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +00007052 S->ICS->dump(); // FIXME: use OS
Richard Smith13b228d2013-09-21 21:19:19 +00007053 OS << ")";
7054 break;
7055
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007056 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00007057 OS << "list aggregate initialization";
7058 break;
7059
Sebastian Redl13dc8f92011-11-27 16:50:07 +00007060 case SK_UnwrapInitList:
7061 OS << "unwrap reference initializer list";
7062 break;
7063
7064 case SK_RewrapInitList:
7065 OS << "rewrap reference initializer list";
7066 break;
7067
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007068 case SK_ConstructorInitialization:
7069 OS << "constructor initialization";
7070 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007071
Stephen Hines176edba2014-12-01 14:53:08 -08007072 case SK_ConstructorInitializationFromList:
7073 OS << "list initialization via constructor";
7074 break;
7075
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007076 case SK_ZeroInitialization:
7077 OS << "zero initialization";
7078 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007079
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007080 case SK_CAssignment:
7081 OS << "C assignment";
7082 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007083
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007084 case SK_StringInit:
7085 OS << "string initialization";
7086 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00007087
7088 case SK_ObjCObjectConversion:
7089 OS << "Objective-C object conversion";
7090 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00007091
7092 case SK_ArrayInit:
7093 OS << "array initialization";
7094 break;
John McCallf85e1932011-06-15 23:02:42 +00007095
Richard Smith0f163e92012-02-15 22:38:09 +00007096 case SK_ParenthesizedArrayInit:
7097 OS << "parenthesized array initialization";
7098 break;
7099
John McCallf85e1932011-06-15 23:02:42 +00007100 case SK_PassByIndirectCopyRestore:
7101 OS << "pass by indirect copy and restore";
7102 break;
7103
7104 case SK_PassByIndirectRestore:
7105 OS << "pass by indirect restore";
7106 break;
7107
7108 case SK_ProduceObjCObject:
7109 OS << "Objective-C object retension";
7110 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00007111
7112 case SK_StdInitializerList:
7113 OS << "std::initializer_list from initializer list";
7114 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007115
Stephen Hines176edba2014-12-01 14:53:08 -08007116 case SK_StdInitializerListConstructorCall:
7117 OS << "list initialization from std::initializer_list";
7118 break;
7119
Guy Benyei21f18c42013-02-07 10:55:47 +00007120 case SK_OCLSamplerInit:
7121 OS << "OpenCL sampler_t from integer constant";
7122 break;
7123
Guy Benyeie6b9d802013-01-20 12:31:11 +00007124 case SK_OCLZeroEvent:
7125 OS << "OpenCL event_t from zero";
7126 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007127 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00007128
7129 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007130 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00007131
7132 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00007133}
7134
7135void InitializationSequence::dump() const {
7136 dump(llvm::errs());
7137}
7138
Richard Smith13b228d2013-09-21 21:19:19 +00007139static void DiagnoseNarrowingInInitList(Sema &S,
7140 const ImplicitConversionSequence &ICS,
7141 QualType PreNarrowingType,
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007142 QualType EntityType,
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007143 const Expr *PostInit) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007144 const StandardConversionSequence *SCS = nullptr;
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007145 switch (ICS.getKind()) {
7146 case ImplicitConversionSequence::StandardConversion:
7147 SCS = &ICS.Standard;
7148 break;
7149 case ImplicitConversionSequence::UserDefinedConversion:
7150 SCS = &ICS.UserDefined.After;
7151 break;
7152 case ImplicitConversionSequence::AmbiguousConversion:
7153 case ImplicitConversionSequence::EllipsisConversion:
7154 case ImplicitConversionSequence::BadConversion:
7155 return;
7156 }
7157
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007158 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7159 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00007160 QualType ConstantType;
7161 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7162 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007163 case NK_Not_Narrowing:
7164 // No narrowing occurred.
7165 return;
7166
7167 case NK_Type_Narrowing:
7168 // This was a floating-to-integer conversion, which is always considered a
7169 // narrowing conversion even if the value is a constant and can be
7170 // represented exactly as an integer.
7171 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007172 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7173 ? diag::warn_init_list_type_narrowing
7174 : diag::ext_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007175 << PostInit->getSourceRange()
7176 << PreNarrowingType.getLocalUnqualifiedType()
7177 << EntityType.getLocalUnqualifiedType();
7178 break;
7179
7180 case NK_Constant_Narrowing:
7181 // A constant value was narrowed.
7182 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007183 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7184 ? diag::warn_init_list_constant_narrowing
7185 : diag::ext_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007186 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00007187 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00007188 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007189 break;
7190
7191 case NK_Variable_Narrowing:
7192 // A variable's value may have been narrowed.
7193 S.Diag(PostInit->getLocStart(),
Richard Smith3347b492013-11-12 02:41:45 +00007194 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7195 ? diag::warn_init_list_variable_narrowing
7196 : diag::ext_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007197 << PostInit->getSourceRange()
7198 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00007199 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007200 break;
7201 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007202
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007203 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007204 llvm::raw_svector_ostream OS(StaticCast);
7205 OS << "static_cast<";
7206 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7207 // It's important to use the typedef's name if there is one so that the
7208 // fixit doesn't break code using types like int64_t.
7209 //
7210 // FIXME: This will break if the typedef requires qualification. But
7211 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00007212 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007213 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00007214 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007215 else {
7216 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7217 // with a broken cast.
7218 return;
7219 }
7220 OS << ">(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007221 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
7222 << PostInit->getSourceRange()
7223 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7224 << FixItHint::CreateInsertion(
7225 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007226}
7227
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007228//===----------------------------------------------------------------------===//
7229// Initialization helper functions
7230//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00007231bool
7232Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7233 ExprResult Init) {
7234 if (Init.isInvalid())
7235 return false;
7236
7237 Expr *InitE = Init.get();
7238 assert(InitE && "No initialization expression");
7239
Douglas Gregor3c394c52012-07-31 22:15:04 +00007240 InitializationKind Kind
7241 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007242 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00007243 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00007244}
7245
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007246ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007247Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7248 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007249 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00007250 bool TopLevelOfInitList,
7251 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007252 if (Init.isInvalid())
7253 return ExprError();
7254
John McCall15d7d122010-11-11 03:21:53 +00007255 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007256 assert(InitE && "No initialization expression?");
7257
7258 if (EqualLoc.isInvalid())
7259 EqualLoc = InitE->getLocStart();
7260
7261 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00007262 EqualLoc,
7263 AllowExplicit);
Richard Smith13b228d2013-09-21 21:19:19 +00007264 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007265 Init.get();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007266
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007267 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007268
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007269 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007270}