blob: 5692d6e8f21c29fcf4a5d42881e6647dd46cbd93 [file] [log] [blame]
Steve Narofff8ecff22008-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 Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Hans Wennborg8f62c5c2013-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 Friedman893abe42009-05-29 18:22:49 +000061 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000062 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000063
Chris Lattnera9196812009-02-26 23:26:43 +000064 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000069 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000070
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000073 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000074 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000075
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000076 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-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 Wennborg8f62c5c2013-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 Gregorfb65e592011-07-27 05:40:30 +000094 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-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 Gregorfb65e592011-07-27 05:40:30 +0000102 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-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 Gregorfb65e592011-07-27 05:40:30 +0000110 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-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 Gregorfb65e592011-07-27 05:40:30 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregorfb65e592011-07-27 05:40:30 +0000120 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000121}
122
Hans Wennborg950f3182013-05-16 09:22:40 +0000123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000125 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000129}
130
Richard Smith430c23b2013-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 Smithd74b16062013-05-06 00:35:47 +0000134 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000135 E->setType(Ty);
Richard Smithd74b16062013-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 Smith430c23b2013-05-05 16:40:13 +0000146 }
Richard Smith430c23b2013-05-05 16:40:13 +0000147}
148
John McCall5decec92011-02-21 07:57:55 +0000149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000151 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000152 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000153 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000154 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner0cb78032009-02-24 22:27:37 +0000156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000158 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000159 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000160 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000164 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000165 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Eli Friedman893abe42009-05-29 18:22:49 +0000168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Eli Friedman554eba92011-04-11 00:23:45 +0000170 // We have an array of character type with known size. However,
Eli Friedman893abe42009-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000173 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-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 Friedman554eba92011-04-11 00:23:45 +0000183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000185 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-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 Dunbar62ee6412012-03-09 18:35:03 +0000191 S.Diag(Str->getLocStart(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000192 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000193 << Str->getSourceRange();
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Eli Friedman893abe42009-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 Smith430c23b2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000201}
202
Chris Lattner0cb78032009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Douglas Gregorcde232f2009-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 Bagnara92141d22011-01-27 19:55:10 +0000221/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-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 Lattner9ececce2009-02-24 22:48:58 +0000234namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000235class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000236 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000237 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000238 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Anders Carlsson6cabf312010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000248 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000249 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000250 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000251 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000252 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000257 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000258 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000259 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-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 Carlsson6cabf312010-01-23 23:23:01 +0000267 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000268 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000269 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000274 unsigned &Index,
275 InitListExpr *StructuredList,
276 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000277 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000278 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000282 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000283 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000284 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000286 unsigned &StructuredIndex,
287 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000288 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000289 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000290 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000294 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000295 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000296 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000297 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000303 bool FinishSubobjectInit,
304 bool TopLevelObject);
Douglas Gregor85df8d82009-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 Gregorcde232f2009-01-29 01:05:33 +0000310 void UpdateStructuredListElement(InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000312 Expr *expr);
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000315
Richard Smith454a7cd2014-06-03 08:26:00 +0000316 static ExprResult PerformEmptyInit(Sema &SemaRef,
317 SourceLocation Loc,
318 const InitializedEntity &Entity,
319 bool VerifyOnly);
320 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 const InitializedEntity &ParentEntity,
322 InitListExpr *ILE, bool &RequiresSecondPass);
Richard Smith454a7cd2014-06-03 08:26:00 +0000323 void FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000324 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000325 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
326 Expr *InitExpr, FieldDecl *Field,
327 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000328 void CheckEmptyInitializable(const InitializedEntity &Entity,
329 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000330
Douglas Gregor85df8d82009-01-29 00:45:39 +0000331public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000332 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000333 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-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 Lattner9ececce2009-02-24 22:48:58 +0000340} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000341
Richard Smith454a7cd2014-06-03 08:26:00 +0000342ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
343 SourceLocation Loc,
344 const InitializedEntity &Entity,
345 bool VerifyOnly) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000346 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
347 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000348 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 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000356 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
357 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
358 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000359 // 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);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000380 // 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());
Nico Weber5752ad02014-07-03 00:38:25 +0000403 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000404 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 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000429 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 Redl2b47b7a2011-10-16 18:19:20 +0000452 hadError = true;
453}
454
Richard Smith454a7cd2014-06-03 08:26:00 +0000455void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000456 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000457 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000458 bool &RequiresSecondPass) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000459 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000460 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000462 = InitializedEntity::InitializeMember(Field, &ParentEntity);
463 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000464 // 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 Smith852c9db2013-04-20 22:23:05 +0000468 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000469 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
470 if (DIE.isInvalid()) {
471 hadError = true;
472 return;
473 }
Richard Smith852c9db2013-04-20 22:23:05 +0000474 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000475 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000476 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000477 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000478 RequiresSecondPass = true;
479 }
480 return;
481 }
482
Douglas Gregor2bb07652009-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 Takumif9cbcc42011-01-27 07:10:08 +0000496
Richard Smith454a7cd2014-06-03 08:26:00 +0000497 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
498 /*VerifyOnly*/false);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000499 if (MemberInit.isInvalid()) {
500 hadError = true;
501 return;
502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Douglas Gregor2bb07652009-12-22 00:05:34 +0000504 if (hadError) {
505 // Do nothing
506 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000507 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000508 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
509 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-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.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000513 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000514 RequiresSecondPass = true;
515 }
516 } else if (InitListExpr *InnerILE
517 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000518 FillInEmptyInitializations(MemberEntity, InnerILE,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000520}
521
Douglas Gregor347f7ea2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000525void
Richard Smith454a7cd2014-06-03 08:26:00 +0000526InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000527 InitListExpr *ILE,
528 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000529 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000530 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000531
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000532 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000533 const RecordDecl *RDecl = RType->getDecl();
534 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000535 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Douglas Gregor2bb07652009-12-22 00:05:34 +0000536 Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000537 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
538 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000539 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000540 if (Field->hasInClassInitializer()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000541 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000542 break;
543 }
544 }
545 } else {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000546 unsigned Init = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000547 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000548 if (Field->isUnnamedBitfield())
549 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000550
Douglas Gregor2bb07652009-12-22 00:05:34 +0000551 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000552 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000553
Richard Smith454a7cd2014-06-03 08:26:00 +0000554 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000555 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000556 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000557
Douglas Gregor2bb07652009-12-22 00:05:34 +0000558 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000559
Douglas Gregor2bb07652009-12-22 00:05:34 +0000560 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000561 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000562 break;
563 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000564 }
565
566 return;
Mike Stump11289f42009-09-09 15:08:12 +0000567 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000568
569 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000570
Douglas Gregor723796a2009-12-16 06:35:08 +0000571 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000572 unsigned NumInits = ILE->getNumInits();
573 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000574 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000575 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000576 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
577 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000579 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000580 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000581 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000582 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000584 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000585 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000586 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000587
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000588 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000589 if (hadError)
590 return;
591
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000592 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
593 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000594 ElementEntity.setElementIndex(Init);
595
Craig Topperc3ec1492014-05-26 06:22:03 +0000596 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000597 if (!InitExpr && !ILE->hasArrayFiller()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000598 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
599 ElementEntity,
600 /*VerifyOnly*/false);
Douglas Gregor723796a2009-12-16 06:35:08 +0000601 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000602 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000603 return;
604 }
605
606 if (hadError) {
607 // Do nothing
608 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-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)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000612 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000613 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000614 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-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) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000619 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000620 return;
621 }
622
Richard Smith454a7cd2014-06-03 08:26:00 +0000623 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
624 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-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.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000628 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000629 RequiresSecondPass = true;
630 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000631 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000632 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000633 = dyn_cast_or_null<InitListExpr>(InitExpr))
Richard Smith454a7cd2014-06-03 08:26:00 +0000634 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000635 }
636}
637
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000638
Douglas Gregor723796a2009-12-16 06:35:08 +0000639InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000640 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000641 bool VerifyOnly)
642 : SemaRef(S), VerifyOnly(VerifyOnly) {
Richard Smith520449d2015-02-05 06:15:50 +0000643 // FIXME: Check that IL isn't already the semantic form of some other
644 // InitListExpr. If it is, we'd create a broken AST.
645
Steve Narofff8ecff22008-05-01 22:18:59 +0000646 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000647
Richard Smith4e0d2e42013-09-20 20:10:22 +0000648 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000649 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000650 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000651 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000652
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000653 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000654 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000655 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000656 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000657 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000658 RequiresSecondPass);
659 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000660}
661
662int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000663 // FIXME: use a proper constant
664 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000665 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000666 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000667 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
668 }
669 return maxElements;
670}
671
672int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000673 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000674 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000675 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000676 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000677 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000678
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000679 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000680 return std::min(InitializableMembers, 1);
681 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000682}
683
Richard Smith4e0d2e42013-09-20 20:10:22 +0000684/// Check whether the range of the initializer \p ParentIList from element
685/// \p Index onwards can be used to initialize an object of type \p T. Update
686/// \p Index to indicate how many elements of the list were consumed.
687///
688/// This also fills in \p StructuredList, from element \p StructuredIndex
689/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000690void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000691 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 QualType T, unsigned &Index,
693 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000694 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000695 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000696
Steve Narofff8ecff22008-05-01 22:18:59 +0000697 if (T->isArrayType())
698 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000699 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000700 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000701 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000702 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000703 else
David Blaikie83d382b2011-09-23 05:06:16 +0000704 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000705
Eli Friedmane0f832b2008-05-25 13:49:22 +0000706 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
709 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000710 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000711 hadError = true;
712 return;
713 }
714
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000715 // Build a structured initializer list corresponding to this subobject.
716 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000717 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
718 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000719 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000720 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000721 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000722
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000723 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000724 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000726 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000727 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000728 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000729
Richard Smithde229232013-06-06 11:41:05 +0000730 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000731 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000732
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000733 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000734 // Update the structured sub-object initializer so that it's ending
735 // range corresponds with the end of the last initializer it used.
736 if (EndIndex < ParentIList->getNumInits()) {
737 SourceLocation EndLoc
738 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
739 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000742 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000743 if (T->isArrayType() || T->isRecordType()) {
744 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000745 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000746 << StructuredSubobjectInitList->getSourceRange()
747 << FixItHint::CreateInsertion(
748 StructuredSubobjectInitList->getLocStart(), "{")
749 << FixItHint::CreateInsertion(
750 SemaRef.getLocForEndOfToken(
751 StructuredSubobjectInitList->getLocEnd()),
752 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000753 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000754 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000755}
756
Richard Smith420fa122015-02-12 01:50:05 +0000757/// Warn that \p Entity was of scalar type and was initialized by a
758/// single-element braced initializer list.
759static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
760 SourceRange Braces) {
761 // Don't warn during template instantiation. If the initialization was
762 // non-dependent, we warned during the initial parse; otherwise, the
763 // type might not be scalar in some uses of the template.
764 if (!S.ActiveTemplateInstantiations.empty())
765 return;
766
767 unsigned DiagID = 0;
768
769 switch (Entity.getKind()) {
770 case InitializedEntity::EK_VectorElement:
771 case InitializedEntity::EK_ComplexElement:
772 case InitializedEntity::EK_ArrayElement:
773 case InitializedEntity::EK_Parameter:
774 case InitializedEntity::EK_Parameter_CF_Audited:
775 case InitializedEntity::EK_Result:
776 // Extra braces here are suspicious.
777 DiagID = diag::warn_braces_around_scalar_init;
778 break;
779
780 case InitializedEntity::EK_Member:
781 // Warn on aggregate initialization but not on ctor init list or
782 // default member initializer.
783 if (Entity.getParent())
784 DiagID = diag::warn_braces_around_scalar_init;
785 break;
786
787 case InitializedEntity::EK_Variable:
788 case InitializedEntity::EK_LambdaCapture:
789 // No warning, might be direct-list-initialization.
790 // FIXME: Should we warn for copy-list-initialization in these cases?
791 break;
792
793 case InitializedEntity::EK_New:
794 case InitializedEntity::EK_Temporary:
795 case InitializedEntity::EK_CompoundLiteralInit:
796 // No warning, braces are part of the syntax of the underlying construct.
797 break;
798
799 case InitializedEntity::EK_RelatedResult:
800 // No warning, we already warned when initializing the result.
801 break;
802
803 case InitializedEntity::EK_Exception:
804 case InitializedEntity::EK_Base:
805 case InitializedEntity::EK_Delegating:
806 case InitializedEntity::EK_BlockElement:
807 llvm_unreachable("unexpected braced scalar init");
808 }
809
810 if (DiagID) {
811 S.Diag(Braces.getBegin(), DiagID)
812 << Braces
813 << FixItHint::CreateRemoval(Braces.getBegin())
814 << FixItHint::CreateRemoval(Braces.getEnd());
815 }
816}
817
818
Richard Smith4e0d2e42013-09-20 20:10:22 +0000819/// Check whether the initializer \p IList (that was written with explicit
820/// braces) can be used to initialize an object of type \p T.
821///
822/// This also fills in \p StructuredList with the fully-braced, desugared
823/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000824void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000825 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000826 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000827 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000828 if (!VerifyOnly) {
829 SyntacticToSemantic[IList] = StructuredList;
830 StructuredList->setSyntacticForm(IList);
831 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000832
833 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000835 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000836 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000837 QualType ExprTy = T;
838 if (!ExprTy->isArrayType())
839 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000840 IList->setType(ExprTy);
841 StructuredList->setType(ExprTy);
842 }
Eli Friedman85f54972008-05-25 13:22:35 +0000843 if (hadError)
844 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000845
Eli Friedman85f54972008-05-25 13:22:35 +0000846 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000847 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000848 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000849 if (SemaRef.getLangOpts().CPlusPlus ||
850 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000851 IList->getType()->isVectorType())) {
852 hadError = true;
853 }
854 return;
855 }
856
Eli Friedmanbd327452009-05-29 20:20:05 +0000857 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000858 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
859 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000860 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000861 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000862 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000863 hadError = true;
864 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000865 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000866 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000867 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000868 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000869 // Don't complain for incomplete types, since we'll get an error
870 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000871 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000872 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000873 CurrentObjectType->isArrayType()? 0 :
874 CurrentObjectType->isVectorType()? 1 :
875 CurrentObjectType->isScalarType()? 2 :
876 CurrentObjectType->isUnionType()? 3 :
877 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000878
Richard Smith1b98ccc2014-07-19 01:39:17 +0000879 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000880 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000881 DK = diag::err_excess_initializers;
882 hadError = true;
883 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000884 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000885 DK = diag::err_excess_initializers;
886 hadError = true;
887 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000888
Chris Lattnerb0912a52009-02-24 22:50:46 +0000889 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000890 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000891 }
892 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000893
Richard Smith420fa122015-02-12 01:50:05 +0000894 if (!VerifyOnly && T->isScalarType() &&
895 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
896 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +0000897}
898
Anders Carlsson6cabf312010-01-23 23:23:01 +0000899void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000900 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000901 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000902 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 unsigned &Index,
904 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000905 unsigned &StructuredIndex,
906 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000907 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
908 // Explicitly braced initializer for complex type can be real+imaginary
909 // parts.
910 CheckComplexType(Entity, IList, DeclType, Index,
911 StructuredList, StructuredIndex);
912 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000913 CheckScalarType(Entity, IList, DeclType, Index,
914 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000915 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000917 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000918 } else if (DeclType->isRecordType()) {
919 assert(DeclType->isAggregateType() &&
920 "non-aggregate records should be handed in CheckSubElementType");
921 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
922 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
923 SubobjectIsDesignatorContext, Index,
924 StructuredList, StructuredIndex,
925 TopLevelObject);
926 } else if (DeclType->isArrayType()) {
927 llvm::APSInt Zero(
928 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
929 false);
930 CheckArrayType(Entity, IList, DeclType, Zero,
931 SubobjectIsDesignatorContext, Index,
932 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000933 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
934 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000935 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000936 if (!VerifyOnly)
937 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
938 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000939 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000940 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000941 CheckReferenceType(Entity, IList, DeclType, Index,
942 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000943 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000944 if (!VerifyOnly)
945 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
946 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000947 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000948 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000949 if (!VerifyOnly)
950 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
951 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000952 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000953 }
954}
955
Anders Carlsson6cabf312010-01-23 23:23:01 +0000956void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000957 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000958 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000959 unsigned &Index,
960 InitListExpr *StructuredList,
961 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000962 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000963
964 if (ElemType->isReferenceType())
965 return CheckReferenceType(Entity, IList, ElemType, Index,
966 StructuredList, StructuredIndex);
967
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000968 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith3c567fc2015-02-12 01:55:09 +0000969 if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000970 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000971 = getStructuredSubobjectInit(IList, Index, ElemType,
972 StructuredList, StructuredIndex,
973 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000974 CheckExplicitInitList(Entity, SubInitList, ElemType,
975 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000976 ++StructuredIndex;
977 ++Index;
978 return;
979 }
Richard Smithe20c83d2012-07-07 08:35:56 +0000980 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +0000981 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +0000982 // This happens during template instantiation when we see an InitListExpr
983 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +0000984 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +0000985 "found implicit initialization for the wrong type");
986 if (!VerifyOnly)
987 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
988 ++Index;
989 return;
Richard Smithe20c83d2012-07-07 08:35:56 +0000990 }
991
Richard Smith3c567fc2015-02-12 01:55:09 +0000992 if (SemaRef.getLangOpts().CPlusPlus) {
993 // C++ [dcl.init.aggr]p2:
994 // Each member is copy-initialized from the corresponding
995 // initializer-clause.
996
997 // FIXME: Better EqualLoc?
998 InitializationKind Kind =
999 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1000 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1001 /*TopLevelOfInitList*/ true);
1002
1003 // C++14 [dcl.init.aggr]p13:
1004 // If the assignment-expression can initialize a member, the member is
1005 // initialized. Otherwise [...] brace elision is assumed
1006 //
1007 // Brace elision is never performed if the element is not an
1008 // assignment-expression.
1009 if (Seq || isa<InitListExpr>(expr)) {
1010 if (!VerifyOnly) {
1011 ExprResult Result =
1012 Seq.Perform(SemaRef, Entity, Kind, expr);
1013 if (Result.isInvalid())
1014 hadError = true;
1015
1016 UpdateStructuredListElement(StructuredList, StructuredIndex,
1017 Result.getAs<Expr>());
1018 }
1019 ++Index;
1020 return;
1021 }
1022
1023 // Fall through for subaggregate initialization
1024 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1025 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001026 return CheckScalarType(Entity, IList, ElemType, Index,
1027 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001028 } else if (const ArrayType *arrayType =
1029 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001030 // arrayType can be incomplete if we're initializing a flexible
1031 // array member. There's nothing we can do with the completed
1032 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001034 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001035 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001036 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1037 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001038 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001039 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001040 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001041 }
John McCall5decec92011-02-21 07:57:55 +00001042
1043 // Fall through for subaggregate initialization.
1044
John McCall5decec92011-02-21 07:57:55 +00001045 } else {
Richard Smith3c567fc2015-02-12 01:55:09 +00001046 assert((ElemType->isRecordType() || ElemType->isVectorType()) &&
1047 "Unexpected type");
1048
John McCall5decec92011-02-21 07:57:55 +00001049 // C99 6.7.8p13:
1050 //
1051 // The initializer for a structure or union object that has
1052 // automatic storage duration shall be either an initializer
1053 // list as described below, or a single expression that has
1054 // compatible structure or union type. In the latter case, the
1055 // initial value of the object, including unnamed members, is
1056 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001057 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001058 if (SemaRef.CheckSingleAssignmentConstraints(
1059 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001060 if (ExprRes.isInvalid())
1061 hadError = true;
1062 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001063 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001064 if (ExprRes.isInvalid())
1065 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001066 }
1067 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001068 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001069 ++Index;
1070 return;
1071 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001072 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001073 // Fall through for subaggregate initialization
1074 }
1075
1076 // C++ [dcl.init.aggr]p12:
1077 //
1078 // [...] Otherwise, if the member is itself a non-empty
1079 // subaggregate, brace elision is assumed and the initializer is
1080 // considered for the initialization of the first member of
1081 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001082 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001083 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001084 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1085 StructuredIndex);
1086 ++StructuredIndex;
1087 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001088 if (!VerifyOnly) {
1089 // We cannot initialize this element, so let
1090 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001091 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001092 /*TopLevelOfInitList=*/true);
1093 }
John McCall5decec92011-02-21 07:57:55 +00001094 hadError = true;
1095 ++Index;
1096 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001097 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001098}
1099
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001100void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1101 InitListExpr *IList, QualType DeclType,
1102 unsigned &Index,
1103 InitListExpr *StructuredList,
1104 unsigned &StructuredIndex) {
1105 assert(Index == 0 && "Index in explicit init list must be zero");
1106
1107 // As an extension, clang supports complex initializers, which initialize
1108 // a complex number component-wise. When an explicit initializer list for
1109 // a complex number contains two two initializers, this extension kicks in:
1110 // it exepcts the initializer list to contain two elements convertible to
1111 // the element type of the complex type. The first element initializes
1112 // the real part, and the second element intitializes the imaginary part.
1113
1114 if (IList->getNumInits() != 2)
1115 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1116 StructuredIndex);
1117
1118 // This is an extension in C. (The builtin _Complex type does not exist
1119 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001120 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001121 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1122 << IList->getSourceRange();
1123
1124 // Initialize the complex number.
1125 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1126 InitializedEntity ElementEntity =
1127 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1128
1129 for (unsigned i = 0; i < 2; ++i) {
1130 ElementEntity.setElementIndex(Index);
1131 CheckSubElementType(ElementEntity, IList, elementType, Index,
1132 StructuredList, StructuredIndex);
1133 }
1134}
1135
1136
Anders Carlsson6cabf312010-01-23 23:23:01 +00001137void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001138 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001139 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001140 InitListExpr *StructuredList,
1141 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001142 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001143 if (!VerifyOnly)
1144 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001145 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001146 diag::warn_cxx98_compat_empty_scalar_initializer :
1147 diag::err_empty_scalar_initializer)
1148 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001149 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001150 ++Index;
1151 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001152 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001153 }
John McCall643169b2010-11-11 00:46:36 +00001154
1155 Expr *expr = IList->getInit(Index);
1156 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001157 // FIXME: This is invalid, and accepting it causes overload resolution
1158 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001159 if (!VerifyOnly)
1160 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001161 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001163
1164 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1165 StructuredIndex);
1166 return;
1167 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001168 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001169 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001170 diag::err_designator_for_scalar_init)
1171 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001172 hadError = true;
1173 ++Index;
1174 ++StructuredIndex;
1175 return;
1176 }
1177
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001178 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001179 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001180 hadError = true;
1181 ++Index;
1182 return;
1183 }
1184
John McCall643169b2010-11-11 00:46:36 +00001185 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001186 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001187 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001188
Craig Topperc3ec1492014-05-26 06:22:03 +00001189 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001190
1191 if (Result.isInvalid())
1192 hadError = true; // types weren't compatible.
1193 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001194 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001195
John McCall643169b2010-11-11 00:46:36 +00001196 if (ResultExpr != expr) {
1197 // The type was promoted, update initializer list.
1198 IList->setInit(Index, ResultExpr);
1199 }
1200 }
1201 if (hadError)
1202 ++StructuredIndex;
1203 else
1204 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1205 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001206}
1207
Anders Carlsson6cabf312010-01-23 23:23:01 +00001208void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1209 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001210 unsigned &Index,
1211 InitListExpr *StructuredList,
1212 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001213 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001214 // FIXME: It would be wonderful if we could point at the actual member. In
1215 // general, it would be useful to pass location information down the stack,
1216 // so that we know the location (or decl) of the "current object" being
1217 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001218 if (!VerifyOnly)
1219 SemaRef.Diag(IList->getLocStart(),
1220 diag::err_init_reference_member_uninitialized)
1221 << DeclType
1222 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001223 hadError = true;
1224 ++Index;
1225 ++StructuredIndex;
1226 return;
1227 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001228
1229 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001230 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001231 if (!VerifyOnly)
1232 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1233 << DeclType << IList->getSourceRange();
1234 hadError = true;
1235 ++Index;
1236 ++StructuredIndex;
1237 return;
1238 }
1239
1240 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001241 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001242 hadError = true;
1243 ++Index;
1244 return;
1245 }
1246
1247 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001248 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1249 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001250
1251 if (Result.isInvalid())
1252 hadError = true;
1253
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001254 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001255 IList->setInit(Index, expr);
1256
1257 if (hadError)
1258 ++StructuredIndex;
1259 else
1260 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1261 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001262}
1263
Anders Carlsson6cabf312010-01-23 23:23:01 +00001264void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001265 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001266 unsigned &Index,
1267 InitListExpr *StructuredList,
1268 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001269 const VectorType *VT = DeclType->getAs<VectorType>();
1270 unsigned maxElements = VT->getNumElements();
1271 unsigned numEltsInit = 0;
1272 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001273
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001274 if (Index >= IList->getNumInits()) {
1275 // Make sure the element type can be value-initialized.
1276 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001277 CheckEmptyInitializable(
1278 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1279 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001280 return;
1281 }
1282
David Blaikiebbafb8a2012-03-11 07:00:24 +00001283 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001284 // If the initializing element is a vector, try to copy-initialize
1285 // instead of breaking it apart (which is doomed to failure anyway).
1286 Expr *Init = IList->getInit(Index);
1287 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001288 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001289 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001290 hadError = true;
1291 ++Index;
1292 return;
1293 }
1294
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001295 ExprResult Result =
1296 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1297 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001298
Craig Topperc3ec1492014-05-26 06:22:03 +00001299 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001300 if (Result.isInvalid())
1301 hadError = true; // types weren't compatible.
1302 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001303 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
John McCall6a16b2f2010-10-30 00:11:39 +00001305 if (ResultExpr != Init) {
1306 // The type was promoted, update initializer list.
1307 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001308 }
1309 }
John McCall6a16b2f2010-10-30 00:11:39 +00001310 if (hadError)
1311 ++StructuredIndex;
1312 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001313 UpdateStructuredListElement(StructuredList, StructuredIndex,
1314 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001315 ++Index;
1316 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
John McCall6a16b2f2010-10-30 00:11:39 +00001319 InitializedEntity ElementEntity =
1320 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321
John McCall6a16b2f2010-10-30 00:11:39 +00001322 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1323 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001324 if (Index >= IList->getNumInits()) {
1325 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001326 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001327 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001329
John McCall6a16b2f2010-10-30 00:11:39 +00001330 ElementEntity.setElementIndex(Index);
1331 CheckSubElementType(ElementEntity, IList, elementType, Index,
1332 StructuredList, StructuredIndex);
1333 }
James Molloy9eef2652014-06-20 14:35:13 +00001334
1335 if (VerifyOnly)
1336 return;
1337
1338 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1339 const VectorType *T = Entity.getType()->getAs<VectorType>();
1340 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1341 T->getVectorKind() == VectorType::NeonPolyVector)) {
1342 // The ability to use vector initializer lists is a GNU vector extension
1343 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1344 // endian machines it works fine, however on big endian machines it
1345 // exhibits surprising behaviour:
1346 //
1347 // uint32x2_t x = {42, 64};
1348 // return vget_lane_u32(x, 0); // Will return 64.
1349 //
1350 // Because of this, explicitly call out that it is non-portable.
1351 //
1352 SemaRef.Diag(IList->getLocStart(),
1353 diag::warn_neon_vector_initializer_non_portable);
1354
1355 const char *typeCode;
1356 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1357
1358 if (elementType->isFloatingType())
1359 typeCode = "f";
1360 else if (elementType->isSignedIntegerType())
1361 typeCode = "s";
1362 else if (elementType->isUnsignedIntegerType())
1363 typeCode = "u";
1364 else
1365 llvm_unreachable("Invalid element type!");
1366
1367 SemaRef.Diag(IList->getLocStart(),
1368 SemaRef.Context.getTypeSize(VT) > 64 ?
1369 diag::note_neon_vector_initializer_non_portable_q :
1370 diag::note_neon_vector_initializer_non_portable)
1371 << typeCode << typeSize;
1372 }
1373
John McCall6a16b2f2010-10-30 00:11:39 +00001374 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001375 }
John McCall6a16b2f2010-10-30 00:11:39 +00001376
1377 InitializedEntity ElementEntity =
1378 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001379
John McCall6a16b2f2010-10-30 00:11:39 +00001380 // OpenCL initializers allows vectors to be constructed from vectors.
1381 for (unsigned i = 0; i < maxElements; ++i) {
1382 // Don't attempt to go past the end of the init list
1383 if (Index >= IList->getNumInits())
1384 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385
John McCall6a16b2f2010-10-30 00:11:39 +00001386 ElementEntity.setElementIndex(Index);
1387
1388 QualType IType = IList->getInit(Index)->getType();
1389 if (!IType->isVectorType()) {
1390 CheckSubElementType(ElementEntity, IList, elementType, Index,
1391 StructuredList, StructuredIndex);
1392 ++numEltsInit;
1393 } else {
1394 QualType VecType;
1395 const VectorType *IVT = IType->getAs<VectorType>();
1396 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001397
John McCall6a16b2f2010-10-30 00:11:39 +00001398 if (IType->isExtVectorType())
1399 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1400 else
1401 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001402 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001403 CheckSubElementType(ElementEntity, IList, VecType, Index,
1404 StructuredList, StructuredIndex);
1405 numEltsInit += numIElts;
1406 }
1407 }
1408
1409 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001410 if (numEltsInit != maxElements) {
1411 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001412 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001413 diag::err_vector_incorrect_num_initializers)
1414 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1415 hadError = true;
1416 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001417}
1418
Anders Carlsson6cabf312010-01-23 23:23:01 +00001419void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001420 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001421 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001422 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001423 unsigned &Index,
1424 InitListExpr *StructuredList,
1425 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001426 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1427
Steve Narofff8ecff22008-05-01 22:18:59 +00001428 // Check for the special-case of initializing an array with a string.
1429 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001430 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1431 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001432 // We place the string literal directly into the resulting
1433 // initializer list. This is the only place where the structure
1434 // of the structured initializer list doesn't match exactly,
1435 // because doing so would involve allocating one character
1436 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001437 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001438 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1439 UpdateStructuredListElement(StructuredList, StructuredIndex,
1440 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001441 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1442 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001443 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001444 return;
1445 }
1446 }
John McCall66884dd2011-02-21 07:22:22 +00001447 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001448 // Check for VLAs; in standard C it would be possible to check this
1449 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1450 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001451 if (!VerifyOnly)
1452 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1453 diag::err_variable_object_no_init)
1454 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001455 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001456 ++Index;
1457 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001458 return;
1459 }
1460
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001461 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001462 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1463 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001464 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001465 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001466 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001467 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001468 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001469 maxElementsKnown = true;
1470 }
1471
John McCall66884dd2011-02-21 07:22:22 +00001472 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001473 while (Index < IList->getNumInits()) {
1474 Expr *Init = IList->getInit(Index);
1475 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001476 // If we're not the subobject that matches up with the '{' for
1477 // the designator, we shouldn't be handling the
1478 // designator. Return immediately.
1479 if (!SubobjectIsDesignatorContext)
1480 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001481
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001482 // Handle this designated initializer. elementIndex will be
1483 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001484 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001485 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001486 StructuredList, StructuredIndex, true,
1487 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001488 hadError = true;
1489 continue;
1490 }
1491
Douglas Gregor033d1252009-01-23 16:54:12 +00001492 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001493 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001494 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001495 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001496 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001497
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001498 // If the array is of incomplete type, keep track of the number of
1499 // elements in the initializer.
1500 if (!maxElementsKnown && elementIndex > maxElements)
1501 maxElements = elementIndex;
1502
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001503 continue;
1504 }
1505
1506 // If we know the maximum number of elements, and we've already
1507 // hit it, stop consuming elements in the initializer list.
1508 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001509 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001510
Anders Carlsson6cabf312010-01-23 23:23:01 +00001511 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001512 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001513 Entity);
1514 // Check this element.
1515 CheckSubElementType(ElementEntity, IList, elementType, Index,
1516 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001517 ++elementIndex;
1518
1519 // If the array is of incomplete type, keep track of the number of
1520 // elements in the initializer.
1521 if (!maxElementsKnown && elementIndex > maxElements)
1522 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001523 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001524 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001525 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001526 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001527 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001528 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001529 // Sizing an array implicitly to zero is not allowed by ISO C,
1530 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001531 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001532 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001533 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001534
Mike Stump11289f42009-09-09 15:08:12 +00001535 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001536 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001537 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001538 if (!hadError && VerifyOnly) {
1539 // Check if there are any members of the array that get value-initialized.
1540 // If so, check if doing that is possible.
1541 // FIXME: This needs to detect holes left by designated initializers too.
1542 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001543 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1544 SemaRef.Context, 0, Entity),
1545 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001546 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001547}
1548
Eli Friedman3fa64df2011-08-23 22:24:57 +00001549bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1550 Expr *InitExpr,
1551 FieldDecl *Field,
1552 bool TopLevelObject) {
1553 // Handle GNU flexible array initializers.
1554 unsigned FlexArrayDiag;
1555 if (isa<InitListExpr>(InitExpr) &&
1556 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1557 // Empty flexible array init always allowed as an extension
1558 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001559 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001560 // Disallow flexible array init in C++; it is not required for gcc
1561 // compatibility, and it needs work to IRGen correctly in general.
1562 FlexArrayDiag = diag::err_flexible_array_init;
1563 } else if (!TopLevelObject) {
1564 // Disallow flexible array init on non-top-level object
1565 FlexArrayDiag = diag::err_flexible_array_init;
1566 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1567 // Disallow flexible array init on anything which is not a variable.
1568 FlexArrayDiag = diag::err_flexible_array_init;
1569 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1570 // Disallow flexible array init on local variables.
1571 FlexArrayDiag = diag::err_flexible_array_init;
1572 } else {
1573 // Allow other cases.
1574 FlexArrayDiag = diag::ext_flexible_array_init;
1575 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001576
1577 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001578 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001579 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001580 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001581 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1582 << Field;
1583 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001584
1585 return FlexArrayDiag != diag::ext_flexible_array_init;
1586}
1587
Anders Carlsson6cabf312010-01-23 23:23:01 +00001588void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001589 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001590 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001591 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001592 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001593 unsigned &Index,
1594 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001595 unsigned &StructuredIndex,
1596 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001597 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001598
Eli Friedman23a9e312008-05-19 19:16:24 +00001599 // If the record is invalid, some of it's members are invalid. To avoid
1600 // confusion, we forgo checking the intializer for the entire record.
1601 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001602 // Assume it was supposed to consume a single initializer.
1603 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001604 hadError = true;
1605 return;
Mike Stump11289f42009-09-09 15:08:12 +00001606 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001607
1608 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001609 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001610
1611 // If there's a default initializer, use it.
1612 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1613 if (VerifyOnly)
1614 return;
1615 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1616 Field != FieldEnd; ++Field) {
1617 if (Field->hasInClassInitializer()) {
1618 StructuredList->setInitializedFieldInUnion(*Field);
1619 // FIXME: Actually build a CXXDefaultInitExpr?
1620 return;
1621 }
1622 }
1623 }
1624
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001625 // Value-initialize the first member of the union that isn't an unnamed
1626 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001627 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1628 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001629 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001630 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001631 CheckEmptyInitializable(
1632 InitializedEntity::InitializeMember(*Field, &Entity),
1633 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001634 else
David Blaikie40ed2972012-06-06 20:45:41 +00001635 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001636 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001637 }
1638 }
1639 return;
1640 }
1641
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001642 // If structDecl is a forward declaration, this loop won't do
1643 // anything except look at designated initializers; That's okay,
1644 // because an error should get printed out elsewhere. It might be
1645 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001646 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001647 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001648 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001649 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001650 while (Index < IList->getNumInits()) {
1651 Expr *Init = IList->getInit(Index);
1652
1653 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001654 // If we're not the subobject that matches up with the '{' for
1655 // the designator, we shouldn't be handling the
1656 // designator. Return immediately.
1657 if (!SubobjectIsDesignatorContext)
1658 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001659
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001660 // Handle this designated initializer. Field will be updated to
1661 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001662 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001663 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001664 StructuredList, StructuredIndex,
1665 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001666 hadError = true;
1667
Douglas Gregora9add4e2009-02-12 19:00:39 +00001668 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001669
1670 // Disable check for missing fields when designators are used.
1671 // This matches gcc behaviour.
1672 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001673 continue;
1674 }
1675
1676 if (Field == FieldEnd) {
1677 // We've run out of fields. We're done.
1678 break;
1679 }
1680
Douglas Gregora9add4e2009-02-12 19:00:39 +00001681 // We've already initialized a member of a union. We're done.
1682 if (InitializedSomething && DeclType->isUnionType())
1683 break;
1684
Douglas Gregor91f84212008-12-11 16:49:14 +00001685 // If we've hit the flexible array member at the end, we're done.
1686 if (Field->getType()->isIncompleteArrayType())
1687 break;
1688
Douglas Gregor51695702009-01-29 16:53:55 +00001689 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001690 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001691 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001692 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001693 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001694
Douglas Gregora82064c2011-06-29 21:51:31 +00001695 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001696 bool InvalidUse;
1697 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001698 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001699 else
David Blaikie40ed2972012-06-06 20:45:41 +00001700 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001701 IList->getInit(Index)->getLocStart());
1702 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001703 ++Index;
1704 ++Field;
1705 hadError = true;
1706 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001707 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001708
Anders Carlsson6cabf312010-01-23 23:23:01 +00001709 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001710 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001711 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1712 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001713 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001714
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001715 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001716 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001717 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001718 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001719
1720 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001721 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001722
John McCalle40b58e2010-03-11 19:32:38 +00001723 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001724 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1725 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1726 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001727 // It is possible we have one or more unnamed bitfields remaining.
1728 // Find first (if any) named field and emit warning.
1729 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1730 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001731 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001732 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001733 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001734 break;
1735 }
1736 }
1737 }
1738
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001739 // Check that any remaining fields can be value-initialized.
1740 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1741 !Field->getType()->isIncompleteArrayType()) {
1742 // FIXME: Should check for holes left by designated initializers too.
1743 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001744 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001745 CheckEmptyInitializable(
1746 InitializedEntity::InitializeMember(*Field, &Entity),
1747 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001748 }
1749 }
1750
Mike Stump11289f42009-09-09 15:08:12 +00001751 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001752 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001753 return;
1754
David Blaikie40ed2972012-06-06 20:45:41 +00001755 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001756 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001757 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001758 ++Index;
1759 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001760 }
1761
Anders Carlsson6cabf312010-01-23 23:23:01 +00001762 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001763 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001764
Anders Carlsson6cabf312010-01-23 23:23:01 +00001765 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001766 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001767 StructuredList, StructuredIndex);
1768 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001769 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001770 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001771}
Steve Narofff8ecff22008-05-01 22:18:59 +00001772
Douglas Gregord5846a12009-04-15 06:41:24 +00001773/// \brief Expand a field designator that refers to a member of an
1774/// anonymous struct or union into a series of field designators that
1775/// refers to the field within the appropriate subobject.
1776///
Douglas Gregord5846a12009-04-15 06:41:24 +00001777static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001778 DesignatedInitExpr *DIE,
1779 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001780 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001781 typedef DesignatedInitExpr::Designator Designator;
1782
Douglas Gregord5846a12009-04-15 06:41:24 +00001783 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001784 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001785 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1786 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1787 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001788 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001789 DIE->getDesignator(DesigIdx)->getDotLoc(),
1790 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1791 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001792 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1793 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001794 assert(isa<FieldDecl>(*PI));
1795 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001796 }
1797
1798 // Expand the current designator into the set of replacement
1799 // designators, so we have a full subobject path down to where the
1800 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001801 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001802 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001803}
Mike Stump11289f42009-09-09 15:08:12 +00001804
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001805static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1806 DesignatedInitExpr *DIE) {
1807 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1808 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1809 for (unsigned I = 0; I < NumIndexExprs; ++I)
1810 IndexExprs[I] = DIE->getSubExpr(I + 1);
1811 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001812 DIE->size(), IndexExprs,
1813 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001814 DIE->usesGNUSyntax(), DIE->getInit());
1815}
1816
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001817namespace {
1818
1819// Callback to only accept typo corrections that are for field members of
1820// the given struct or union.
1821class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1822 public:
1823 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1824 : Record(RD) {}
1825
Craig Toppere14c0f82014-03-12 04:55:44 +00001826 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001827 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1828 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1829 }
1830
1831 private:
1832 RecordDecl *Record;
1833};
1834
1835}
1836
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001837/// @brief Check the well-formedness of a C99 designated initializer.
1838///
1839/// Determines whether the designated initializer @p DIE, which
1840/// resides at the given @p Index within the initializer list @p
1841/// IList, is well-formed for a current object of type @p DeclType
1842/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001843/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001844/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001845///
1846/// @param IList The initializer list in which this designated
1847/// initializer occurs.
1848///
Douglas Gregora5324162009-04-15 04:56:10 +00001849/// @param DIE The designated initializer expression.
1850///
1851/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001852///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001853/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001854/// into which the designation in @p DIE should refer.
1855///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001856/// @param NextField If non-NULL and the first designator in @p DIE is
1857/// a field, this will be set to the field declaration corresponding
1858/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001859///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001860/// @param NextElementIndex If non-NULL and the first designator in @p
1861/// DIE is an array designator or GNU array-range designator, this
1862/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001863///
1864/// @param Index Index into @p IList where the designated initializer
1865/// @p DIE occurs.
1866///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001867/// @param StructuredList The initializer list expression that
1868/// describes all of the subobject initializers in the order they'll
1869/// actually be initialized.
1870///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001871/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001872bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001873InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001874 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001875 DesignatedInitExpr *DIE,
1876 unsigned DesigIdx,
1877 QualType &CurrentObjectType,
1878 RecordDecl::field_iterator *NextField,
1879 llvm::APSInt *NextElementIndex,
1880 unsigned &Index,
1881 InitListExpr *StructuredList,
1882 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001883 bool FinishSubobjectInit,
1884 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001885 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001886 // Check the actual initialization for the designated object type.
1887 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001888
1889 // Temporarily remove the designator expression from the
1890 // initializer list that the child calls see, so that we don't try
1891 // to re-process the designator.
1892 unsigned OldIndex = Index;
1893 IList->setInit(OldIndex, DIE->getInit());
1894
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001895 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001896 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001897
1898 // Restore the designated initializer expression in the syntactic
1899 // form of the initializer list.
1900 if (IList->getInit(OldIndex) != DIE->getInit())
1901 DIE->setInit(IList->getInit(OldIndex));
1902 IList->setInit(OldIndex, DIE);
1903
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001904 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905 }
1906
Douglas Gregora5324162009-04-15 04:56:10 +00001907 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001908 bool IsFirstDesignator = (DesigIdx == 0);
1909 if (!VerifyOnly) {
1910 assert((IsFirstDesignator || StructuredList) &&
1911 "Need a non-designated initializer list to start from");
1912
1913 // Determine the structural initializer list that corresponds to the
1914 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001915 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001916 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1917 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001918 SourceRange(D->getLocStart(),
1919 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001920 assert(StructuredList && "Expected a structured initializer list");
1921 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001922
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001923 if (D->isFieldDesignator()) {
1924 // C99 6.7.8p7:
1925 //
1926 // If a designator has the form
1927 //
1928 // . identifier
1929 //
1930 // then the current object (defined below) shall have
1931 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001932 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001933 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001934 if (!RT) {
1935 SourceLocation Loc = D->getDotLoc();
1936 if (Loc.isInvalid())
1937 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001938 if (!VerifyOnly)
1939 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001940 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001941 ++Index;
1942 return true;
1943 }
1944
Douglas Gregord5846a12009-04-15 06:41:24 +00001945 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00001946 if (!KnownField) {
1947 IdentifierInfo *FieldName = D->getFieldName();
1948 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1949 for (NamedDecl *ND : Lookup) {
1950 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
1951 KnownField = FD;
1952 break;
1953 }
1954 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001955 // In verify mode, don't modify the original.
1956 if (VerifyOnly)
1957 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00001958 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001959 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00001960 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001961 break;
1962 }
1963 }
David Majnemer36ef8982014-08-11 18:33:59 +00001964 if (!KnownField) {
1965 if (VerifyOnly) {
1966 ++Index;
1967 return true; // No typo correction when just trying this out.
1968 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001969
David Majnemer36ef8982014-08-11 18:33:59 +00001970 // Name lookup found something, but it wasn't a field.
1971 if (!Lookup.empty()) {
1972 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1973 << FieldName;
1974 SemaRef.Diag(Lookup.front()->getLocation(),
1975 diag::note_field_designator_found);
1976 ++Index;
1977 return true;
1978 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001979
David Majnemer36ef8982014-08-11 18:33:59 +00001980 // Name lookup didn't find anything.
1981 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00001982 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1983 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00001984 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001985 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
1986 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001987 SemaRef.diagnoseTypo(
1988 Corrected,
1989 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00001990 << FieldName << CurrentObjectType);
1991 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001992 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001993 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00001994 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001995 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1996 << FieldName << CurrentObjectType;
1997 ++Index;
1998 return true;
1999 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002000 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002001 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002002
David Majnemer58e4ea92014-08-23 01:48:50 +00002003 unsigned FieldIndex = 0;
2004 for (auto *FI : RT->getDecl()->fields()) {
2005 if (FI->isUnnamedBitfield())
2006 continue;
2007 if (KnownField == FI)
2008 break;
2009 ++FieldIndex;
2010 }
2011
David Majnemer36ef8982014-08-11 18:33:59 +00002012 RecordDecl::field_iterator Field =
2013 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2014
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002015 // All of the fields of a union are located at the same place in
2016 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002017 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002018 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002019 if (!VerifyOnly) {
2020 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2021 if (CurrentField && CurrentField != *Field) {
2022 assert(StructuredList->getNumInits() == 1
2023 && "A union should never have more than one initializer!");
2024
2025 // we're about to throw away an initializer, emit warning
2026 SemaRef.Diag(D->getFieldLoc(),
2027 diag::warn_initializer_overrides)
2028 << D->getSourceRange();
2029 Expr *ExistingInit = StructuredList->getInit(0);
2030 SemaRef.Diag(ExistingInit->getLocStart(),
2031 diag::note_previous_initializer)
2032 << /*FIXME:has side effects=*/0
2033 << ExistingInit->getSourceRange();
2034
2035 // remove existing initializer
2036 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002037 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002038 }
2039
David Blaikie40ed2972012-06-06 20:45:41 +00002040 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002041 }
Douglas Gregor51695702009-01-29 16:53:55 +00002042 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002043
Douglas Gregora82064c2011-06-29 21:51:31 +00002044 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002045 bool InvalidUse;
2046 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00002047 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002048 else
David Blaikie40ed2972012-06-06 20:45:41 +00002049 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002050 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002051 ++Index;
2052 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002053 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002054
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002055 if (!VerifyOnly) {
2056 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002057 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002058
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002059 // Make sure that our non-designated initializer list has space
2060 // for a subobject corresponding to this field.
2061 if (FieldIndex >= StructuredList->getNumInits())
2062 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2063 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002064
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002065 // This designator names a flexible array member.
2066 if (Field->getType()->isIncompleteArrayType()) {
2067 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002068 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002069 // We can't designate an object within the flexible array
2070 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002071 if (!VerifyOnly) {
2072 DesignatedInitExpr::Designator *NextD
2073 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002074 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002075 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002076 << SourceRange(NextD->getLocStart(),
2077 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002078 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002079 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002080 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002081 Invalid = true;
2082 }
2083
Chris Lattner001b29c2010-10-10 17:49:49 +00002084 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2085 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002086 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002087 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002088 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002089 diag::err_flexible_array_init_needs_braces)
2090 << DIE->getInit()->getSourceRange();
2091 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002092 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002093 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002094 Invalid = true;
2095 }
2096
Eli Friedman3fa64df2011-08-23 22:24:57 +00002097 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002098 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002099 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002100 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002101
2102 if (Invalid) {
2103 ++Index;
2104 return true;
2105 }
2106
2107 // Initialize the array.
2108 bool prevHadError = hadError;
2109 unsigned newStructuredIndex = FieldIndex;
2110 unsigned OldIndex = Index;
2111 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002112
2113 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002114 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002115 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002116 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002117
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002118 IList->setInit(OldIndex, DIE);
2119 if (hadError && !prevHadError) {
2120 ++Field;
2121 ++FieldIndex;
2122 if (NextField)
2123 *NextField = Field;
2124 StructuredIndex = FieldIndex;
2125 return true;
2126 }
2127 } else {
2128 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002129 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002130 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002131
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002132 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002133 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002135 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002136 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002137 true, false))
2138 return true;
2139 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002140
2141 // Find the position of the next field to be initialized in this
2142 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002143 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002144 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002145
2146 // If this the first designator, our caller will continue checking
2147 // the rest of this struct/class/union subobject.
2148 if (IsFirstDesignator) {
2149 if (NextField)
2150 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002151 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002152 return false;
2153 }
2154
Douglas Gregor17bd0942009-01-28 23:36:17 +00002155 if (!FinishSubobjectInit)
2156 return false;
2157
Douglas Gregord5846a12009-04-15 06:41:24 +00002158 // We've already initialized something in the union; we're done.
2159 if (RT->getDecl()->isUnion())
2160 return hadError;
2161
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002162 // Check the remaining fields within this class/struct/union subobject.
2163 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
Anders Carlsson6cabf312010-01-23 23:23:01 +00002165 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002166 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002167 return hadError && !prevHadError;
2168 }
2169
2170 // C99 6.7.8p6:
2171 //
2172 // If a designator has the form
2173 //
2174 // [ constant-expression ]
2175 //
2176 // then the current object (defined below) shall have array
2177 // type and the expression shall be an integer constant
2178 // expression. If the array is of unknown size, any
2179 // nonnegative value is valid.
2180 //
2181 // Additionally, cope with the GNU extension that permits
2182 // designators of the form
2183 //
2184 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002185 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002186 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002187 if (!VerifyOnly)
2188 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2189 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002190 ++Index;
2191 return true;
2192 }
2193
Craig Topperc3ec1492014-05-26 06:22:03 +00002194 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002195 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2196 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002197 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002198 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002199 DesignatedEndIndex = DesignatedStartIndex;
2200 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002201 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002202
Mike Stump11289f42009-09-09 15:08:12 +00002203 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002204 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002205 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002206 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002207 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002208
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002209 // Codegen can't handle evaluating array range designators that have side
2210 // effects, because we replicate the AST value for each initialized element.
2211 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2212 // elements with something that has a side effect, so codegen can emit an
2213 // "error unsupported" error instead of miscompiling the app.
2214 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002215 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002216 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002217 }
2218
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002219 if (isa<ConstantArrayType>(AT)) {
2220 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002221 DesignatedStartIndex
2222 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002223 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002224 DesignatedEndIndex
2225 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002226 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2227 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002228 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002229 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002230 diag::err_array_designator_too_large)
2231 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2232 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002233 ++Index;
2234 return true;
2235 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002236 } else {
2237 // Make sure the bit-widths and signedness match.
2238 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002239 DesignatedEndIndex
2240 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002241 else if (DesignatedStartIndex.getBitWidth() <
2242 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002243 DesignatedStartIndex
2244 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002245 DesignatedStartIndex.setIsUnsigned(true);
2246 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
Eli Friedman1f16b742013-06-11 21:48:11 +00002249 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2250 // We're modifying a string literal init; we have to decompose the string
2251 // so we can modify the individual characters.
2252 ASTContext &Context = SemaRef.Context;
2253 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2254
2255 // Compute the character type
2256 QualType CharTy = AT->getElementType();
2257
2258 // Compute the type of the integer literals.
2259 QualType PromotedCharTy = CharTy;
2260 if (CharTy->isPromotableIntegerType())
2261 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2262 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2263
2264 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2265 // Get the length of the string.
2266 uint64_t StrLen = SL->getLength();
2267 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2268 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2269 StructuredList->resizeInits(Context, StrLen);
2270
2271 // Build a literal for each character in the string, and put them into
2272 // the init list.
2273 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2274 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2275 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002276 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002277 if (CharTy != PromotedCharTy)
2278 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002279 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002280 StructuredList->updateInit(Context, i, Init);
2281 }
2282 } else {
2283 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2284 std::string Str;
2285 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2286
2287 // Get the length of the string.
2288 uint64_t StrLen = Str.size();
2289 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2290 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2291 StructuredList->resizeInits(Context, StrLen);
2292
2293 // Build a literal for each character in the string, and put them into
2294 // the init list.
2295 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2296 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2297 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002298 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002299 if (CharTy != PromotedCharTy)
2300 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002301 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002302 StructuredList->updateInit(Context, i, Init);
2303 }
2304 }
2305 }
2306
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002307 // Make sure that our non-designated initializer list has space
2308 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002309 if (!VerifyOnly &&
2310 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002311 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002312 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002313
Douglas Gregor17bd0942009-01-28 23:36:17 +00002314 // Repeatedly perform subobject initializations in the range
2315 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002316
Douglas Gregor17bd0942009-01-28 23:36:17 +00002317 // Move to the next designator
2318 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2319 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002320
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002321 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002322 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002323
Douglas Gregor17bd0942009-01-28 23:36:17 +00002324 while (DesignatedStartIndex <= DesignatedEndIndex) {
2325 // Recurse to check later designated subobjects.
2326 QualType ElementType = AT->getElementType();
2327 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002328
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002329 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002330 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002331 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002332 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002333 (DesignatedStartIndex == DesignatedEndIndex),
2334 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002335 return true;
2336
2337 // Move to the next index in the array that we'll be initializing.
2338 ++DesignatedStartIndex;
2339 ElementIndex = DesignatedStartIndex.getZExtValue();
2340 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002341
2342 // If this the first designator, our caller will continue checking
2343 // the rest of this array subobject.
2344 if (IsFirstDesignator) {
2345 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002346 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002347 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002348 return false;
2349 }
Mike Stump11289f42009-09-09 15:08:12 +00002350
Douglas Gregor17bd0942009-01-28 23:36:17 +00002351 if (!FinishSubobjectInit)
2352 return false;
2353
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002354 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002355 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002356 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002357 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002358 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002359 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002360}
2361
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002362// Get the structured initializer list for a subobject of type
2363// @p CurrentObjectType.
2364InitListExpr *
2365InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2366 QualType CurrentObjectType,
2367 InitListExpr *StructuredList,
2368 unsigned StructuredIndex,
2369 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002370 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002371 return nullptr; // No structured list in verification-only mode.
2372 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002373 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002374 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002375 else if (StructuredIndex < StructuredList->getNumInits())
2376 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002377
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002378 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2379 return Result;
2380
2381 if (ExistingInit) {
2382 // We are creating an initializer list that initializes the
2383 // subobjects of the current object, but there was already an
2384 // initialization that completely initialized the current
2385 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002386 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002387 // struct X { int a, b; };
2388 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002389 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002390 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2391 // designated initializer re-initializes the whole
2392 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002393 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002394 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002395 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002396 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002397 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002398 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002399 << ExistingInit->getSourceRange();
2400 }
2401
Mike Stump11289f42009-09-09 15:08:12 +00002402 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002403 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002404 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002405 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002406
Eli Friedman91f5ae52012-02-23 02:25:10 +00002407 QualType ResultType = CurrentObjectType;
2408 if (!ResultType->isArrayType())
2409 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2410 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002411
Douglas Gregor6d00c992009-03-20 23:58:33 +00002412 // Pre-allocate storage for the structured initializer list.
2413 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002414 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002415 bool GotNumInits = false;
2416 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002417 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002418 GotNumInits = true;
2419 } else if (Index < IList->getNumInits()) {
2420 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002421 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002422 GotNumInits = true;
2423 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002424 }
2425
Mike Stump11289f42009-09-09 15:08:12 +00002426 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002427 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2428 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2429 NumElements = CAType->getSize().getZExtValue();
2430 // Simple heuristic so that we don't allocate a very large
2431 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002432 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002433 NumElements = 0;
2434 }
John McCall9dd450b2009-09-21 23:43:11 +00002435 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002436 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002437 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002438 RecordDecl *RDecl = RType->getDecl();
2439 if (RDecl->isUnion())
2440 NumElements = 1;
2441 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002442 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002443 }
2444
Ted Kremenekac034612010-04-13 23:39:13 +00002445 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002446
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002447 // Link this new initializer list into the structured initializer
2448 // lists.
2449 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002450 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002451 else {
2452 Result->setSyntacticForm(IList);
2453 SyntacticToSemantic[IList] = Result;
2454 }
2455
2456 return Result;
2457}
2458
2459/// Update the initializer at index @p StructuredIndex within the
2460/// structured initializer list to the value @p expr.
2461void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2462 unsigned &StructuredIndex,
2463 Expr *expr) {
2464 // No structured initializer list to update
2465 if (!StructuredList)
2466 return;
2467
Ted Kremenekac034612010-04-13 23:39:13 +00002468 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2469 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002470 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002471 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002472 diag::warn_initializer_overrides)
2473 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002474 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002475 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002476 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002477 << PrevInit->getSourceRange();
2478 }
Mike Stump11289f42009-09-09 15:08:12 +00002479
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002480 ++StructuredIndex;
2481}
2482
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002483/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002484/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002485/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002486/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002487/// failure. Returns the index expression, possibly with an implicit cast
2488/// added, on success. If everything went okay, Value will receive the
2489/// value of the constant expression.
2490static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002491CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002492 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002493
2494 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002495 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2496 if (Result.isInvalid())
2497 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002498
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002499 if (Value.isSigned() && Value.isNegative())
2500 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002501 << Value.toString(10) << Index->getSourceRange();
2502
Douglas Gregor51650d32009-01-23 21:04:18 +00002503 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002504 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002505}
2506
John McCalldadc5752010-08-24 06:29:42 +00002507ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002508 SourceLocation Loc,
2509 bool GNUSyntax,
2510 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002511 typedef DesignatedInitExpr::Designator ASTDesignator;
2512
2513 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002514 SmallVector<ASTDesignator, 32> Designators;
2515 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002516
2517 // Build designators and check array designator expressions.
2518 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2519 const Designator &D = Desig.getDesignator(Idx);
2520 switch (D.getKind()) {
2521 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002522 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002523 D.getFieldLoc()));
2524 break;
2525
2526 case Designator::ArrayDesignator: {
2527 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2528 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002529 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002530 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002531 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002532 Invalid = true;
2533 else {
2534 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002535 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002536 D.getRBracketLoc()));
2537 InitExpressions.push_back(Index);
2538 }
2539 break;
2540 }
2541
2542 case Designator::ArrayRangeDesignator: {
2543 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2544 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2545 llvm::APSInt StartValue;
2546 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002547 bool StartDependent = StartIndex->isTypeDependent() ||
2548 StartIndex->isValueDependent();
2549 bool EndDependent = EndIndex->isTypeDependent() ||
2550 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002551 if (!StartDependent)
2552 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002553 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002554 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002555 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002556
2557 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002558 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002559 else {
2560 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002561 if (StartDependent || EndDependent) {
2562 // Nothing to compute.
2563 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002564 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002565 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002566 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002567
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002568 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002569 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002570 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002571 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2572 Invalid = true;
2573 } else {
2574 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002575 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002576 D.getEllipsisLoc(),
2577 D.getRBracketLoc()));
2578 InitExpressions.push_back(StartIndex);
2579 InitExpressions.push_back(EndIndex);
2580 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002581 }
2582 break;
2583 }
2584 }
2585 }
2586
2587 if (Invalid || Init.isInvalid())
2588 return ExprError();
2589
2590 // Clear out the expressions within the designation.
2591 Desig.ClearExprs(*this);
2592
2593 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002594 = DesignatedInitExpr::Create(Context,
2595 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002596 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002597 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002598
David Blaikiebbafb8a2012-03-11 07:00:24 +00002599 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002600 Diag(DIE->getLocStart(), diag::ext_designated_init)
2601 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002602
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002603 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002604}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002605
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002606//===----------------------------------------------------------------------===//
2607// Initialization entity
2608//===----------------------------------------------------------------------===//
2609
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002610InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002611 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002612 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002613{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002614 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2615 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002616 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002617 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002618 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002619 Type = VT->getElementType();
2620 } else {
2621 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2622 assert(CT && "Unexpected type");
2623 Kind = EK_ComplexElement;
2624 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002625 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002626}
2627
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002628InitializedEntity
2629InitializedEntity::InitializeBase(ASTContext &Context,
2630 const CXXBaseSpecifier *Base,
2631 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002632 InitializedEntity Result;
2633 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002634 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002635 Result.Base = reinterpret_cast<uintptr_t>(Base);
2636 if (IsInheritedVirtualBase)
2637 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638
Douglas Gregor1b303932009-12-22 15:35:07 +00002639 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002640 return Result;
2641}
2642
Douglas Gregor85dabae2009-12-16 01:38:02 +00002643DeclarationName InitializedEntity::getName() const {
2644 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002645 case EK_Parameter:
2646 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002647 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2648 return (D ? D->getDeclName() : DeclarationName());
2649 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002650
2651 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002652 case EK_Member:
2653 return VariableOrMember->getDeclName();
2654
Douglas Gregor19666fb2012-02-15 16:57:26 +00002655 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002656 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002657
Douglas Gregor85dabae2009-12-16 01:38:02 +00002658 case EK_Result:
2659 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002660 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002661 case EK_Temporary:
2662 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002663 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002664 case EK_ArrayElement:
2665 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002666 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002667 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002668 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002669 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002670 return DeclarationName();
2671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002672
David Blaikie8a40f702012-01-17 06:56:22 +00002673 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002674}
2675
Douglas Gregora4b592a2009-12-19 03:01:41 +00002676DeclaratorDecl *InitializedEntity::getDecl() const {
2677 switch (getKind()) {
2678 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002679 case EK_Member:
2680 return VariableOrMember;
2681
John McCall31168b02011-06-15 23:02:42 +00002682 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002683 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002684 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2685
Douglas Gregora4b592a2009-12-19 03:01:41 +00002686 case EK_Result:
2687 case EK_Exception:
2688 case EK_New:
2689 case EK_Temporary:
2690 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002691 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002692 case EK_ArrayElement:
2693 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002694 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002695 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002696 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002697 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002698 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002699 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002701
David Blaikie8a40f702012-01-17 06:56:22 +00002702 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002703}
2704
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002705bool InitializedEntity::allowsNRVO() const {
2706 switch (getKind()) {
2707 case EK_Result:
2708 case EK_Exception:
2709 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002711 case EK_Variable:
2712 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002713 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002714 case EK_Member:
2715 case EK_New:
2716 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002717 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002718 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002719 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002720 case EK_ArrayElement:
2721 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002722 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002723 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002724 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002725 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002726 break;
2727 }
2728
2729 return false;
2730}
2731
Richard Smithe6c01442013-06-05 00:46:14 +00002732unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002733 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002734 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2735 for (unsigned I = 0; I != Depth; ++I)
2736 OS << "`-";
2737
2738 switch (getKind()) {
2739 case EK_Variable: OS << "Variable"; break;
2740 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002741 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2742 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002743 case EK_Result: OS << "Result"; break;
2744 case EK_Exception: OS << "Exception"; break;
2745 case EK_Member: OS << "Member"; break;
2746 case EK_New: OS << "New"; break;
2747 case EK_Temporary: OS << "Temporary"; break;
2748 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002749 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002750 case EK_Base: OS << "Base"; break;
2751 case EK_Delegating: OS << "Delegating"; break;
2752 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2753 case EK_VectorElement: OS << "VectorElement " << Index; break;
2754 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2755 case EK_BlockElement: OS << "Block"; break;
2756 case EK_LambdaCapture:
2757 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002758 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002759 break;
2760 }
2761
2762 if (Decl *D = getDecl()) {
2763 OS << " ";
2764 cast<NamedDecl>(D)->printQualifiedName(OS);
2765 }
2766
2767 OS << " '" << getType().getAsString() << "'\n";
2768
2769 return Depth + 1;
2770}
2771
2772void InitializedEntity::dump() const {
2773 dumpImpl(llvm::errs());
2774}
2775
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002776//===----------------------------------------------------------------------===//
2777// Initialization sequence
2778//===----------------------------------------------------------------------===//
2779
2780void InitializationSequence::Step::Destroy() {
2781 switch (Kind) {
2782 case SK_ResolveAddressOfOverloadedFunction:
2783 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002784 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002785 case SK_CastDerivedToBaseLValue:
2786 case SK_BindReference:
2787 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002788 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002789 case SK_UserConversion:
2790 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002791 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002792 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00002793 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00002794 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002795 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00002796 case SK_UnwrapInitList:
2797 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002798 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00002799 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002800 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002801 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002802 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002803 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002804 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002805 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002806 case SK_PassByIndirectCopyRestore:
2807 case SK_PassByIndirectRestore:
2808 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002809 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00002810 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00002811 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002812 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002813 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002815 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002816 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002817 delete ICS;
2818 }
2819}
2820
Douglas Gregor838fcc32010-03-26 20:14:36 +00002821bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002822 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002823}
2824
2825bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002826 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002827 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002828
Douglas Gregor838fcc32010-03-26 20:14:36 +00002829 switch (getFailureKind()) {
2830 case FK_TooManyInitsForReference:
2831 case FK_ArrayNeedsInitList:
2832 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002833 case FK_ArrayNeedsInitListOrWideStringLiteral:
2834 case FK_NarrowStringIntoWideCharArray:
2835 case FK_WideStringIntoCharArray:
2836 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002837 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2838 case FK_NonConstLValueReferenceBindingToTemporary:
2839 case FK_NonConstLValueReferenceBindingToUnrelated:
2840 case FK_RValueReferenceBindingToLValue:
2841 case FK_ReferenceInitDropsQualifiers:
2842 case FK_ReferenceInitFailed:
2843 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002844 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002845 case FK_TooManyInitsForScalar:
2846 case FK_ReferenceBindingToInitList:
2847 case FK_InitListBadDestinationType:
2848 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002849 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002850 case FK_ArrayTypeMismatch:
2851 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002852 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002853 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002854 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002855 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002856 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857
Douglas Gregor838fcc32010-03-26 20:14:36 +00002858 case FK_ReferenceInitOverloadFailed:
2859 case FK_UserConversionOverloadFailed:
2860 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002861 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002862 return FailedOverloadResult == OR_Ambiguous;
2863 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864
David Blaikie8a40f702012-01-17 06:56:22 +00002865 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002866}
2867
Douglas Gregorb33eed02010-04-16 22:09:46 +00002868bool InitializationSequence::isConstructorInitialization() const {
2869 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2870}
2871
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002872void
2873InitializationSequence
2874::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2875 DeclAccessPair Found,
2876 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002877 Step S;
2878 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2879 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002880 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002881 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002882 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002883 Steps.push_back(S);
2884}
2885
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002886void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002887 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002888 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002889 switch (VK) {
2890 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2891 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2892 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002893 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002894 S.Type = BaseType;
2895 Steps.push_back(S);
2896}
2897
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002898void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002899 bool BindingTemporary) {
2900 Step S;
2901 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2902 S.Type = T;
2903 Steps.push_back(S);
2904}
2905
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002906void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2907 Step S;
2908 S.Kind = SK_ExtraneousCopyToTemporary;
2909 S.Type = T;
2910 Steps.push_back(S);
2911}
2912
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002913void
2914InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2915 DeclAccessPair FoundDecl,
2916 QualType T,
2917 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002918 Step S;
2919 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002920 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002921 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002922 S.Function.Function = Function;
2923 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002924 Steps.push_back(S);
2925}
2926
2927void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002928 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002929 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002930 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002931 switch (VK) {
2932 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002933 S.Kind = SK_QualificationConversionRValue;
2934 break;
John McCall2536c6d2010-08-25 10:28:54 +00002935 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002936 S.Kind = SK_QualificationConversionXValue;
2937 break;
John McCall2536c6d2010-08-25 10:28:54 +00002938 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002939 S.Kind = SK_QualificationConversionLValue;
2940 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002941 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002942 S.Type = Ty;
2943 Steps.push_back(S);
2944}
2945
Richard Smith77be48a2014-07-31 06:31:19 +00002946void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
2947 Step S;
2948 S.Kind = SK_AtomicConversion;
2949 S.Type = Ty;
2950 Steps.push_back(S);
2951}
2952
Jordan Roseb1312a52013-04-11 00:58:58 +00002953void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2954 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2955
2956 Step S;
2957 S.Kind = SK_LValueToRValue;
2958 S.Type = Ty;
2959 Steps.push_back(S);
2960}
2961
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002962void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002963 const ImplicitConversionSequence &ICS, QualType T,
2964 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002965 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002966 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2967 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002968 S.Type = T;
2969 S.ICS = new ImplicitConversionSequence(ICS);
2970 Steps.push_back(S);
2971}
2972
Douglas Gregor51e77d52009-12-10 17:56:55 +00002973void InitializationSequence::AddListInitializationStep(QualType T) {
2974 Step S;
2975 S.Kind = SK_ListInitialization;
2976 S.Type = T;
2977 Steps.push_back(S);
2978}
2979
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002981InitializationSequence
2982::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2983 AccessSpecifier Access,
2984 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002985 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002986 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002987 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00002988 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00002989 : SK_ConstructorInitializationFromList
2990 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002991 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002992 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002993 S.Function.Function = Constructor;
2994 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002995 Steps.push_back(S);
2996}
2997
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002998void InitializationSequence::AddZeroInitializationStep(QualType T) {
2999 Step S;
3000 S.Kind = SK_ZeroInitialization;
3001 S.Type = T;
3002 Steps.push_back(S);
3003}
3004
Douglas Gregore1314a62009-12-18 05:02:21 +00003005void InitializationSequence::AddCAssignmentStep(QualType T) {
3006 Step S;
3007 S.Kind = SK_CAssignment;
3008 S.Type = T;
3009 Steps.push_back(S);
3010}
3011
Eli Friedman78275202009-12-19 08:11:05 +00003012void InitializationSequence::AddStringInitStep(QualType T) {
3013 Step S;
3014 S.Kind = SK_StringInit;
3015 S.Type = T;
3016 Steps.push_back(S);
3017}
3018
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003019void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3020 Step S;
3021 S.Kind = SK_ObjCObjectConversion;
3022 S.Type = T;
3023 Steps.push_back(S);
3024}
3025
Douglas Gregore2f943b2011-02-22 18:29:51 +00003026void InitializationSequence::AddArrayInitStep(QualType T) {
3027 Step S;
3028 S.Kind = SK_ArrayInit;
3029 S.Type = T;
3030 Steps.push_back(S);
3031}
3032
Richard Smithebeed412012-02-15 22:38:09 +00003033void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3034 Step S;
3035 S.Kind = SK_ParenthesizedArrayInit;
3036 S.Type = T;
3037 Steps.push_back(S);
3038}
3039
John McCall31168b02011-06-15 23:02:42 +00003040void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3041 bool shouldCopy) {
3042 Step s;
3043 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3044 : SK_PassByIndirectRestore);
3045 s.Type = type;
3046 Steps.push_back(s);
3047}
3048
3049void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3050 Step S;
3051 S.Kind = SK_ProduceObjCObject;
3052 S.Type = T;
3053 Steps.push_back(S);
3054}
3055
Sebastian Redlc1839b12012-01-17 22:49:42 +00003056void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3057 Step S;
3058 S.Kind = SK_StdInitializerList;
3059 S.Type = T;
3060 Steps.push_back(S);
3061}
3062
Guy Benyei61054192013-02-07 10:55:47 +00003063void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3064 Step S;
3065 S.Kind = SK_OCLSamplerInit;
3066 S.Type = T;
3067 Steps.push_back(S);
3068}
3069
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003070void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3071 Step S;
3072 S.Kind = SK_OCLZeroEvent;
3073 S.Type = T;
3074 Steps.push_back(S);
3075}
3076
Sebastian Redl29526f02011-11-27 16:50:07 +00003077void InitializationSequence::RewrapReferenceInitList(QualType T,
3078 InitListExpr *Syntactic) {
3079 assert(Syntactic->getNumInits() == 1 &&
3080 "Can only rewrap trivial init lists.");
3081 Step S;
3082 S.Kind = SK_UnwrapInitList;
3083 S.Type = Syntactic->getInit(0)->getType();
3084 Steps.insert(Steps.begin(), S);
3085
3086 S.Kind = SK_RewrapInitList;
3087 S.Type = T;
3088 S.WrappingSyntacticList = Syntactic;
3089 Steps.push_back(S);
3090}
3091
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003093 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003094 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003095 this->Failure = Failure;
3096 this->FailedOverloadResult = Result;
3097}
3098
3099//===----------------------------------------------------------------------===//
3100// Attempt initialization
3101//===----------------------------------------------------------------------===//
3102
John McCall31168b02011-06-15 23:02:42 +00003103static void MaybeProduceObjCObject(Sema &S,
3104 InitializationSequence &Sequence,
3105 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003106 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003107
3108 /// When initializing a parameter, produce the value if it's marked
3109 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003110 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003111 if (!Entity.isParameterConsumed())
3112 return;
3113
3114 assert(Entity.getType()->isObjCRetainableType() &&
3115 "consuming an object of unretainable type?");
3116 Sequence.AddProduceObjCObjectStep(Entity.getType());
3117
3118 /// When initializing a return value, if the return type is a
3119 /// retainable type, then returns need to immediately retain the
3120 /// object. If an autorelease is required, it will be done at the
3121 /// last instant.
3122 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3123 if (!Entity.getType()->isObjCRetainableType())
3124 return;
3125
3126 Sequence.AddProduceObjCObjectStep(Entity.getType());
3127 }
3128}
3129
Richard Smithcc1b96d2013-06-12 22:31:48 +00003130static void TryListInitialization(Sema &S,
3131 const InitializedEntity &Entity,
3132 const InitializationKind &Kind,
3133 InitListExpr *InitList,
3134 InitializationSequence &Sequence);
3135
Richard Smithd86812d2012-07-05 08:39:21 +00003136/// \brief When initializing from init list via constructor, handle
3137/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003138///
Richard Smithd86812d2012-07-05 08:39:21 +00003139/// \return true if we have handled initialization of an object of type
3140/// std::initializer_list<T>, false otherwise.
3141static bool TryInitializerListConstruction(Sema &S,
3142 InitListExpr *List,
3143 QualType DestType,
3144 InitializationSequence &Sequence) {
3145 QualType E;
3146 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003147 return false;
3148
Richard Smithcc1b96d2013-06-12 22:31:48 +00003149 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3150 Sequence.setIncompleteTypeFailure(E);
3151 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003152 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003153
3154 // Try initializing a temporary array from the init list.
3155 QualType ArrayType = S.Context.getConstantArrayType(
3156 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3157 List->getNumInits()),
3158 clang::ArrayType::Normal, 0);
3159 InitializedEntity HiddenArray =
3160 InitializedEntity::InitializeTemporary(ArrayType);
3161 InitializationKind Kind =
3162 InitializationKind::CreateDirectList(List->getExprLoc());
3163 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3164 if (Sequence)
3165 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003166 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003167}
3168
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003169static OverloadingResult
3170ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003171 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003172 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003173 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003174 OverloadCandidateSet::iterator &Best,
3175 bool CopyInitializing, bool AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003176 bool OnlyListConstructors, bool IsListInit) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003177 CandidateSet.clear();
3178
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003179 for (ArrayRef<NamedDecl *>::iterator
3180 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003181 NamedDecl *D = *Con;
3182 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3183 bool SuppressUserConversions = false;
3184
3185 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003186 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003187 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3188 if (ConstructorTmpl)
3189 Constructor = cast<CXXConstructorDecl>(
3190 ConstructorTmpl->getTemplatedDecl());
3191 else {
3192 Constructor = cast<CXXConstructorDecl>(D);
3193
Richard Smith6c6ddab2013-09-21 21:23:47 +00003194 // C++11 [over.best.ics]p4:
Larisse Voufo19d08672015-01-27 18:47:05 +00003195 // ... and the constructor or user-defined conversion function is a
3196 // candidate by
3197 // — 13.3.1.3, when the argument is the temporary in the second step
3198 // of a class copy-initialization, or
3199 // — 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
3200 // user-defined conversion sequences are not considered.
Larisse Voufobcf327a2015-02-10 02:20:14 +00003201 // FIXME: This breaks backward compatibility, e.g. PR12117. As a
3202 // temporary fix, let's re-instate the third bullet above until
3203 // there is a resolution in the standard, i.e.,
3204 // - 13.3.1.7 when the initializer list has exactly one element that is
3205 // itself an initializer list and a conversion to some class X or
3206 // reference to (possibly cv-qualified) X is considered for the first
3207 // parameter of a constructor of X.
3208 if ((CopyInitializing ||
3209 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3210 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003211 SuppressUserConversions = true;
3212 }
3213
3214 if (!Constructor->isInvalidDecl() &&
3215 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003216 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003217 if (ConstructorTmpl)
3218 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003219 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003220 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003221 else {
3222 // C++ [over.match.copy]p1:
3223 // - When initializing a temporary to be bound to the first parameter
3224 // of a constructor that takes a reference to possibly cv-qualified
3225 // T as its first argument, called with a single argument in the
3226 // context of direct-initialization, explicit conversion functions
3227 // are also considered.
3228 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003229 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003230 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003231 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003232 SuppressUserConversions,
3233 /*PartialOverloading=*/false,
3234 /*AllowExplicit=*/AllowExplicitConv);
3235 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003236 }
3237 }
3238
3239 // Perform overload resolution and return the result.
3240 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3241}
3242
Sebastian Redled2e5322011-12-22 14:44:04 +00003243/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3244/// enumerates the constructors of the initialized entity and performs overload
3245/// resolution to select the best.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003246/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003247/// \param IsInitListCopy Is this non-list-initialization resulting from a
3248/// list-initialization from {x} where x is the same
3249/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003250static void TryConstructorInitialization(Sema &S,
3251 const InitializedEntity &Entity,
3252 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003253 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003254 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003255 bool IsListInit = false,
3256 bool IsInitListCopy = false) {
3257 assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3258 "IsListInit must come with a single initializer list argument.");
Sebastian Redl88e4d492012-02-04 21:27:33 +00003259
Sebastian Redled2e5322011-12-22 14:44:04 +00003260 // The type we're constructing needs to be complete.
3261 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003262 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003263 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003264 }
3265
3266 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3267 assert(DestRecordType && "Constructor initialization requires record type");
3268 CXXRecordDecl *DestRecordDecl
3269 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3270
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003271 // Build the candidate set directly in the initialization sequence
3272 // structure, so that it will persist if we fail.
3273 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3274
3275 // Determine whether we are allowed to call explicit constructors or
3276 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003277 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003278 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003279
Sebastian Redled2e5322011-12-22 14:44:04 +00003280 // - Otherwise, if T is a class type, constructors are considered. The
3281 // applicable constructors are enumerated, and the best one is chosen
3282 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003283 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003284 // The container holding the constructors can under certain conditions
3285 // be changed while iterating (e.g. because of deserialization).
3286 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003287 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003288
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003289 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003290 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003291 bool AsInitializerList = false;
3292
Larisse Voufo19d08672015-01-27 18:47:05 +00003293 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003294 // When objects of non-aggregate type T are list-initialized, such that
3295 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3296 // according to the rules in this section, overload resolution selects
3297 // the constructor in two phases:
3298 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003299 // - Initially, the candidate functions are the initializer-list
3300 // constructors of the class T and the argument list consists of the
3301 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003302 if (IsListInit) {
Richard Smithd86812d2012-07-05 08:39:21 +00003303 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003304 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003305
3306 // If the initializer list has no elements and T has a default constructor,
3307 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003308 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003309 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003310 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003311 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003312 /*OnlyListConstructor=*/true,
3313 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003314
3315 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003316 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003317 }
3318
3319 // C++11 [over.match.list]p1:
3320 // - If no viable initializer-list constructor is found, overload resolution
3321 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003322 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003323 // elements of the initializer list.
3324 if (Result == OR_No_Viable_Function) {
3325 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003326 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003327 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003328 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003329 /*OnlyListConstructors=*/false,
3330 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003331 }
3332 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003333 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003334 InitializationSequence::FK_ListConstructorOverloadFailed :
3335 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003336 Result);
3337 return;
3338 }
3339
Richard Smithd86812d2012-07-05 08:39:21 +00003340 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003341 // If a program calls for the default initialization of an object
3342 // of a const-qualified type T, T shall be a class type with a
3343 // user-provided default constructor.
3344 if (Kind.getKind() == InitializationKind::IK_Default &&
3345 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003346 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003347 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3348 return;
3349 }
3350
Sebastian Redl048a6d72012-04-01 19:54:59 +00003351 // C++11 [over.match.list]p1:
3352 // In copy-list-initialization, if an explicit constructor is chosen, the
3353 // initializer is ill-formed.
3354 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smithed83ebd2015-02-05 07:02:11 +00003355 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003356 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3357 return;
3358 }
3359
Sebastian Redled2e5322011-12-22 14:44:04 +00003360 // Add the constructor initialization step. Any cv-qualification conversion is
3361 // subsumed by the initialization.
3362 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithed83ebd2015-02-05 07:02:11 +00003363 Sequence.AddConstructorInitializationStep(
3364 CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
3365 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003366}
3367
Sebastian Redl29526f02011-11-27 16:50:07 +00003368static bool
3369ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3370 Expr *Initializer,
3371 QualType &SourceType,
3372 QualType &UnqualifiedSourceType,
3373 QualType UnqualifiedTargetType,
3374 InitializationSequence &Sequence) {
3375 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3376 S.Context.OverloadTy) {
3377 DeclAccessPair Found;
3378 bool HadMultipleCandidates = false;
3379 if (FunctionDecl *Fn
3380 = S.ResolveAddressOfOverloadedFunction(Initializer,
3381 UnqualifiedTargetType,
3382 false, Found,
3383 &HadMultipleCandidates)) {
3384 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3385 HadMultipleCandidates);
3386 SourceType = Fn->getType();
3387 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3388 } else if (!UnqualifiedTargetType->isRecordType()) {
3389 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3390 return true;
3391 }
3392 }
3393 return false;
3394}
3395
3396static void TryReferenceInitializationCore(Sema &S,
3397 const InitializedEntity &Entity,
3398 const InitializationKind &Kind,
3399 Expr *Initializer,
3400 QualType cv1T1, QualType T1,
3401 Qualifiers T1Quals,
3402 QualType cv2T2, QualType T2,
3403 Qualifiers T2Quals,
3404 InitializationSequence &Sequence);
3405
Richard Smithd86812d2012-07-05 08:39:21 +00003406static void TryValueInitialization(Sema &S,
3407 const InitializedEntity &Entity,
3408 const InitializationKind &Kind,
3409 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003410 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003411
Sebastian Redl29526f02011-11-27 16:50:07 +00003412/// \brief Attempt list initialization of a reference.
3413static void TryReferenceListInitialization(Sema &S,
3414 const InitializedEntity &Entity,
3415 const InitializationKind &Kind,
3416 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003417 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003418 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003419 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003420 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3421 return;
3422 }
3423
3424 QualType DestType = Entity.getType();
3425 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3426 Qualifiers T1Quals;
3427 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3428
3429 // Reference initialization via an initializer list works thus:
3430 // If the initializer list consists of a single element that is
3431 // reference-related to the referenced type, bind directly to that element
3432 // (possibly creating temporaries).
3433 // Otherwise, initialize a temporary with the initializer list and
3434 // bind to that.
3435 if (InitList->getNumInits() == 1) {
3436 Expr *Initializer = InitList->getInit(0);
3437 QualType cv2T2 = Initializer->getType();
3438 Qualifiers T2Quals;
3439 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3440
3441 // If this fails, creating a temporary wouldn't work either.
3442 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3443 T1, Sequence))
3444 return;
3445
3446 SourceLocation DeclLoc = Initializer->getLocStart();
3447 bool dummy1, dummy2, dummy3;
3448 Sema::ReferenceCompareResult RefRelationship
3449 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3450 dummy2, dummy3);
3451 if (RefRelationship >= Sema::Ref_Related) {
3452 // Try to bind the reference here.
3453 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3454 T1Quals, cv2T2, T2, T2Quals, Sequence);
3455 if (Sequence)
3456 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3457 return;
3458 }
Richard Smith03d93932013-01-15 07:58:29 +00003459
3460 // Update the initializer if we've resolved an overloaded function.
3461 if (Sequence.step_begin() != Sequence.step_end())
3462 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003463 }
3464
3465 // Not reference-related. Create a temporary and bind to that.
3466 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3467
3468 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3469 if (Sequence) {
3470 if (DestType->isRValueReferenceType() ||
3471 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3472 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3473 else
3474 Sequence.SetFailed(
3475 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3476 }
3477}
3478
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003479/// \brief Attempt list initialization (C++0x [dcl.init.list])
3480static void TryListInitialization(Sema &S,
3481 const InitializedEntity &Entity,
3482 const InitializationKind &Kind,
3483 InitListExpr *InitList,
3484 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003485 QualType DestType = Entity.getType();
3486
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003487 // C++ doesn't allow scalar initialization with more than one argument.
3488 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003489 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003490 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3491 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3492 return;
3493 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003494 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003495 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003496 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003497 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003498
Larisse Voufod2010992015-01-24 23:09:54 +00003499 if (DestType->isRecordType() &&
3500 S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3501 Sequence.setIncompleteTypeFailure(DestType);
3502 return;
3503 }
Richard Smithd86812d2012-07-05 08:39:21 +00003504
Larisse Voufo19d08672015-01-27 18:47:05 +00003505 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003506 // - If T is a class type and the initializer list has a single element of
3507 // type cv U, where U is T or a class derived from T, the object is
3508 // initialized from that element (by copy-initialization for
3509 // copy-list-initialization, or by direct-initialization for
3510 // direct-list-initialization).
3511 // - Otherwise, if T is a character array and the initializer list has a
3512 // single element that is an appropriately-typed string literal
3513 // (8.5.2 [dcl.init.string]), initialization is performed as described
3514 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003515 // - Otherwise, if T is an aggregate, [...] (continue below).
3516 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003517 if (DestType->isRecordType()) {
3518 QualType InitType = InitList->getInit(0)->getType();
3519 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
3520 S.IsDerivedFrom(InitType, DestType)) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003521 Expr *InitAsExpr = InitList->getInit(0);
3522 TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
3523 Sequence, /*InitListSyntax*/ false,
3524 /*IsInitListCopy*/ true);
Larisse Voufod2010992015-01-24 23:09:54 +00003525 return;
3526 }
3527 }
3528 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3529 Expr *SubInit[1] = {InitList->getInit(0)};
3530 if (!isa<VariableArrayType>(DestAT) &&
3531 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3532 InitializationKind SubKind =
3533 Kind.getKind() == InitializationKind::IK_DirectList
3534 ? InitializationKind::CreateDirect(Kind.getLocation(),
3535 InitList->getLBraceLoc(),
3536 InitList->getRBraceLoc())
3537 : Kind;
3538 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3539 /*TopLevelOfInitList*/ true);
3540
3541 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3542 // the element is not an appropriately-typed string literal, in which
3543 // case we should proceed as in C++11 (below).
3544 if (Sequence) {
3545 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3546 return;
3547 }
3548 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003549 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003550 }
Larisse Voufod2010992015-01-24 23:09:54 +00003551
3552 // C++11 [dcl.init.list]p3:
3553 // - If T is an aggregate, aggregate initialization is performed.
3554 if (DestType->isRecordType() && !DestType->isAggregateType()) {
3555 if (S.getLangOpts().CPlusPlus11) {
3556 // - Otherwise, if the initializer list has no elements and T is a
3557 // class type with a default constructor, the object is
3558 // value-initialized.
3559 if (InitList->getNumInits() == 0) {
3560 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3561 if (RD->hasDefaultConstructor()) {
3562 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3563 return;
3564 }
3565 }
3566
3567 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3568 // an initializer_list object constructed [...]
3569 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3570 return;
3571
3572 // - Otherwise, if T is a class type, constructors are considered.
3573 Expr *InitListAsExpr = InitList;
3574 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3575 Sequence, /*InitListSyntax*/ true);
3576 } else
3577 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3578 return;
3579 }
3580
Richard Smith089c3162013-09-21 21:55:46 +00003581 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3582 InitList->getNumInits() == 1 &&
3583 InitList->getInit(0)->getType()->isRecordType()) {
3584 // - Otherwise, if the initializer list has a single element of type E
3585 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00003586 // initialized from that element (by copy-initialization for
3587 // copy-list-initialization, or by direct-initialization for
3588 // direct-list-initialization); if a narrowing conversion is required
3589 // to convert the element to T, the program is ill-formed.
3590 //
Richard Smith089c3162013-09-21 21:55:46 +00003591 // Per core-24034, this is direct-initialization if we were performing
3592 // direct-list-initialization and copy-initialization otherwise.
3593 // We can't use InitListChecker for this, because it always performs
3594 // copy-initialization. This only matters if we might use an 'explicit'
3595 // conversion operator, so we only need to handle the cases where the source
3596 // is of record type.
3597 InitializationKind SubKind =
3598 Kind.getKind() == InitializationKind::IK_DirectList
3599 ? InitializationKind::CreateDirect(Kind.getLocation(),
3600 InitList->getLBraceLoc(),
3601 InitList->getRBraceLoc())
3602 : Kind;
3603 Expr *SubInit[1] = { InitList->getInit(0) };
3604 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3605 /*TopLevelOfInitList*/true);
3606 if (Sequence)
3607 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3608 return;
3609 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003610
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003611 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003612 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003613 if (CheckInitList.HadError()) {
3614 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3615 return;
3616 }
3617
3618 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003619 Sequence.AddListInitializationStep(DestType);
3620}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621
3622/// \brief Try a reference initialization that involves calling a conversion
3623/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003624static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3625 const InitializedEntity &Entity,
3626 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003627 Expr *Initializer,
3628 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003629 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003630 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003631 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3632 QualType T1 = cv1T1.getUnqualifiedType();
3633 QualType cv2T2 = Initializer->getType();
3634 QualType T2 = cv2T2.getUnqualifiedType();
3635
3636 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003637 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003638 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003640 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003641 ObjCConversion,
3642 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003643 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003644 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003645 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003646 (void)ObjCLifetimeConversion;
3647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 // Build the candidate set directly in the initialization sequence
3649 // structure, so that it will persist if we fail.
3650 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3651 CandidateSet.clear();
3652
3653 // Determine whether we are allowed to call explicit constructors or
3654 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003655 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003656 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3657
Craig Topperc3ec1492014-05-26 06:22:03 +00003658 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003659 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3660 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003661 // The type we're converting to is a class type. Enumerate its constructors
3662 // to see if there is a suitable conversion.
3663 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003664
David Blaikieff7d47a2012-12-19 00:45:41 +00003665 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003666 // The container holding the constructors can under certain conditions
3667 // be changed while iterating (e.g. because of deserialization).
3668 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003669 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003670 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003671 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3672 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003673 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3674
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003675 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003676 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003677 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003678 if (ConstructorTmpl)
3679 Constructor = cast<CXXConstructorDecl>(
3680 ConstructorTmpl->getTemplatedDecl());
3681 else
John McCalla0296f72010-03-19 07:35:19 +00003682 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003684 if (!Constructor->isInvalidDecl() &&
3685 Constructor->isConvertingConstructor(AllowExplicit)) {
3686 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003687 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003688 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003689 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003690 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003691 else
John McCalla0296f72010-03-19 07:35:19 +00003692 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003693 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003694 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003697 }
John McCall3696dcb2010-08-17 07:23:57 +00003698 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3699 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
Craig Topperc3ec1492014-05-26 06:22:03 +00003701 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003702 if ((T2RecordType = T2->getAs<RecordType>()) &&
3703 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003704 // The type we're converting from is a class type, enumerate its conversion
3705 // functions.
3706 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3707
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003708 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
3709 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003710 NamedDecl *D = *I;
3711 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3712 if (isa<UsingShadowDecl>(D))
3713 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003715 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3716 CXXConversionDecl *Conv;
3717 if (ConvTemplate)
3718 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3719 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003720 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003722 // If the conversion function doesn't return a reference type,
3723 // it can't be considered for this conversion unless we're allowed to
3724 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725 // FIXME: Do we need to make sure that we only consider conversion
3726 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003727 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003728 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003729 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3730 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003731 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003732 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003733 DestType, CandidateSet,
3734 /*AllowObjCConversionOnExplicit=*/
3735 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003736 else
John McCalla0296f72010-03-19 07:35:19 +00003737 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003738 Initializer, DestType, CandidateSet,
3739 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003740 }
3741 }
3742 }
John McCall3696dcb2010-08-17 07:23:57 +00003743 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3744 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003746 SourceLocation DeclLoc = Initializer->getLocStart();
3747
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003749 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003751 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003753
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003754 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003755 // This is the overload that will be used for this initialization step if we
3756 // use this initialization. Mark it as referenced.
3757 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003758
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003759 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003760 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003761 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003762 else
3763 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003764
3765 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003766 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003767 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003768 T2.getNonLValueExprType(S.Context),
3769 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003770
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003772 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003773 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003774 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003775 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003776 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003777 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003778
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003779 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003780 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003781 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003782 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003783 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003784 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003785 NewDerivedToBase, NewObjCConversion,
3786 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003787 if (NewRefRelationship == Sema::Ref_Incompatible) {
3788 // If the type we've converted to is not reference-related to the
3789 // type we're looking for, then there is another conversion step
3790 // we need to perform to produce a temporary of the right type
3791 // that we'll be binding to.
3792 ImplicitConversionSequence ICS;
3793 ICS.setStandard();
3794 ICS.Standard = Best->FinalConversion;
3795 T2 = ICS.Standard.getToType(2);
3796 Sequence.AddConversionSequenceStep(ICS, T2);
3797 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003798 Sequence.AddDerivedToBaseCastStep(
3799 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003801 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003802 else if (NewObjCConversion)
3803 Sequence.AddObjCObjectConversionStep(
3804 S.Context.getQualifiedType(T1,
3805 T2.getNonReferenceType().getQualifiers()));
3806
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003807 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003808 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003810 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3811 return OR_Success;
3812}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813
Richard Smithc620f552011-10-19 16:55:56 +00003814static void CheckCXX98CompatAccessibleCopy(Sema &S,
3815 const InitializedEntity &Entity,
3816 Expr *CurInitExpr);
3817
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3819static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003820 const InitializedEntity &Entity,
3821 const InitializationKind &Kind,
3822 Expr *Initializer,
3823 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003824 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003825 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003826 Qualifiers T1Quals;
3827 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003828 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003829 Qualifiers T2Quals;
3830 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003831
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003832 // If the initializer is the address of an overloaded function, try
3833 // to resolve the overloaded function. If all goes well, T2 is the
3834 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003835 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3836 T1, Sequence))
3837 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003838
Sebastian Redl29526f02011-11-27 16:50:07 +00003839 // Delegate everything else to a subfunction.
3840 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3841 T1Quals, cv2T2, T2, T2Quals, Sequence);
3842}
3843
Jordan Roseb1312a52013-04-11 00:58:58 +00003844/// Converts the target of reference initialization so that it has the
3845/// appropriate qualifiers and value kind.
3846///
3847/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3848/// \code
3849/// int x;
3850/// const int &r = x;
3851/// \endcode
3852///
3853/// In this case the reference is binding to a bitfield lvalue, which isn't
3854/// valid. Perform a load to create a lifetime-extended temporary instead.
3855/// \code
3856/// const int &r = someStruct.bitfield;
3857/// \endcode
3858static ExprValueKind
3859convertQualifiersAndValueKindIfNecessary(Sema &S,
3860 InitializationSequence &Sequence,
3861 Expr *Initializer,
3862 QualType cv1T1,
3863 Qualifiers T1Quals,
3864 Qualifiers T2Quals,
3865 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003866 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003867 Initializer->refersToVectorElement();
3868
3869 if (IsNonAddressableType) {
3870 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3871 // lvalue reference to a non-volatile const type, or the reference shall be
3872 // an rvalue reference.
3873 //
3874 // If not, we can't make a temporary and bind to that. Give up and allow the
3875 // error to be diagnosed later.
3876 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3877 assert(Initializer->isGLValue());
3878 return Initializer->getValueKind();
3879 }
3880
3881 // Force a load so we can materialize a temporary.
3882 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3883 return VK_RValue;
3884 }
3885
3886 if (T1Quals != T2Quals) {
3887 Sequence.AddQualificationConversionStep(cv1T1,
3888 Initializer->getValueKind());
3889 }
3890
3891 return Initializer->getValueKind();
3892}
3893
3894
Sebastian Redl29526f02011-11-27 16:50:07 +00003895/// \brief Reference initialization without resolving overloaded functions.
3896static void TryReferenceInitializationCore(Sema &S,
3897 const InitializedEntity &Entity,
3898 const InitializationKind &Kind,
3899 Expr *Initializer,
3900 QualType cv1T1, QualType T1,
3901 Qualifiers T1Quals,
3902 QualType cv2T2, QualType T2,
3903 Qualifiers T2Quals,
3904 InitializationSequence &Sequence) {
3905 QualType DestType = Entity.getType();
3906 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003907 // Compute some basic properties of the types and the initializer.
3908 bool isLValueRef = DestType->isLValueReferenceType();
3909 bool isRValueRef = !isLValueRef;
3910 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003911 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003912 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003913 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003914 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003915 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003916 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003917
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003918 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003920 // "cv2 T2" as follows:
3921 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003923 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003924 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003925 // there are no function rvalues in C++, rvalue refs to functions are treated
3926 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003927 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003928 bool T1Function = T1->isFunctionType();
3929 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003931 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003933 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003935 // reference-compatible with "cv2 T2," or
3936 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003938 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003939 // can occur. However, we do pay attention to whether it is a bit-field
3940 // to decide whether we're actually binding to a temporary created from
3941 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003942 if (DerivedToBase)
3943 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003944 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003945 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003946 else if (ObjCConversion)
3947 Sequence.AddObjCObjectConversionStep(
3948 S.Context.getQualifiedType(T1, T2Quals));
3949
Jordan Roseb1312a52013-04-11 00:58:58 +00003950 ExprValueKind ValueKind =
3951 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3952 cv1T1, T1Quals, T2Quals,
3953 isLValueRef);
3954 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003955 return;
3956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957
3958 // - has a class type (i.e., T2 is a class type), where T1 is not
3959 // reference-related to T2, and can be implicitly converted to an
3960 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3961 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003962 // applicable conversion functions (13.3.1.6) and choosing the best
3963 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003964 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003965 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003966 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3967 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003968 ConvOvlResult = TryRefInitWithConversionFunction(
3969 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003970 if (ConvOvlResult == OR_Success)
3971 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003972 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003973 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003974 InitializationSequence::FK_ReferenceInitOverloadFailed,
3975 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003976 }
3977 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003978
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003979 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003980 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003981 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003982 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003983 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3984 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3985 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003986 Sequence.SetOverloadFailure(
3987 InitializationSequence::FK_ReferenceInitOverloadFailed,
3988 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003989 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003990 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003991 ? (RefRelationship == Sema::Ref_Related
3992 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3993 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3994 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003995
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003996 return;
3997 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003998
Douglas Gregor92e460e2011-01-20 16:44:54 +00003999 // - If the initializer expression
4000 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
4001 // "cv1 T1" is reference-compatible with "cv2 T2"
4002 // Note: functions are handled below.
4003 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00004004 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004005 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004006 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00004007 (InitCategory.isXValue() ||
4008 (InitCategory.isPRValue() && T2->isRecordType()) ||
4009 (InitCategory.isPRValue() && T2->isArrayType()))) {
4010 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
4011 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004012 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4013 // compiler the freedom to perform a copy here or bind to the
4014 // object, while C++0x requires that we bind directly to the
4015 // object. Hence, we always bind to the object without making an
4016 // extra copy. However, in C++03 requires that we check for the
4017 // presence of a suitable copy constructor:
4018 //
4019 // The constructor that would be used to make the copy shall
4020 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004021 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004022 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004023 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004024 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004025 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026
Douglas Gregor92e460e2011-01-20 16:44:54 +00004027 if (DerivedToBase)
4028 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
4029 ValueKind);
4030 else if (ObjCConversion)
4031 Sequence.AddObjCObjectConversionStep(
4032 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Jordan Roseb1312a52013-04-11 00:58:58 +00004034 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
4035 Initializer, cv1T1,
4036 T1Quals, T2Quals,
4037 isLValueRef);
4038
4039 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042
4043 // - has a class type (i.e., T2 is a class type), where T1 is not
4044 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004045 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4046 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004047 //
4048 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004049 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004050 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004051 ConvOvlResult = TryRefInitWithConversionFunction(
4052 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004053 if (ConvOvlResult)
4054 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004055 InitializationSequence::FK_ReferenceInitOverloadFailed,
4056 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004058 return;
4059 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004061 if ((RefRelationship == Sema::Ref_Compatible ||
4062 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
4063 isRValueRef && InitCategory.isLValue()) {
4064 Sequence.SetFailed(
4065 InitializationSequence::FK_RValueReferenceBindingToLValue);
4066 return;
4067 }
4068
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004069 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4070 return;
4071 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004072
4073 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004074 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004075 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004076 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004077
John McCallec6f4e92010-06-04 02:29:22 +00004078 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4079
Richard Smith2eabf782013-06-13 00:57:57 +00004080 // FIXME: Why do we use an implicit conversion here rather than trying
4081 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004082 ImplicitConversionSequence ICS
4083 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004084 /*SuppressUserConversions=*/false,
4085 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004086 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004087 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4088 /*AllowObjCWritebackConversion=*/false);
4089
4090 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004091 // FIXME: Use the conversion function set stored in ICS to turn
4092 // this into an overloading ambiguity diagnostic. However, we need
4093 // to keep that set as an OverloadCandidateSet rather than as some
4094 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004095 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4096 Sequence.SetOverloadFailure(
4097 InitializationSequence::FK_ReferenceInitOverloadFailed,
4098 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004099 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4100 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004101 else
4102 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004103 return;
John McCall31168b02011-06-15 23:02:42 +00004104 } else {
4105 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004106 }
4107
4108 // [...] If T1 is reference-related to T2, cv1 must be the
4109 // same cv-qualification as, or greater cv-qualification
4110 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004111 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4112 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004114 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004115 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4116 return;
4117 }
4118
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004120 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004122 InitCategory.isLValue()) {
4123 Sequence.SetFailed(
4124 InitializationSequence::FK_RValueReferenceBindingToLValue);
4125 return;
4126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004128 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4129 return;
4130}
4131
4132/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133/// (C++ [dcl.init.string], C99 6.7.8).
4134static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004135 const InitializedEntity &Entity,
4136 const InitializationKind &Kind,
4137 Expr *Initializer,
4138 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004139 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004140}
4141
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004142/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004144 const InitializedEntity &Entity,
4145 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004146 InitializationSequence &Sequence,
4147 InitListExpr *InitList) {
4148 assert((!InitList || InitList->getNumInits() == 0) &&
4149 "Shouldn't use value-init for non-empty init lists");
4150
Richard Smith1bfe0682012-02-14 21:14:13 +00004151 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004152 //
4153 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004154 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004156 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004157 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004159 if (const RecordType *RT = T->getAs<RecordType>()) {
4160 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004161 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004162 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004163 // C++98:
4164 // -- if T is a class type (clause 9) with a user-declared constructor
4165 // (12.1), then the default constructor for T is called (and the
4166 // initialization is ill-formed if T has no accessible default
4167 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004168 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004169 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004170 } else {
4171 // C++11:
4172 // -- if T is a class type (clause 9) with either no default constructor
4173 // (12.1 [class.ctor]) or a default constructor that is user-provided
4174 // or deleted, then the object is default-initialized;
4175 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4176 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004177 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004179
Richard Smith1bfe0682012-02-14 21:14:13 +00004180 // -- if T is a (possibly cv-qualified) non-union class type without a
4181 // user-provided or deleted default constructor, then the object is
4182 // zero-initialized and, if T has a non-trivial default constructor,
4183 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004184 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4185 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004186 if (NeedZeroInitialization)
4187 Sequence.AddZeroInitializationStep(Entity.getType());
4188
Richard Smith593f9932012-12-08 02:01:17 +00004189 // C++03:
4190 // -- if T is a non-union class type without a user-declared constructor,
4191 // then every non-static data member and base class component of T is
4192 // value-initialized;
4193 // [...] A program that calls for [...] value-initialization of an
4194 // entity of reference type is ill-formed.
4195 //
4196 // C++11 doesn't need this handling, because value-initialization does not
4197 // occur recursively there, and the implicit default constructor is
4198 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004199 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004200 ClassDecl->hasUninitializedReferenceMember()) {
4201 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4202 return;
4203 }
4204
Richard Smithd86812d2012-07-05 08:39:21 +00004205 // If this is list-value-initialization, pass the empty init list on when
4206 // building the constructor call. This affects the semantics of a few
4207 // things (such as whether an explicit default constructor can be called).
4208 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004209 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004210 bool InitListSyntax = InitList;
4211
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004212 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4213 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004214 }
4215 }
4216
Douglas Gregor1b303932009-12-22 15:35:07 +00004217 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004218}
4219
Douglas Gregor85dabae2009-12-16 01:38:02 +00004220/// \brief Attempt default initialization (C++ [dcl.init]p6).
4221static void TryDefaultInitialization(Sema &S,
4222 const InitializedEntity &Entity,
4223 const InitializationKind &Kind,
4224 InitializationSequence &Sequence) {
4225 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
Douglas Gregor85dabae2009-12-16 01:38:02 +00004227 // C++ [dcl.init]p6:
4228 // To default-initialize an object of type T means:
4229 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004230 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4231
Douglas Gregor85dabae2009-12-16 01:38:02 +00004232 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4233 // constructor for T is called (and the initialization is ill-formed if
4234 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004235 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004236 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004237 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004238 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004239
Douglas Gregor85dabae2009-12-16 01:38:02 +00004240 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004241
Douglas Gregor85dabae2009-12-16 01:38:02 +00004242 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004243 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004244 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004245 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004246 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004247 return;
4248 }
4249
4250 // If the destination type has a lifetime property, zero-initialize it.
4251 if (DestType.getQualifiers().hasObjCLifetime()) {
4252 Sequence.AddZeroInitializationStep(Entity.getType());
4253 return;
4254 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004255}
4256
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004257/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4258/// which enumerates all conversion functions and performs overload resolution
4259/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004261 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004262 const InitializationKind &Kind,
4263 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004264 InitializationSequence &Sequence,
4265 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004266 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4267 QualType SourceType = Initializer->getType();
4268 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4269 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Douglas Gregor540c3b02009-12-14 17:27:33 +00004271 // Build the candidate set directly in the initialization sequence
4272 // structure, so that it will persist if we fail.
4273 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4274 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor540c3b02009-12-14 17:27:33 +00004276 // Determine whether we are allowed to call explicit constructors or
4277 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004278 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004279
Douglas Gregor540c3b02009-12-14 17:27:33 +00004280 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4281 // The type we're converting to is a class type. Enumerate its constructors
4282 // to see if there is a suitable conversion.
4283 CXXRecordDecl *DestRecordDecl
4284 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285
Douglas Gregord9848152010-04-26 14:36:57 +00004286 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004288 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004289 // The container holding the constructors can under certain conditions
4290 // be changed while iterating. To be safe we copy the lookup results
4291 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004292 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004293 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004294 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004295 Con != ConEnd; ++Con) {
4296 NamedDecl *D = *Con;
4297 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298
Douglas Gregord9848152010-04-26 14:36:57 +00004299 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004300 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004301 FunctionTemplateDecl *ConstructorTmpl
4302 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004303 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004304 Constructor = cast<CXXConstructorDecl>(
4305 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004306 else
Douglas Gregord9848152010-04-26 14:36:57 +00004307 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregord9848152010-04-26 14:36:57 +00004309 if (!Constructor->isInvalidDecl() &&
4310 Constructor->isConvertingConstructor(AllowExplicit)) {
4311 if (ConstructorTmpl)
4312 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004313 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004314 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004315 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004316 else
4317 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004318 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004319 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321 }
Douglas Gregord9848152010-04-26 14:36:57 +00004322 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004323 }
Eli Friedman78275202009-12-19 08:11:05 +00004324
4325 SourceLocation DeclLoc = Initializer->getLocStart();
4326
Douglas Gregor540c3b02009-12-14 17:27:33 +00004327 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4328 // The type we're converting from is a class type, enumerate its conversion
4329 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004330
Eli Friedman4afe9a32009-12-20 22:12:03 +00004331 // We can only enumerate the conversion functions for a complete type; if
4332 // the type isn't complete, simply skip this step.
4333 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4334 CXXRecordDecl *SourceRecordDecl
4335 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004337 const auto &Conversions =
4338 SourceRecordDecl->getVisibleConversionFunctions();
4339 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004340 NamedDecl *D = *I;
4341 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4342 if (isa<UsingShadowDecl>(D))
4343 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Eli Friedman4afe9a32009-12-20 22:12:03 +00004345 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4346 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004347 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004348 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004349 else
John McCallda4458e2010-03-31 01:36:47 +00004350 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Eli Friedman4afe9a32009-12-20 22:12:03 +00004352 if (AllowExplicit || !Conv->isExplicit()) {
4353 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004354 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004355 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004356 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004357 else
John McCalla0296f72010-03-19 07:35:19 +00004358 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004359 Initializer, DestType, CandidateSet,
4360 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004361 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004362 }
4363 }
4364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
4366 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004367 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004368 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004369 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004370 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004372 Result);
4373 return;
4374 }
John McCall0d1da222010-01-12 00:44:57 +00004375
Douglas Gregor540c3b02009-12-14 17:27:33 +00004376 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004377 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Douglas Gregor540c3b02009-12-14 17:27:33 +00004380 if (isa<CXXConstructorDecl>(Function)) {
4381 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004382 // subsumed by the initialization. Per DR5, the created temporary is of the
4383 // cv-unqualified type of the destination.
4384 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4385 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004386 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004387 return;
4388 }
4389
4390 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004391 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004392 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004393 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004394 // the resulting temporary object (possible to create an object of
4395 // a base class type). That copy is not a separate conversion, so
4396 // we just make a note of the actual destination type (possibly a
4397 // base class of the type returned by the conversion function) and
4398 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004399 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4400 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004401 return;
4402 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004403
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004404 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4405 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406
Douglas Gregor5ab11652010-04-17 22:01:05 +00004407 // If the conversion following the call to the conversion function
4408 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004409 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4410 Best->FinalConversion.Third) {
4411 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004412 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004413 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004414 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004415 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004416}
4417
Richard Smithf032001b2013-06-20 02:18:31 +00004418/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4419/// a function with a pointer return type contains a 'return false;' statement.
4420/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4421/// code using that header.
4422///
4423/// Work around this by treating 'return false;' as zero-initializing the result
4424/// if it's used in a pointer-returning function in a system header.
4425static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4426 const InitializedEntity &Entity,
4427 const Expr *Init) {
4428 return S.getLangOpts().CPlusPlus11 &&
4429 Entity.getKind() == InitializedEntity::EK_Result &&
4430 Entity.getType()->isPointerType() &&
4431 isa<CXXBoolLiteralExpr>(Init) &&
4432 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4433 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4434}
4435
John McCall31168b02011-06-15 23:02:42 +00004436/// The non-zero enum values here are indexes into diagnostic alternatives.
4437enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4438
4439/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004440static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004441 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004442 // Skip parens.
4443 e = e->IgnoreParens();
4444
4445 // Skip address-of nodes.
4446 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4447 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004448 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4449 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004450
4451 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004452 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4453 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004454 case CK_Dependent:
4455 case CK_BitCast:
4456 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004457 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004458 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004459
4460 case CK_ArrayToPointerDecay:
4461 return IIK_nonscalar;
4462
4463 case CK_NullToPointer:
4464 return IIK_okay;
4465
4466 default:
4467 break;
4468 }
4469
4470 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004471 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004472 // set isWeakAccess to true, to mean that there will be an implicit
4473 // load which requires a cleanup.
4474 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4475 isWeakAccess = true;
4476
John McCall63f84442011-06-27 23:59:58 +00004477 if (!isAddressOf) return IIK_nonlocal;
4478
John McCall113bee02012-03-10 09:33:50 +00004479 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4480 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004481
4482 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004483
4484 // If we have a conditional operator, check both sides.
4485 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004486 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4487 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004488 return iik;
4489
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004490 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004491
4492 // These are never scalar.
4493 } else if (isa<ArraySubscriptExpr>(e)) {
4494 return IIK_nonscalar;
4495
4496 // Otherwise, it needs to be a null pointer constant.
4497 } else {
4498 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4499 ? IIK_okay : IIK_nonlocal);
4500 }
4501
4502 return IIK_nonlocal;
4503}
4504
4505/// Check whether the given expression is a valid operand for an
4506/// indirect copy/restore.
4507static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4508 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004509 bool isWeakAccess = false;
4510 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4511 // If isWeakAccess to true, there will be an implicit
4512 // load which requires a cleanup.
4513 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4514 S.ExprNeedsCleanups = true;
4515
John McCall31168b02011-06-15 23:02:42 +00004516 if (iik == IIK_okay) return;
4517
4518 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4519 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4520 << src->getSourceRange();
4521}
4522
Douglas Gregore2f943b2011-02-22 18:29:51 +00004523/// \brief Determine whether we have compatible array types for the
4524/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00004525static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00004526 const ArrayType *Source) {
4527 // If the source and destination array types are equivalent, we're
4528 // done.
4529 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4530 return true;
4531
4532 // Make sure that the element types are the same.
4533 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4534 return false;
4535
4536 // The only mismatch we allow is when the destination is an
4537 // incomplete array type and the source is a constant array type.
4538 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4539}
4540
John McCall31168b02011-06-15 23:02:42 +00004541static bool tryObjCWritebackConversion(Sema &S,
4542 InitializationSequence &Sequence,
4543 const InitializedEntity &Entity,
4544 Expr *Initializer) {
4545 bool ArrayDecay = false;
4546 QualType ArgType = Initializer->getType();
4547 QualType ArgPointee;
4548 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4549 ArrayDecay = true;
4550 ArgPointee = ArgArrayType->getElementType();
4551 ArgType = S.Context.getPointerType(ArgPointee);
4552 }
4553
4554 // Handle write-back conversion.
4555 QualType ConvertedArgType;
4556 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4557 ConvertedArgType))
4558 return false;
4559
4560 // We should copy unless we're passing to an argument explicitly
4561 // marked 'out'.
4562 bool ShouldCopy = true;
4563 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4564 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4565
4566 // Do we need an lvalue conversion?
4567 if (ArrayDecay || Initializer->isGLValue()) {
4568 ImplicitConversionSequence ICS;
4569 ICS.setStandard();
4570 ICS.Standard.setAsIdentityConversion();
4571
4572 QualType ResultType;
4573 if (ArrayDecay) {
4574 ICS.Standard.First = ICK_Array_To_Pointer;
4575 ResultType = S.Context.getPointerType(ArgPointee);
4576 } else {
4577 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4578 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4579 }
4580
4581 Sequence.AddConversionSequenceStep(ICS, ResultType);
4582 }
4583
4584 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4585 return true;
4586}
4587
Guy Benyei61054192013-02-07 10:55:47 +00004588static bool TryOCLSamplerInitialization(Sema &S,
4589 InitializationSequence &Sequence,
4590 QualType DestType,
4591 Expr *Initializer) {
4592 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4593 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4594 return false;
4595
4596 Sequence.AddOCLSamplerInitStep(DestType);
4597 return true;
4598}
4599
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004600//
4601// OpenCL 1.2 spec, s6.12.10
4602//
4603// The event argument can also be used to associate the
4604// async_work_group_copy with a previous async copy allowing
4605// an event to be shared by multiple async copies; otherwise
4606// event should be zero.
4607//
4608static bool TryOCLZeroEventInitialization(Sema &S,
4609 InitializationSequence &Sequence,
4610 QualType DestType,
4611 Expr *Initializer) {
4612 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4613 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4614 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4615 return false;
4616
4617 Sequence.AddOCLZeroEventStep(DestType);
4618 return true;
4619}
4620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004621InitializationSequence::InitializationSequence(Sema &S,
4622 const InitializedEntity &Entity,
4623 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004624 MultiExprArg Args,
4625 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004626 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004627 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4628}
4629
4630void InitializationSequence::InitializeFrom(Sema &S,
4631 const InitializedEntity &Entity,
4632 const InitializationKind &Kind,
4633 MultiExprArg Args,
4634 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004635 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004636
John McCall5e77d762013-04-16 07:28:30 +00004637 // Eliminate non-overload placeholder types in the arguments. We
4638 // need to do this before checking whether types are dependent
4639 // because lowering a pseudo-object expression might well give us
4640 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004641 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004642 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4643 // FIXME: should we be doing this here?
4644 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4645 if (result.isInvalid()) {
4646 SetFailed(FK_PlaceholderType);
4647 return;
4648 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004649 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004650 }
4651
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004652 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653 // The semantics of initializers are as follows. The destination type is
4654 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004655 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004657 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004658 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004659
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004660 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004661 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004662 SequenceKind = DependentSequence;
4663 return;
4664 }
4665
Sebastian Redld201edf2011-06-05 13:59:11 +00004666 // Almost everything is a normal sequence.
4667 setSequenceKind(NormalSequence);
4668
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004669 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004670 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004671 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004672 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004673 if (S.getLangOpts().ObjC1) {
4674 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4675 DestType, Initializer->getType(),
4676 Initializer) ||
4677 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4678 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004679 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004680 if (!isa<InitListExpr>(Initializer))
4681 SourceType = Initializer->getType();
4682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
Sebastian Redl0501c632012-02-12 16:37:36 +00004684 // - If the initializer is a (non-parenthesized) braced-init-list, the
4685 // object is list-initialized (8.5.4).
4686 if (Kind.getKind() != InitializationKind::IK_Direct) {
4687 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4688 TryListInitialization(S, Entity, Kind, InitList, *this);
4689 return;
4690 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004692
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004693 // - If the destination type is a reference type, see 8.5.3.
4694 if (DestType->isReferenceType()) {
4695 // C++0x [dcl.init.ref]p1:
4696 // A variable declared to be a T& or T&&, that is, "reference to type T"
4697 // (8.3.2), shall be initialized by an object, or function, of type T or
4698 // by an object that can be converted into a T.
4699 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004700 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004701 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004702 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004703 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004704 return;
4705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004706
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004707 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004708 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004709 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004710 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004711 return;
4712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
Douglas Gregor85dabae2009-12-16 01:38:02 +00004714 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004715 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004716 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004717 return;
4718 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004719
John McCall66884dd2011-02-21 07:22:22 +00004720 // - If the destination type is an array of characters, an array of
4721 // char16_t, an array of char32_t, or an array of wchar_t, and the
4722 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004724 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004725 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004726 if (Initializer && isa<VariableArrayType>(DestAT)) {
4727 SetFailed(FK_VariableLengthArrayHasInitializer);
4728 return;
4729 }
4730
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004731 if (Initializer) {
4732 switch (IsStringInit(Initializer, DestAT, Context)) {
4733 case SIF_None:
4734 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4735 return;
4736 case SIF_NarrowStringIntoWideChar:
4737 SetFailed(FK_NarrowStringIntoWideCharArray);
4738 return;
4739 case SIF_WideStringIntoChar:
4740 SetFailed(FK_WideStringIntoCharArray);
4741 return;
4742 case SIF_IncompatWideStringIntoWideChar:
4743 SetFailed(FK_IncompatWideStringIntoWideChar);
4744 return;
4745 case SIF_Other:
4746 break;
4747 }
John McCall66884dd2011-02-21 07:22:22 +00004748 }
4749
Douglas Gregore2f943b2011-02-22 18:29:51 +00004750 // Note: as an GNU C extension, we allow initialization of an
4751 // array from a compound literal that creates an array of the same
4752 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004753 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004754 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4755 Initializer->getType()->isArrayType()) {
4756 const ArrayType *SourceAT
4757 = Context.getAsArrayType(Initializer->getType());
4758 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004759 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004760 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004761 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004762 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004763 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004764 }
Richard Smithebeed412012-02-15 22:38:09 +00004765 }
Richard Smithd86812d2012-07-05 08:39:21 +00004766 // Note: as a GNU C++ extension, we allow list-initialization of a
4767 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004768 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004769 Entity.getKind() == InitializedEntity::EK_Member &&
4770 Initializer && isa<InitListExpr>(Initializer)) {
4771 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4772 *this);
4773 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004774 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004775 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004776 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4777 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004778 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004779 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004780
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004781 return;
4782 }
Eli Friedman78275202009-12-19 08:11:05 +00004783
Larisse Voufod2010992015-01-24 23:09:54 +00004784 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00004785 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004786 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004787 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004788
4789 // We're at the end of the line for C: it's either a write-back conversion
4790 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004791 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004792 // If allowed, check whether this is an Objective-C writeback conversion.
4793 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004794 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004795 return;
4796 }
Guy Benyei61054192013-02-07 10:55:47 +00004797
4798 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4799 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004800
4801 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4802 return;
4803
John McCall31168b02011-06-15 23:02:42 +00004804 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004805 AddCAssignmentStep(DestType);
4806 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004807 return;
4808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809
David Blaikiebbafb8a2012-03-11 07:00:24 +00004810 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004811
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004812 // - If the destination type is a (possibly cv-qualified) class type:
4813 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814 // - If the initialization is direct-initialization, or if it is
4815 // copy-initialization where the cv-unqualified version of the
4816 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004817 // class of the destination, constructors are considered. [...]
4818 if (Kind.getKind() == InitializationKind::IK_Direct ||
4819 (Kind.getKind() == InitializationKind::IK_Copy &&
4820 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4821 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004822 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith77be48a2014-07-31 06:31:19 +00004823 DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004825 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004827 // used) to a derived class thereof are enumerated as described in
4828 // 13.3.1.4, and the best one is chosen through overload resolution
4829 // (13.3).
4830 else
Richard Smith77be48a2014-07-31 06:31:19 +00004831 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004832 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004833 return;
4834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004836 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004837 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004838 return;
4839 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004840 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
4842 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004843 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004844 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00004845 // For a conversion to _Atomic(T) from either T or a class type derived
4846 // from T, initialize the T object then convert to _Atomic type.
4847 bool NeedAtomicConversion = false;
4848 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4849 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4850 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4851 DestType = Atomic->getValueType();
4852 NeedAtomicConversion = true;
4853 }
4854 }
4855
4856 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004857 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004858 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00004859 if (!Failed() && NeedAtomicConversion)
4860 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004861 return;
4862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004864 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004865 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004866 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004867 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004868 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00004869
John McCall31168b02011-06-15 23:02:42 +00004870 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00004871 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00004872 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004873 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004874 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004875 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4876 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00004877
4878 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00004879 ICS.Standard.Second == ICK_Writeback_Conversion) {
4880 // Objective-C ARC writeback conversion.
4881
4882 // We should copy unless we're passing to an argument explicitly
4883 // marked 'out'.
4884 bool ShouldCopy = true;
4885 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4886 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4887
4888 // If there was an lvalue adjustment, add it as a separate conversion.
4889 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4890 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4891 ImplicitConversionSequence LvalueICS;
4892 LvalueICS.setStandard();
4893 LvalueICS.Standard.setAsIdentityConversion();
4894 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4895 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004896 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004897 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004898
Richard Smith77be48a2014-07-31 06:31:19 +00004899 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004900 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004901 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004902 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4903 AddZeroInitializationStep(Entity.getType());
4904 } else if (Initializer->getType() == Context.OverloadTy &&
4905 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4906 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004907 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004908 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004909 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004910 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00004911 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004912
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004913 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004914 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004915}
4916
4917InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004918 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004919 StepEnd = Steps.end();
4920 Step != StepEnd; ++Step)
4921 Step->Destroy();
4922}
4923
4924//===----------------------------------------------------------------------===//
4925// Perform initialization
4926//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004928getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004929 switch(Entity.getKind()) {
4930 case InitializedEntity::EK_Variable:
4931 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004932 case InitializedEntity::EK_Exception:
4933 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004934 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004935 return Sema::AA_Initializing;
4936
4937 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004938 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004939 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4940 return Sema::AA_Sending;
4941
Douglas Gregore1314a62009-12-18 05:02:21 +00004942 return Sema::AA_Passing;
4943
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004944 case InitializedEntity::EK_Parameter_CF_Audited:
4945 if (Entity.getDecl() &&
4946 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4947 return Sema::AA_Sending;
4948
4949 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4950
Douglas Gregore1314a62009-12-18 05:02:21 +00004951 case InitializedEntity::EK_Result:
4952 return Sema::AA_Returning;
4953
Douglas Gregore1314a62009-12-18 05:02:21 +00004954 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004955 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004956 // FIXME: Can we tell apart casting vs. converting?
4957 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004958
Douglas Gregore1314a62009-12-18 05:02:21 +00004959 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004960 case InitializedEntity::EK_ArrayElement:
4961 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004962 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004963 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004964 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004965 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004966 return Sema::AA_Initializing;
4967 }
4968
David Blaikie8a40f702012-01-17 06:56:22 +00004969 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004970}
4971
Richard Smith27874d62013-01-08 00:08:23 +00004972/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004973/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004974static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004975 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004976 case InitializedEntity::EK_ArrayElement:
4977 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004978 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004979 case InitializedEntity::EK_New:
4980 case InitializedEntity::EK_Variable:
4981 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004982 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004983 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004984 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004985 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004986 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004987 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004988 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004989 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004990
Douglas Gregore1314a62009-12-18 05:02:21 +00004991 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004992 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004993 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004994 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004995 return true;
4996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997
Douglas Gregore1314a62009-12-18 05:02:21 +00004998 llvm_unreachable("missed an InitializedEntity kind?");
4999}
5000
Douglas Gregor95562572010-04-24 23:45:46 +00005001/// \brief Whether the given entity, when initialized with an object
5002/// created for that initialization, requires destruction.
5003static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
5004 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005005 case InitializedEntity::EK_Result:
5006 case InitializedEntity::EK_New:
5007 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005008 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005009 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005010 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005011 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005012 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005013 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014
Richard Smith27874d62013-01-08 00:08:23 +00005015 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00005016 case InitializedEntity::EK_Variable:
5017 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005018 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005019 case InitializedEntity::EK_Temporary:
5020 case InitializedEntity::EK_ArrayElement:
5021 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005022 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005023 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005024 return true;
5025 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026
5027 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005028}
5029
Richard Smithc620f552011-10-19 16:55:56 +00005030/// \brief Look for copy and move constructors and constructor templates, for
5031/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
5032static void LookupCopyAndMoveConstructors(Sema &S,
5033 OverloadCandidateSet &CandidateSet,
5034 CXXRecordDecl *Class,
5035 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00005036 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005037 // The container holding the constructors can under certain conditions
5038 // be changed while iterating (e.g. because of deserialization).
5039 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00005040 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00005041 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005042 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
5043 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00005044 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00005045
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005046 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00005047 // Handle copy/moveconstructors, only.
5048 if (!Constructor || Constructor->isInvalidDecl() ||
5049 !Constructor->isCopyOrMoveConstructor() ||
5050 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5051 continue;
5052
5053 DeclAccessPair FoundDecl
5054 = DeclAccessPair::make(Constructor, Constructor->getAccess());
5055 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005056 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00005057 continue;
5058 }
5059
5060 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005061 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00005062 if (ConstructorTmpl->isInvalidDecl())
5063 continue;
5064
5065 Constructor = cast<CXXConstructorDecl>(
5066 ConstructorTmpl->getTemplatedDecl());
5067 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5068 continue;
5069
5070 // FIXME: Do we need to limit this to copy-constructor-like
5071 // candidates?
5072 DeclAccessPair FoundDecl
5073 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00005074 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005075 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00005076 }
5077}
5078
5079/// \brief Get the location at which initialization diagnostics should appear.
5080static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5081 Expr *Initializer) {
5082 switch (Entity.getKind()) {
5083 case InitializedEntity::EK_Result:
5084 return Entity.getReturnLoc();
5085
5086 case InitializedEntity::EK_Exception:
5087 return Entity.getThrowLoc();
5088
5089 case InitializedEntity::EK_Variable:
5090 return Entity.getDecl()->getLocation();
5091
Douglas Gregor19666fb2012-02-15 16:57:26 +00005092 case InitializedEntity::EK_LambdaCapture:
5093 return Entity.getCaptureLoc();
5094
Richard Smithc620f552011-10-19 16:55:56 +00005095 case InitializedEntity::EK_ArrayElement:
5096 case InitializedEntity::EK_Member:
5097 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005098 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005099 case InitializedEntity::EK_Temporary:
5100 case InitializedEntity::EK_New:
5101 case InitializedEntity::EK_Base:
5102 case InitializedEntity::EK_Delegating:
5103 case InitializedEntity::EK_VectorElement:
5104 case InitializedEntity::EK_ComplexElement:
5105 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005106 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005107 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005108 return Initializer->getLocStart();
5109 }
5110 llvm_unreachable("missed an InitializedEntity kind?");
5111}
5112
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005113/// \brief Make a (potentially elidable) temporary copy of the object
5114/// provided by the given initializer by calling the appropriate copy
5115/// constructor.
5116///
5117/// \param S The Sema object used for type-checking.
5118///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005119/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005120/// the type of the initializer expression or a superclass thereof.
5121///
James Dennett634962f2012-06-14 21:40:34 +00005122/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005123///
5124/// \param CurInit The initializer expression.
5125///
5126/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5127/// is permitted in C++03 (but not C++0x) when binding a reference to
5128/// an rvalue.
5129///
5130/// \returns An expression that copies the initializer expression into
5131/// a temporary object, or an error expression if a copy could not be
5132/// created.
John McCalldadc5752010-08-24 06:29:42 +00005133static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005134 QualType T,
5135 const InitializedEntity &Entity,
5136 ExprResult CurInit,
5137 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005138 if (CurInit.isInvalid())
5139 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005140 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005141 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005142 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005143 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005144 Class = cast<CXXRecordDecl>(Record->getDecl());
5145 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005146 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005147
Douglas Gregor5d369002011-01-21 18:05:27 +00005148 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005149 // When certain criteria are met, an implementation is allowed to
5150 // omit the copy/move construction of a class object, even if the
5151 // copy/move constructor and/or destructor for the object have
5152 // side effects. [...]
5153 // - when a temporary class object that has not been bound to a
5154 // reference (12.2) would be copied/moved to a class object
5155 // with the same cv-unqualified type, the copy/move operation
5156 // can be omitted by constructing the temporary object
5157 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005158 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005159 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005160 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005161 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005162 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005163 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005164 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005165
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005166 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005167 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005168 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005169
Douglas Gregorf282a762011-01-21 19:38:21 +00005170 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005171 // Only consider constructors and constructor templates. Per
5172 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5173 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005174 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005175 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005176
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005177 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5178
Douglas Gregore1314a62009-12-18 05:02:21 +00005179 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005180 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005181 case OR_Success:
5182 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005183
Douglas Gregore1314a62009-12-18 05:02:21 +00005184 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005185 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5186 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5187 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005188 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005189 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005190 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005191 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005192 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005193 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005194
Douglas Gregore1314a62009-12-18 05:02:21 +00005195 case OR_Ambiguous:
5196 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005197 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005198 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005199 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005200 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005201
Douglas Gregore1314a62009-12-18 05:02:21 +00005202 case OR_Deleted:
5203 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005204 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005205 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005206 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005207 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005208 }
5209
Douglas Gregor5ab11652010-04-17 22:01:05 +00005210 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005211 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005212 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005213
Anders Carlssona01874b2010-04-21 18:47:17 +00005214 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005215 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005216
5217 if (IsExtraneousCopy) {
5218 // If this is a totally extraneous copy for C++03 reference
5219 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005220 // expression. We don't generate an (elided) copy operation here
5221 // because doing so would require us to pass down a flag to avoid
5222 // infinite recursion, where each step adds another extraneous,
5223 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005224
Douglas Gregor30b52772010-04-18 07:57:34 +00005225 // Instantiate the default arguments of any extra parameters in
5226 // the selected copy constructor, as if we were going to create a
5227 // proper call to the copy constructor.
5228 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5229 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5230 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005231 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005232 break;
5233
5234 // Build the default argument expression; we don't actually care
5235 // if this succeeds or not, because this routine will complain
5236 // if there was a problem.
5237 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5238 }
5239
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005240 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005242
Douglas Gregor5ab11652010-04-17 22:01:05 +00005243 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005244 // constructor call (we might have derived-to-base conversions, or
5245 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005246 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005247 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005248
Douglas Gregord0ace022010-04-25 00:55:24 +00005249 // Actually perform the constructor call.
5250 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005251 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005252 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005253 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005254 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005255 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005256 CXXConstructExpr::CK_Complete,
5257 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005258
Douglas Gregord0ace022010-04-25 00:55:24 +00005259 // If we're supposed to bind temporaries, do so.
5260 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005261 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005262 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005263}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005264
Richard Smithc620f552011-10-19 16:55:56 +00005265/// \brief Check whether elidable copy construction for binding a reference to
5266/// a temporary would have succeeded if we were building in C++98 mode, for
5267/// -Wc++98-compat.
5268static void CheckCXX98CompatAccessibleCopy(Sema &S,
5269 const InitializedEntity &Entity,
5270 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005271 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005272
5273 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5274 if (!Record)
5275 return;
5276
5277 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005278 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005279 return;
5280
5281 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005282 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005283 LookupCopyAndMoveConstructors(
5284 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5285
5286 // Perform overload resolution.
5287 OverloadCandidateSet::iterator Best;
5288 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5289
5290 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5291 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5292 << CurInitExpr->getSourceRange();
5293
5294 switch (OR) {
5295 case OR_Success:
5296 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005297 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005298 // FIXME: Check default arguments as far as that's possible.
5299 break;
5300
5301 case OR_No_Viable_Function:
5302 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005303 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005304 break;
5305
5306 case OR_Ambiguous:
5307 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005308 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005309 break;
5310
5311 case OR_Deleted:
5312 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005313 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005314 break;
5315 }
5316}
5317
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005318void InitializationSequence::PrintInitLocationNote(Sema &S,
5319 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005320 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005321 if (Entity.getDecl()->getLocation().isInvalid())
5322 return;
5323
5324 if (Entity.getDecl()->getDeclName())
5325 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5326 << Entity.getDecl()->getDeclName();
5327 else
5328 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5329 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005330 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5331 Entity.getMethodDecl())
5332 S.Diag(Entity.getMethodDecl()->getLocation(),
5333 diag::note_method_return_type_change)
5334 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005335}
5336
Sebastian Redl112aa822011-07-14 19:07:55 +00005337static bool isReferenceBinding(const InitializationSequence::Step &s) {
5338 return s.Kind == InitializationSequence::SK_BindReference ||
5339 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5340}
5341
Jordan Rose6c0505e2013-05-06 16:48:12 +00005342/// Returns true if the parameters describe a constructor initialization of
5343/// an explicit temporary object, e.g. "Point(x, y)".
5344static bool isExplicitTemporary(const InitializedEntity &Entity,
5345 const InitializationKind &Kind,
5346 unsigned NumArgs) {
5347 switch (Entity.getKind()) {
5348 case InitializedEntity::EK_Temporary:
5349 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005350 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005351 break;
5352 default:
5353 return false;
5354 }
5355
5356 switch (Kind.getKind()) {
5357 case InitializationKind::IK_DirectList:
5358 return true;
5359 // FIXME: Hack to work around cast weirdness.
5360 case InitializationKind::IK_Direct:
5361 case InitializationKind::IK_Value:
5362 return NumArgs != 1;
5363 default:
5364 return false;
5365 }
5366}
5367
Sebastian Redled2e5322011-12-22 14:44:04 +00005368static ExprResult
5369PerformConstructorInitialization(Sema &S,
5370 const InitializedEntity &Entity,
5371 const InitializationKind &Kind,
5372 MultiExprArg Args,
5373 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005374 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005375 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005376 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005377 SourceLocation LBraceLoc,
5378 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005379 unsigned NumArgs = Args.size();
5380 CXXConstructorDecl *Constructor
5381 = cast<CXXConstructorDecl>(Step.Function.Function);
5382 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5383
5384 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005385 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005386 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5387 ? Kind.getEqualLoc()
5388 : Kind.getLocation();
5389
5390 if (Kind.getKind() == InitializationKind::IK_Default) {
5391 // Force even a trivial, implicit default constructor to be
5392 // semantically checked. We do this explicitly because we don't build
5393 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005394 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005395 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005396 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005397 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5398 }
5399
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005400 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005401
Douglas Gregor6073dca2012-02-24 23:56:31 +00005402 // C++ [over.match.copy]p1:
5403 // - When initializing a temporary to be bound to the first parameter
5404 // of a constructor that takes a reference to possibly cv-qualified
5405 // T as its first argument, called with a single argument in the
5406 // context of direct-initialization, explicit conversion functions
5407 // are also considered.
5408 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5409 Args.size() == 1 &&
5410 Constructor->isCopyOrMoveConstructor();
5411
Sebastian Redled2e5322011-12-22 14:44:04 +00005412 // Determine the arguments required to actually perform the constructor
5413 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005414 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005415 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005416 AllowExplicitConv,
5417 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005418 return ExprError();
5419
5420
Jordan Rose6c0505e2013-05-06 16:48:12 +00005421 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005422 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005423 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005424 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5425 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005426
5427 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5428 if (!TSInfo)
5429 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005430 SourceRange ParenOrBraceRange =
5431 (Kind.getKind() == InitializationKind::IK_DirectList)
5432 ? SourceRange(LBraceLoc, RBraceLoc)
5433 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005434
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005435 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5436 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5437 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005438 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005439 } else {
5440 CXXConstructExpr::ConstructionKind ConstructKind =
5441 CXXConstructExpr::CK_Complete;
5442
5443 if (Entity.getKind() == InitializedEntity::EK_Base) {
5444 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5445 CXXConstructExpr::CK_VirtualBase :
5446 CXXConstructExpr::CK_NonVirtualBase;
5447 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5448 ConstructKind = CXXConstructExpr::CK_Delegating;
5449 }
5450
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005451 // Only get the parenthesis or brace range if it is a list initialization or
5452 // direct construction.
5453 SourceRange ParenOrBraceRange;
5454 if (IsListInitialization)
5455 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5456 else if (Kind.getKind() == InitializationKind::IK_Direct)
5457 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005458
5459 // If the entity allows NRVO, mark the construction as elidable
5460 // unconditionally.
5461 if (Entity.allowsNRVO())
5462 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5463 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005464 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005465 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005466 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005467 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005468 ConstructorInitRequiresZeroInit,
5469 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005470 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005471 else
5472 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5473 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005474 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005475 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005476 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005477 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005478 ConstructorInitRequiresZeroInit,
5479 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005480 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005481 }
5482 if (CurInit.isInvalid())
5483 return ExprError();
5484
5485 // Only check access if all of that succeeded.
5486 S.CheckConstructorAccess(Loc, Constructor, Entity,
5487 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005488 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5489 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005490
5491 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005492 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005493
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005494 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005495}
5496
Richard Smitheb3cad52012-06-04 22:27:30 +00005497/// Determine whether the specified InitializedEntity definitely has a lifetime
5498/// longer than the current full-expression. Conservatively returns false if
5499/// it's unclear.
5500static bool
5501InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5502 const InitializedEntity *Top = &Entity;
5503 while (Top->getParent())
5504 Top = Top->getParent();
5505
5506 switch (Top->getKind()) {
5507 case InitializedEntity::EK_Variable:
5508 case InitializedEntity::EK_Result:
5509 case InitializedEntity::EK_Exception:
5510 case InitializedEntity::EK_Member:
5511 case InitializedEntity::EK_New:
5512 case InitializedEntity::EK_Base:
5513 case InitializedEntity::EK_Delegating:
5514 return true;
5515
5516 case InitializedEntity::EK_ArrayElement:
5517 case InitializedEntity::EK_VectorElement:
5518 case InitializedEntity::EK_BlockElement:
5519 case InitializedEntity::EK_ComplexElement:
5520 // Could not determine what the full initialization is. Assume it might not
5521 // outlive the full-expression.
5522 return false;
5523
5524 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005525 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005526 case InitializedEntity::EK_Temporary:
5527 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005528 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005529 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005530 // The entity being initialized might not outlive the full-expression.
5531 return false;
5532 }
5533
5534 llvm_unreachable("unknown entity kind");
5535}
5536
Richard Smithe6c01442013-06-05 00:46:14 +00005537/// Determine the declaration which an initialized entity ultimately refers to,
5538/// for the purpose of lifetime-extending a temporary bound to a reference in
5539/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005540static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5541 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005542 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005543 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005544 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005545 case InitializedEntity::EK_Variable:
5546 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005547 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005548
5549 case InitializedEntity::EK_Member:
5550 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005551 if (Entity->getParent())
5552 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5553 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005554
5555 // except:
5556 // -- A temporary bound to a reference member in a constructor's
5557 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005558 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005559
5560 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005561 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005562 // -- A temporary bound to a reference parameter in a function call
5563 // persists until the completion of the full-expression containing
5564 // the call.
5565 case InitializedEntity::EK_Result:
5566 // -- The lifetime of a temporary bound to the returned value in a
5567 // function return statement is not extended; the temporary is
5568 // destroyed at the end of the full-expression in the return statement.
5569 case InitializedEntity::EK_New:
5570 // -- A temporary bound to a reference in a new-initializer persists
5571 // until the completion of the full-expression containing the
5572 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005573 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005574
5575 case InitializedEntity::EK_Temporary:
5576 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005577 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005578 // We don't yet know the storage duration of the surrounding temporary.
5579 // Assume it's got full-expression duration for now, it will patch up our
5580 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005581 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005582
5583 case InitializedEntity::EK_ArrayElement:
5584 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005585 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5586 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005587
5588 case InitializedEntity::EK_Base:
5589 case InitializedEntity::EK_Delegating:
5590 // We can reach this case for aggregate initialization in a constructor:
5591 // struct A { int &&r; };
5592 // struct B : A { B() : A{0} {} };
5593 // In this case, use the innermost field decl as the context.
5594 return FallbackDecl;
5595
5596 case InitializedEntity::EK_BlockElement:
5597 case InitializedEntity::EK_LambdaCapture:
5598 case InitializedEntity::EK_Exception:
5599 case InitializedEntity::EK_VectorElement:
5600 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005601 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005602 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005603 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005604}
5605
David Majnemerdaff3702014-05-01 17:50:17 +00005606static void performLifetimeExtension(Expr *Init,
5607 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005608
5609/// Update a glvalue expression that is used as the initializer of a reference
5610/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005611/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005612static bool
5613performReferenceExtension(Expr *Init,
5614 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005615 // Walk past any constructs which we can lifetime-extend across.
5616 Expr *Old;
5617 do {
5618 Old = Init;
5619
Richard Smithdbc82492015-01-10 01:28:13 +00005620 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5621 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5622 // This is just redundant braces around an initializer. Step over it.
5623 Init = ILE->getInit(0);
5624 }
5625 }
5626
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005627 // Step over any subobject adjustments; we may have a materialized
5628 // temporary inside them.
5629 SmallVector<const Expr *, 2> CommaLHSs;
5630 SmallVector<SubobjectAdjustment, 2> Adjustments;
5631 Init = const_cast<Expr *>(
5632 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5633
5634 // Per current approach for DR1376, look through casts to reference type
5635 // when performing lifetime extension.
5636 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5637 if (CE->getSubExpr()->isGLValue())
5638 Init = CE->getSubExpr();
5639
5640 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5641 // It's unclear if binding a reference to that xvalue extends the array
5642 // temporary.
5643 } while (Init != Old);
5644
Richard Smithe6c01442013-06-05 00:46:14 +00005645 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5646 // Update the storage duration of the materialized temporary.
5647 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005648 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5649 ExtendingEntity->allocateManglingNumber());
5650 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005651 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005652 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005653
5654 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005655}
5656
5657/// Update a prvalue expression that is going to be materialized as a
5658/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005659static void performLifetimeExtension(Expr *Init,
5660 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005661 // Dig out the expression which constructs the extended temporary.
5662 SmallVector<const Expr *, 2> CommaLHSs;
5663 SmallVector<SubobjectAdjustment, 2> Adjustments;
5664 Init = const_cast<Expr *>(
5665 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5666
Richard Smith736a9472013-06-12 20:42:33 +00005667 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5668 Init = BTE->getSubExpr();
5669
Richard Smithcc1b96d2013-06-12 22:31:48 +00005670 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005671 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005672 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005673 return;
5674 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005675
Richard Smithe6c01442013-06-05 00:46:14 +00005676 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005677 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005678 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005679 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005680 return;
5681 }
5682
Richard Smithcc1b96d2013-06-12 22:31:48 +00005683 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005684 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5685
5686 // If we lifetime-extend a braced initializer which is initializing an
5687 // aggregate, and that aggregate contains reference members which are
5688 // bound to temporaries, those temporaries are also lifetime-extended.
5689 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5690 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005691 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005692 else {
5693 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005694 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005695 if (Index >= ILE->getNumInits())
5696 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005697 if (I->isUnnamedBitfield())
5698 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005699 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005700 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005701 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005702 else if (isa<InitListExpr>(SubInit) ||
5703 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005704 // This may be either aggregate-initialization of a member or
5705 // initialization of a std::initializer_list object. Either way,
5706 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005707 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005708 ++Index;
5709 }
5710 }
5711 }
5712 }
5713}
5714
Richard Smithcc1b96d2013-06-12 22:31:48 +00005715static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5716 const Expr *Init, bool IsInitializerList,
5717 const ValueDecl *ExtendingDecl) {
5718 // Warn if a field lifetime-extends a temporary.
5719 if (isa<FieldDecl>(ExtendingDecl)) {
5720 if (IsInitializerList) {
5721 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5722 << /*at end of constructor*/true;
5723 return;
5724 }
5725
5726 bool IsSubobjectMember = false;
5727 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5728 Ent = Ent->getParent()) {
5729 if (Ent->getKind() != InitializedEntity::EK_Base) {
5730 IsSubobjectMember = true;
5731 break;
5732 }
5733 }
5734 S.Diag(Init->getExprLoc(),
5735 diag::warn_bind_ref_member_to_temporary)
5736 << ExtendingDecl << Init->getSourceRange()
5737 << IsSubobjectMember << IsInitializerList;
5738 if (IsSubobjectMember)
5739 S.Diag(ExtendingDecl->getLocation(),
5740 diag::note_ref_subobject_of_member_declared_here);
5741 else
5742 S.Diag(ExtendingDecl->getLocation(),
5743 diag::note_ref_or_ptr_member_declared_here)
5744 << /*is pointer*/false;
5745 }
5746}
5747
Richard Smithaaa0ec42013-09-21 21:19:19 +00005748static void DiagnoseNarrowingInInitList(Sema &S,
5749 const ImplicitConversionSequence &ICS,
5750 QualType PreNarrowingType,
5751 QualType EntityType,
5752 const Expr *PostInit);
5753
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005754ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005755InitializationSequence::Perform(Sema &S,
5756 const InitializedEntity &Entity,
5757 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005758 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005759 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005760 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005761 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005762 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764
Sebastian Redld201edf2011-06-05 13:59:11 +00005765 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005766 // If the declaration is a non-dependent, incomplete array type
5767 // that has an initializer, then its type will be completed once
5768 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005769 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005770 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005771 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005772 if (const IncompleteArrayType *ArrayT
5773 = S.Context.getAsIncompleteArrayType(DeclType)) {
5774 // FIXME: We don't currently have the ability to accurately
5775 // compute the length of an initializer list without
5776 // performing full type-checking of the initializer list
5777 // (since we have to determine where braces are implicitly
5778 // introduced and such). So, we fall back to making the array
5779 // type a dependently-sized array type with no specified
5780 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005781 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005782 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005783
Douglas Gregor51e77d52009-12-10 17:56:55 +00005784 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005785 if (DeclaratorDecl *DD = Entity.getDecl()) {
5786 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5787 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005788 if (IncompleteArrayTypeLoc ArrayLoc =
5789 TL.getAs<IncompleteArrayTypeLoc>())
5790 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005791 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005792 }
5793
5794 *ResultType
5795 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005796 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005797 ArrayT->getSizeModifier(),
5798 ArrayT->getIndexTypeCVRQualifiers(),
5799 Brackets);
5800 }
5801
5802 }
5803 }
Sebastian Redla9351792012-02-11 23:51:47 +00005804 if (Kind.getKind() == InitializationKind::IK_Direct &&
5805 !Kind.isExplicitCast()) {
5806 // Rebuild the ParenListExpr.
5807 SourceRange ParenRange = Kind.getParenRange();
5808 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005809 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005810 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005811 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005812 Kind.isExplicitCast() ||
5813 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005814 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005815 }
5816
Sebastian Redld201edf2011-06-05 13:59:11 +00005817 // No steps means no initialization.
5818 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005819 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005820
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005821 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005822 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005823 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005824 // Produce a C++98 compatibility warning if we are initializing a reference
5825 // from an initializer list. For parameters, we produce a better warning
5826 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005827 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005828 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5829 << Init->getSourceRange();
5830 }
5831
Richard Smitheb3cad52012-06-04 22:27:30 +00005832 // Diagnose cases where we initialize a pointer to an array temporary, and the
5833 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005834 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005835 Entity.getType()->isPointerType() &&
5836 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005837 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005838 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5839 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5840 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5841 << Init->getSourceRange();
5842 }
5843
Douglas Gregor1b303932009-12-22 15:35:07 +00005844 QualType DestType = Entity.getType().getNonReferenceType();
5845 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005846 // the same as Entity.getDecl()->getType() in cases involving type merging,
5847 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005848 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005849 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005850 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005851
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005852 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005853
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005854 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005855 // grab the only argument out the Args and place it into the "current"
5856 // initializer.
5857 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005858 case SK_ResolveAddressOfOverloadedFunction:
5859 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005860 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005861 case SK_CastDerivedToBaseLValue:
5862 case SK_BindReference:
5863 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005864 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005865 case SK_UserConversion:
5866 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005867 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005868 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00005869 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00005870 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005871 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005872 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005873 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005874 case SK_UnwrapInitList:
5875 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005876 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005877 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005878 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005879 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005880 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005881 case SK_PassByIndirectCopyRestore:
5882 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005883 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005884 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005885 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005886 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005887 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005888 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005889 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005890 break;
John McCall34376a62010-12-04 03:47:34 +00005891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005892
Douglas Gregore1314a62009-12-18 05:02:21 +00005893 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00005894 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00005895 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005896 case SK_ZeroInitialization:
5897 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005899
5900 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005901 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005902 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005903 for (step_iterator Step = step_begin(), StepEnd = step_end();
5904 Step != StepEnd; ++Step) {
5905 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005906 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005907
John Wiegley01296292011-04-08 18:41:53 +00005908 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005909
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005910 switch (Step->Kind) {
5911 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005913 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005914 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005915 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5916 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005917 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005918 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005919 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005920 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005922 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005923 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005924 case SK_CastDerivedToBaseLValue: {
5925 // We have a derived-to-base cast that produces either an rvalue or an
5926 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005927
John McCallcf142162010-08-07 06:22:56 +00005928 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005929
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005930 // Casts to inaccessible base classes are allowed with C-style casts.
5931 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5932 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005933 CurInit.get()->getLocStart(),
5934 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005935 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005936 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005937
John McCall2536c6d2010-08-25 10:28:54 +00005938 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005939 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005940 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005941 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005942 VK_XValue :
5943 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005944 CurInit =
5945 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5946 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005947 break;
5948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005949
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005950 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005951 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5952 if (CurInit.get()->refersToBitField()) {
5953 // We don't necessarily have an unambiguous source bit-field.
5954 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005955 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005956 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005957 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005958 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005959 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005960 if (BitField)
5961 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5962
John McCallfaf5fb42010-08-26 23:41:50 +00005963 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005964 }
Anders Carlssona91be642010-01-29 02:47:33 +00005965
John Wiegley01296292011-04-08 18:41:53 +00005966 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005967 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005968 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5969 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005970 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005971 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005972 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005974
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005975 // Reference binding does not have any corresponding ASTs.
5976
5977 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005978 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005979 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005980
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005981 // Even though we didn't materialize a temporary, the binding may still
5982 // extend the lifetime of a temporary. This happens if we bind a reference
5983 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005984 if (const InitializedEntity *ExtendingEntity =
5985 getEntityForTemporaryLifetimeExtension(&Entity))
5986 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5987 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5988 /*IsInitializerList=*/false,
5989 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005990
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005991 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005992
Richard Smithe6c01442013-06-05 00:46:14 +00005993 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005994 // Make sure the "temporary" is actually an rvalue.
5995 assert(CurInit.get()->isRValue() && "not a temporary");
5996
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005997 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005998 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005999 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006000
Douglas Gregorfe314812011-06-21 17:03:29 +00006001 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00006002 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00006003 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006004 Entity.getType()->isLValueReferenceType());
6005
6006 // Maybe lifetime-extend the temporary's subobjects to match the
6007 // entity's lifetime.
6008 if (const InitializedEntity *ExtendingEntity =
6009 getEntityForTemporaryLifetimeExtension(&Entity))
6010 if (performReferenceExtension(MTE, ExtendingEntity))
6011 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
6012 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006013
6014 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00006015 // need cleanups. Likewise if we're extending this temporary to automatic
6016 // storage duration -- we need to register its cleanup during the
6017 // full-expression's cleanups.
6018 if ((S.getLangOpts().ObjCAutoRefCount &&
6019 MTE->getType()->isObjCLifetimeType()) ||
6020 (MTE->getStorageDuration() == SD_Automatic &&
6021 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00006022 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00006023
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006024 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006025 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006027
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006028 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006029 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006030 /*IsExtraneousCopy=*/true);
6031 break;
6032
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006033 case SK_UserConversion: {
6034 // We have a user-defined conversion that invokes either a constructor
6035 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006036 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00006037 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00006038 FunctionDecl *Fn = Step->Function.Function;
6039 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006040 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006041 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006042 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006043 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006044 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006045 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006046 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00006047
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006048 // Determine the arguments required to actually perform the constructor
6049 // call.
John Wiegley01296292011-04-08 18:41:53 +00006050 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006051 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006052 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006053 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006054 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006055
Richard Smithb24f0672012-02-11 19:22:50 +00006056 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006057 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006058 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006059 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006060 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006061 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006062 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006063 CXXConstructExpr::CK_Complete,
6064 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006065 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006066 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006067
Anders Carlssona01874b2010-04-21 18:47:17 +00006068 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00006069 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00006070 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6071 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006072
John McCalle3027922010-08-25 11:45:40 +00006073 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00006074 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6075 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6076 S.IsDerivedFrom(SourceType, Class))
6077 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006078
Douglas Gregor95562572010-04-24 23:45:46 +00006079 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006080 } else {
6081 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006082 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006083 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006084 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006085 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6086 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006087
6088 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006089 // derived-to-base conversion? I believe the answer is "no", because
6090 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006091 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006092 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006093 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006094 FoundFn, Conversion);
6095 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006096 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006097 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006098
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006099 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006100 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6101 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006102 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006103 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006104
John McCalle3027922010-08-25 11:45:40 +00006105 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006106
Alp Toker314cc812014-01-25 16:55:45 +00006107 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006109
Sebastian Redl112aa822011-07-14 19:07:55 +00006110 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006111 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6112
6113 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006114 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006115 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006116 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006117 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006118 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006119 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006120 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006121 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6122 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006123 }
6124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006125
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006126 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6127 CastKind, CurInit.get(), nullptr,
6128 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006129 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006130 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006131 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006132 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006133 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006134 break;
6135 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006136
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006137 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006138 case SK_QualificationConversionXValue:
6139 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006140 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006141 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006142 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006143 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006144 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006145 VK_XValue :
6146 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006147 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006148 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006149 }
6150
Richard Smith77be48a2014-07-31 06:31:19 +00006151 case SK_AtomicConversion: {
6152 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6153 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6154 CK_NonAtomicToAtomic, VK_RValue);
6155 break;
6156 }
6157
Jordan Roseb1312a52013-04-11 00:58:58 +00006158 case SK_LValueToRValue: {
6159 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006160 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6161 CK_LValueToRValue, CurInit.get(),
6162 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006163 break;
6164 }
6165
Richard Smithaaa0ec42013-09-21 21:19:19 +00006166 case SK_ConversionSequence:
6167 case SK_ConversionSequenceNoNarrowing: {
6168 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006169 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6170 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006171 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006172 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006173 ExprResult CurInitExprRes =
6174 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006175 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006176 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006177 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006178 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006179
6180 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6181 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6182 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6183 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006184 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006186
Douglas Gregor51e77d52009-12-10 17:56:55 +00006187 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006188 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006189 // If we're not initializing the top-level entity, we need to create an
6190 // InitializeTemporary entity for our target type.
6191 QualType Ty = Step->Type;
6192 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006193 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006194 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6195 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006196 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006197 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006198 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006199
Richard Smithcc1b96d2013-06-12 22:31:48 +00006200 // Hack: We must update *ResultType if available in order to set the
6201 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6202 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6203 if (ResultType &&
6204 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006205 if ((*ResultType)->isRValueReferenceType())
6206 Ty = S.Context.getRValueReferenceType(Ty);
6207 else if ((*ResultType)->isLValueReferenceType())
6208 Ty = S.Context.getLValueReferenceType(Ty,
6209 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6210 *ResultType = Ty;
6211 }
6212
6213 InitListExpr *StructuredInitList =
6214 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006215 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006216 CurInit = shouldBindAsTemporary(InitEntity)
6217 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006218 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006219 break;
6220 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006221
Richard Smith53324112014-07-16 21:33:43 +00006222 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006223 // When an initializer list is passed for a parameter of type "reference
6224 // to object", we don't get an EK_Temporary entity, but instead an
6225 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006226 // FIXME: This is a hack. What we really should do is create a user
6227 // conversion step for this case, but this makes it considerably more
6228 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006229 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6230 Entity.getType().getNonReferenceType());
6231 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006232 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006233 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006234 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6235 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006236 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006237 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6238 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006239 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006240 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006241 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006242 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006243 InitList->getLBraceLoc(),
6244 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006245 break;
6246 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006247
Sebastian Redl29526f02011-11-27 16:50:07 +00006248 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006249 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006250 break;
6251
6252 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006253 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006254 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6255 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006256 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006257 ILE->setSyntacticForm(Syntactic);
6258 ILE->setType(E->getType());
6259 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006260 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006261 break;
6262 }
6263
Richard Smith53324112014-07-16 21:33:43 +00006264 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006265 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006266 // When an initializer list is passed for a parameter of type "reference
6267 // to object", we don't get an EK_Temporary entity, but instead an
6268 // EK_Parameter entity with reference type.
6269 // FIXME: This is a hack. What we really should do is create a user
6270 // conversion step for this case, but this makes it considerably more
6271 // complicated. For now, this will do.
6272 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6273 Entity.getType().getNonReferenceType());
6274 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006275 bool IsStdInitListInit =
6276 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006277 CurInit = PerformConstructorInitialization(
6278 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6279 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006280 /*IsListInitialization*/IsStdInitListInit,
6281 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006282 /*LBraceLoc*/SourceLocation(),
6283 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006284 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006286
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006287 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006288 step_iterator NextStep = Step;
6289 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006290 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006291 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006292 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006293 // The need for zero-initialization is recorded directly into
6294 // the call to the object's constructor within the next step.
6295 ConstructorInitRequiresZeroInit = true;
6296 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006297 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006298 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006299 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6300 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006301 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006302 Kind.getRange().getBegin());
6303
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006304 CurInit = new (S.Context) CXXScalarValueInitExpr(
6305 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6306 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006307 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006308 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006309 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006310 break;
6311 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006312
6313 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006314 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006315 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006316 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006317 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6318 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006319 if (Result.isInvalid())
6320 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006321 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006322
6323 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006324 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006325 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006326 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006327 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006328 == Sema::Compatible)
6329 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006330 if (CurInitExprRes.isInvalid())
6331 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006332 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006333
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006334 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006335 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6336 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006337 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006338 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006339 &Complained)) {
6340 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006341 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006342 } else if (Complained)
6343 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006344 break;
6345 }
Eli Friedman78275202009-12-19 08:11:05 +00006346
6347 case SK_StringInit: {
6348 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006349 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006350 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006351 break;
6352 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006353
6354 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006355 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006356 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006357 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006358 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006359
6360 case SK_ArrayInit:
6361 // Okay: we checked everything before creating this step. Note that
6362 // this is a GNU extension.
6363 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006364 << Step->Type << CurInit.get()->getType()
6365 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006366
6367 // If the destination type is an incomplete array type, update the
6368 // type accordingly.
6369 if (ResultType) {
6370 if (const IncompleteArrayType *IncompleteDest
6371 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6372 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006373 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006374 *ResultType = S.Context.getConstantArrayType(
6375 IncompleteDest->getElementType(),
6376 ConstantSource->getSize(),
6377 ArrayType::Normal, 0);
6378 }
6379 }
6380 }
John McCall31168b02011-06-15 23:02:42 +00006381 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006382
Richard Smithebeed412012-02-15 22:38:09 +00006383 case SK_ParenthesizedArrayInit:
6384 // Okay: we checked everything before creating this step. Note that
6385 // this is a GNU extension.
6386 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6387 << CurInit.get()->getSourceRange();
6388 break;
6389
John McCall31168b02011-06-15 23:02:42 +00006390 case SK_PassByIndirectCopyRestore:
6391 case SK_PassByIndirectRestore:
6392 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006393 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6394 CurInit.get(), Step->Type,
6395 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006396 break;
6397
6398 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006399 CurInit =
6400 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6401 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006402 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006403
6404 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006405 S.Diag(CurInit.get()->getExprLoc(),
6406 diag::warn_cxx98_compat_initializer_list_init)
6407 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006408
Richard Smithcc1b96d2013-06-12 22:31:48 +00006409 // Materialize the temporary into memory.
6410 MaterializeTemporaryExpr *MTE = new (S.Context)
6411 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006412 /*BoundToLvalueReference=*/false);
6413
6414 // Maybe lifetime-extend the array temporary's subobjects to match the
6415 // entity's lifetime.
6416 if (const InitializedEntity *ExtendingEntity =
6417 getEntityForTemporaryLifetimeExtension(&Entity))
6418 if (performReferenceExtension(MTE, ExtendingEntity))
6419 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6420 /*IsInitializerList=*/true,
6421 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006422
6423 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006424 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006425
6426 // Bind the result, in case the library has given initializer_list a
6427 // non-trivial destructor.
6428 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006429 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006430 break;
6431 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006432
Guy Benyei61054192013-02-07 10:55:47 +00006433 case SK_OCLSamplerInit: {
6434 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006435 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006436
6437 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006438
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006439 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006440 if (!SourceType->isSamplerT())
6441 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6442 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006443 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006444 llvm_unreachable("Invalid EntityKind!");
6445 }
6446
6447 break;
6448 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006449 case SK_OCLZeroEvent: {
6450 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006451 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006452
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006453 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006454 CK_ZeroToOCLEvent,
6455 CurInit.get()->getValueKind());
6456 break;
6457 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006458 }
6459 }
John McCall1f425642010-11-11 03:21:53 +00006460
6461 // Diagnose non-fatal problems with the completed initialization.
6462 if (Entity.getKind() == InitializedEntity::EK_Member &&
6463 cast<FieldDecl>(Entity.getDecl())->isBitField())
6464 S.CheckBitFieldInitialization(Kind.getLocation(),
6465 cast<FieldDecl>(Entity.getDecl()),
6466 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006467
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006468 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006469}
6470
Richard Smith593f9932012-12-08 02:01:17 +00006471/// Somewhere within T there is an uninitialized reference subobject.
6472/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006473static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6474 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006475 if (T->isReferenceType()) {
6476 S.Diag(Loc, diag::err_reference_without_init)
6477 << T.getNonReferenceType();
6478 return true;
6479 }
6480
6481 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6482 if (!RD || !RD->hasUninitializedReferenceMember())
6483 return false;
6484
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006485 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006486 if (FI->isUnnamedBitfield())
6487 continue;
6488
6489 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6490 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6491 return true;
6492 }
6493 }
6494
Aaron Ballman574705e2014-03-13 15:41:46 +00006495 for (const auto &BI : RD->bases()) {
6496 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006497 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6498 return true;
6499 }
6500 }
6501
6502 return false;
6503}
6504
6505
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006506//===----------------------------------------------------------------------===//
6507// Diagnose initialization failures
6508//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006509
6510/// Emit notes associated with an initialization that failed due to a
6511/// "simple" conversion failure.
6512static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6513 Expr *op) {
6514 QualType destType = entity.getType();
6515 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6516 op->getType()->isObjCObjectPointerType()) {
6517
6518 // Emit a possible note about the conversion failing because the
6519 // operand is a message send with a related result type.
6520 S.EmitRelatedResultTypeNote(op);
6521
6522 // Emit a possible note about a return failing because we're
6523 // expecting a related result type.
6524 if (entity.getKind() == InitializedEntity::EK_Result)
6525 S.EmitRelatedResultTypeNoteForReturn(destType);
6526 }
6527}
6528
Richard Smith0449aaf2013-11-21 23:30:57 +00006529static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6530 InitListExpr *InitList) {
6531 QualType DestType = Entity.getType();
6532
6533 QualType E;
6534 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6535 QualType ArrayType = S.Context.getConstantArrayType(
6536 E.withConst(),
6537 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6538 InitList->getNumInits()),
6539 clang::ArrayType::Normal, 0);
6540 InitializedEntity HiddenArray =
6541 InitializedEntity::InitializeTemporary(ArrayType);
6542 return diagnoseListInit(S, HiddenArray, InitList);
6543 }
6544
Richard Smith8d082d12014-09-04 22:13:39 +00006545 if (DestType->isReferenceType()) {
6546 // A list-initialization failure for a reference means that we tried to
6547 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
6548 // inner initialization failed.
6549 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
6550 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
6551 SourceLocation Loc = InitList->getLocStart();
6552 if (auto *D = Entity.getDecl())
6553 Loc = D->getLocation();
6554 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
6555 return;
6556 }
6557
Richard Smith0449aaf2013-11-21 23:30:57 +00006558 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6559 /*VerifyOnly=*/false);
6560 assert(DiagnoseInitList.HadError() &&
6561 "Inconsistent init list check result.");
6562}
6563
Nico Weber9386c822014-07-23 05:16:10 +00006564/// Prints a fixit for adding a null initializer for |Entity|. Call this only
6565/// right after emitting a diagnostic.
6566static void maybeEmitZeroInitializationFixit(Sema &S,
6567 InitializationSequence &Sequence,
6568 const InitializedEntity &Entity) {
6569 if (Entity.getKind() != InitializedEntity::EK_Variable)
6570 return;
6571
6572 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
6573 if (VD->getInit() || VD->getLocEnd().isMacroID())
6574 return;
6575
6576 QualType VariableTy = VD->getType().getCanonicalType();
6577 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
6578 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
6579
6580 S.Diag(Loc, diag::note_add_initializer)
6581 << VD << FixItHint::CreateInsertion(Loc, Init);
6582}
6583
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006585 const InitializedEntity &Entity,
6586 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006587 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006588 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006589 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590
Douglas Gregor1b303932009-12-22 15:35:07 +00006591 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006592 switch (Failure) {
6593 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006594 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006595 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006596 // Dig out the reference subobject which is uninitialized and diagnose it.
6597 // If this is value-initialization, this could be nested some way within
6598 // the target type.
6599 assert(Kind.getKind() == InitializationKind::IK_Value ||
6600 DestType->isReferenceType());
6601 bool Diagnosed =
6602 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6603 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6604 (void)Diagnosed;
6605 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006606 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006607 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006609
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006610 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006611 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006612 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006613 case FK_ArrayNeedsInitListOrStringLiteral:
6614 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6615 break;
6616 case FK_ArrayNeedsInitListOrWideStringLiteral:
6617 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6618 break;
6619 case FK_NarrowStringIntoWideCharArray:
6620 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6621 break;
6622 case FK_WideStringIntoCharArray:
6623 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6624 break;
6625 case FK_IncompatWideStringIntoWideChar:
6626 S.Diag(Kind.getLocation(),
6627 diag::err_array_init_incompat_wide_string_into_wchar);
6628 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006629 case FK_ArrayTypeMismatch:
6630 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006631 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006632 (Failure == FK_ArrayTypeMismatch
6633 ? diag::err_array_init_different_type
6634 : diag::err_array_init_non_constant_array))
6635 << DestType.getNonReferenceType()
6636 << Args[0]->getType()
6637 << Args[0]->getSourceRange();
6638 break;
6639
John McCalla59dc2f2012-01-05 00:13:19 +00006640 case FK_VariableLengthArrayHasInitializer:
6641 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6642 << Args[0]->getSourceRange();
6643 break;
6644
John McCall16df1e52010-03-30 21:47:33 +00006645 case FK_AddressOfOverloadFailed: {
6646 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006648 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006649 true,
6650 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006651 break;
John McCall16df1e52010-03-30 21:47:33 +00006652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006653
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006654 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006655 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006656 switch (FailedOverloadResult) {
6657 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006658 if (Failure == FK_UserConversionOverloadFailed)
6659 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6660 << Args[0]->getType() << DestType
6661 << Args[0]->getSourceRange();
6662 else
6663 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6664 << DestType << Args[0]->getType()
6665 << Args[0]->getSourceRange();
6666
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006667 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006670 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006671 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006672 DestType.getNonReferenceType(),
6673 diag::err_typecheck_nonviable_condition_incomplete,
6674 Args[0]->getType(), Args[0]->getSourceRange()))
6675 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6676 << Args[0]->getType() << Args[0]->getSourceRange()
6677 << DestType.getNonReferenceType();
6678
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006679 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006680 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006682 case OR_Deleted: {
6683 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6684 << Args[0]->getType() << DestType.getNonReferenceType()
6685 << Args[0]->getSourceRange();
6686 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006687 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006688 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6689 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006690 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006691 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006692 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006693 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006694 }
6695 break;
6696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006697
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006698 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006699 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006700 }
6701 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006703 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006704 if (isa<InitListExpr>(Args[0])) {
6705 S.Diag(Kind.getLocation(),
6706 diag::err_lvalue_reference_bind_to_initlist)
6707 << DestType.getNonReferenceType().isVolatileQualified()
6708 << DestType.getNonReferenceType()
6709 << Args[0]->getSourceRange();
6710 break;
6711 }
6712 // Intentional fallthrough
6713
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006714 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006715 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006716 Failure == FK_NonConstLValueReferenceBindingToTemporary
6717 ? diag::err_lvalue_reference_bind_to_temporary
6718 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006719 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006720 << DestType.getNonReferenceType()
6721 << Args[0]->getType()
6722 << Args[0]->getSourceRange();
6723 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006724
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006725 case FK_RValueReferenceBindingToLValue:
6726 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006727 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006728 << Args[0]->getSourceRange();
6729 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006730
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006731 case FK_ReferenceInitDropsQualifiers:
6732 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6733 << DestType.getNonReferenceType()
6734 << Args[0]->getType()
6735 << Args[0]->getSourceRange();
6736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006737
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006738 case FK_ReferenceInitFailed:
6739 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6740 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006741 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006742 << Args[0]->getType()
6743 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006744 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006745 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006746
Douglas Gregorb491ed32011-02-19 21:32:49 +00006747 case FK_ConversionFailed: {
6748 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006749 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006750 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006751 << DestType
John McCall086a4642010-11-24 05:12:34 +00006752 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006753 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006754 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006755 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6756 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006757 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006758 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006759 }
John Wiegley01296292011-04-08 18:41:53 +00006760
6761 case FK_ConversionFromPropertyFailed:
6762 // No-op. This error has already been reported.
6763 break;
6764
Douglas Gregor51e77d52009-12-10 17:56:55 +00006765 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006766 SourceRange R;
6767
6768 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006769 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006770 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006771 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006772 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006773
Alp Tokerb6cc5922014-05-03 03:45:55 +00006774 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006775 if (Kind.isCStyleOrFunctionalCast())
6776 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6777 << R;
6778 else
6779 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6780 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006781 break;
6782 }
6783
6784 case FK_ReferenceBindingToInitList:
6785 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6786 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6787 break;
6788
6789 case FK_InitListBadDestinationType:
6790 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6791 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6792 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006793
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006794 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006795 case FK_ConstructorOverloadFailed: {
6796 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006797 if (Args.size())
6798 ArgsRange = SourceRange(Args.front()->getLocStart(),
6799 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006800
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006801 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00006802 assert(Args.size() == 1 &&
6803 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006804 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006805 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006806 }
6807
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006808 // FIXME: Using "DestType" for the entity we're printing is probably
6809 // bad.
6810 switch (FailedOverloadResult) {
6811 case OR_Ambiguous:
6812 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6813 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006814 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006815 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006816
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006817 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006818 if (Kind.getKind() == InitializationKind::IK_Default &&
6819 (Entity.getKind() == InitializedEntity::EK_Base ||
6820 Entity.getKind() == InitializedEntity::EK_Member) &&
6821 isa<CXXConstructorDecl>(S.CurContext)) {
6822 // This is implicit default initialization of a member or
6823 // base within a constructor. If no viable function was
6824 // found, notify the user that she needs to explicitly
6825 // initialize this base/member.
6826 CXXConstructorDecl *Constructor
6827 = cast<CXXConstructorDecl>(S.CurContext);
6828 if (Entity.getKind() == InitializedEntity::EK_Base) {
6829 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006830 << (Constructor->getInheritedConstructor() ? 2 :
6831 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006832 << S.Context.getTypeDeclType(Constructor->getParent())
6833 << /*base=*/0
6834 << Entity.getType();
6835
6836 RecordDecl *BaseDecl
6837 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6838 ->getDecl();
6839 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6840 << S.Context.getTagDeclType(BaseDecl);
6841 } else {
6842 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006843 << (Constructor->getInheritedConstructor() ? 2 :
6844 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006845 << S.Context.getTypeDeclType(Constructor->getParent())
6846 << /*member=*/1
6847 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006848 S.Diag(Entity.getDecl()->getLocation(),
6849 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006850
6851 if (const RecordType *Record
6852 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006853 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006854 diag::note_previous_decl)
6855 << S.Context.getTagDeclType(Record->getDecl());
6856 }
6857 break;
6858 }
6859
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006860 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6861 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006862 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006863 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006864
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006865 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006866 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006867 OverloadingResult Ovl
6868 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006869 if (Ovl != OR_Deleted) {
6870 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6871 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006872 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006873 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006874 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006875
6876 // If this is a defaulted or implicitly-declared function, then
6877 // it was implicitly deleted. Make it clear that the deletion was
6878 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006879 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006880 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006881 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006882 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006883 else
6884 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6885 << true << DestType << ArgsRange;
6886
6887 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006888 break;
6889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006890
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006891 case OR_Success:
6892 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006893 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006894 }
David Blaikie60deeee2012-01-17 08:24:58 +00006895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006896
Douglas Gregor85dabae2009-12-16 01:38:02 +00006897 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006898 if (Entity.getKind() == InitializedEntity::EK_Member &&
6899 isa<CXXConstructorDecl>(S.CurContext)) {
6900 // This is implicit default-initialization of a const member in
6901 // a constructor. Complain that it needs to be explicitly
6902 // initialized.
6903 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6904 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006905 << (Constructor->getInheritedConstructor() ? 2 :
6906 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006907 << S.Context.getTypeDeclType(Constructor->getParent())
6908 << /*const=*/1
6909 << Entity.getName();
6910 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6911 << Entity.getName();
6912 } else {
6913 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00006914 << DestType << (bool)DestType->getAs<RecordType>();
6915 maybeEmitZeroInitializationFixit(S, *this, Entity);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006916 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006917 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006919 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006920 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006921 diag::err_init_incomplete_type);
6922 break;
6923
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006924 case FK_ListInitializationFailed: {
6925 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006926 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6927 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006928 break;
6929 }
John McCall4124c492011-10-17 18:40:02 +00006930
6931 case FK_PlaceholderType: {
6932 // FIXME: Already diagnosed!
6933 break;
6934 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006935
Sebastian Redl048a6d72012-04-01 19:54:59 +00006936 case FK_ExplicitConstructor: {
6937 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6938 << Args[0]->getSourceRange();
6939 OverloadCandidateSet::iterator Best;
6940 OverloadingResult Ovl
6941 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006942 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006943 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6944 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6945 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6946 break;
6947 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006950 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006951 return true;
6952}
Douglas Gregore1314a62009-12-18 05:02:21 +00006953
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006954void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006955 switch (SequenceKind) {
6956 case FailedSequence: {
6957 OS << "Failed sequence: ";
6958 switch (Failure) {
6959 case FK_TooManyInitsForReference:
6960 OS << "too many initializers for reference";
6961 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006963 case FK_ArrayNeedsInitList:
6964 OS << "array requires initializer list";
6965 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006966
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006967 case FK_ArrayNeedsInitListOrStringLiteral:
6968 OS << "array requires initializer list or string literal";
6969 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006970
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006971 case FK_ArrayNeedsInitListOrWideStringLiteral:
6972 OS << "array requires initializer list or wide string literal";
6973 break;
6974
6975 case FK_NarrowStringIntoWideCharArray:
6976 OS << "narrow string into wide char array";
6977 break;
6978
6979 case FK_WideStringIntoCharArray:
6980 OS << "wide string into char array";
6981 break;
6982
6983 case FK_IncompatWideStringIntoWideChar:
6984 OS << "incompatible wide string into wide char array";
6985 break;
6986
Douglas Gregore2f943b2011-02-22 18:29:51 +00006987 case FK_ArrayTypeMismatch:
6988 OS << "array type mismatch";
6989 break;
6990
6991 case FK_NonConstantArrayInit:
6992 OS << "non-constant array initializer";
6993 break;
6994
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006995 case FK_AddressOfOverloadFailed:
6996 OS << "address of overloaded function failed";
6997 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006998
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006999 case FK_ReferenceInitOverloadFailed:
7000 OS << "overload resolution for reference initialization failed";
7001 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007003 case FK_NonConstLValueReferenceBindingToTemporary:
7004 OS << "non-const lvalue reference bound to temporary";
7005 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007006
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007007 case FK_NonConstLValueReferenceBindingToUnrelated:
7008 OS << "non-const lvalue reference bound to unrelated type";
7009 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007011 case FK_RValueReferenceBindingToLValue:
7012 OS << "rvalue reference bound to an lvalue";
7013 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007014
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007015 case FK_ReferenceInitDropsQualifiers:
7016 OS << "reference initialization drops qualifiers";
7017 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007018
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007019 case FK_ReferenceInitFailed:
7020 OS << "reference initialization failed";
7021 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007023 case FK_ConversionFailed:
7024 OS << "conversion failed";
7025 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007026
John Wiegley01296292011-04-08 18:41:53 +00007027 case FK_ConversionFromPropertyFailed:
7028 OS << "conversion from property failed";
7029 break;
7030
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007031 case FK_TooManyInitsForScalar:
7032 OS << "too many initializers for scalar";
7033 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007034
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007035 case FK_ReferenceBindingToInitList:
7036 OS << "referencing binding to initializer list";
7037 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007038
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007039 case FK_InitListBadDestinationType:
7040 OS << "initializer list for non-aggregate, non-scalar type";
7041 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007042
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007043 case FK_UserConversionOverloadFailed:
7044 OS << "overloading failed for user-defined conversion";
7045 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007046
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007047 case FK_ConstructorOverloadFailed:
7048 OS << "constructor overloading failed";
7049 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007050
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007051 case FK_DefaultInitOfConst:
7052 OS << "default initialization of a const variable";
7053 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007054
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00007055 case FK_Incomplete:
7056 OS << "initialization of incomplete type";
7057 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007058
7059 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007060 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00007061 break;
7062
John McCalla59dc2f2012-01-05 00:13:19 +00007063 case FK_VariableLengthArrayHasInitializer:
7064 OS << "variable length array has an initializer";
7065 break;
7066
John McCall4124c492011-10-17 18:40:02 +00007067 case FK_PlaceholderType:
7068 OS << "initializer expression isn't contextually valid";
7069 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00007070
7071 case FK_ListConstructorOverloadFailed:
7072 OS << "list constructor overloading failed";
7073 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007074
Sebastian Redl048a6d72012-04-01 19:54:59 +00007075 case FK_ExplicitConstructor:
7076 OS << "list copy initialization chose explicit constructor";
7077 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007078 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007079 OS << '\n';
7080 return;
7081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007082
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007083 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007084 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007085 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
Sebastian Redld201edf2011-06-05 13:59:11 +00007087 case NormalSequence:
7088 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007089 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007091
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007092 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7093 if (S != step_begin()) {
7094 OS << " -> ";
7095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007096
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007097 switch (S->Kind) {
7098 case SK_ResolveAddressOfOverloadedFunction:
7099 OS << "resolve address of overloaded function";
7100 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007101
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007102 case SK_CastDerivedToBaseRValue:
7103 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7104 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007105
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007106 case SK_CastDerivedToBaseXValue:
7107 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7108 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007109
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007110 case SK_CastDerivedToBaseLValue:
7111 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7112 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007113
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007114 case SK_BindReference:
7115 OS << "bind reference to lvalue";
7116 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007118 case SK_BindReferenceToTemporary:
7119 OS << "bind reference to a temporary";
7120 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007121
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007122 case SK_ExtraneousCopyToTemporary:
7123 OS << "extraneous C++03 copy to temporary";
7124 break;
7125
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007126 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007127 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007128 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007129
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007130 case SK_QualificationConversionRValue:
7131 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007132 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007133
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007134 case SK_QualificationConversionXValue:
7135 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007136 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007137
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007138 case SK_QualificationConversionLValue:
7139 OS << "qualification conversion (lvalue)";
7140 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007141
Richard Smith77be48a2014-07-31 06:31:19 +00007142 case SK_AtomicConversion:
7143 OS << "non-atomic-to-atomic conversion";
7144 break;
7145
Jordan Roseb1312a52013-04-11 00:58:58 +00007146 case SK_LValueToRValue:
7147 OS << "load (lvalue to rvalue)";
7148 break;
7149
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007150 case SK_ConversionSequence:
7151 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007152 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007153 OS << ")";
7154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007155
Richard Smithaaa0ec42013-09-21 21:19:19 +00007156 case SK_ConversionSequenceNoNarrowing:
7157 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007158 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007159 OS << ")";
7160 break;
7161
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007162 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007163 OS << "list aggregate initialization";
7164 break;
7165
Sebastian Redl29526f02011-11-27 16:50:07 +00007166 case SK_UnwrapInitList:
7167 OS << "unwrap reference initializer list";
7168 break;
7169
7170 case SK_RewrapInitList:
7171 OS << "rewrap reference initializer list";
7172 break;
7173
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007174 case SK_ConstructorInitialization:
7175 OS << "constructor initialization";
7176 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177
Richard Smith53324112014-07-16 21:33:43 +00007178 case SK_ConstructorInitializationFromList:
7179 OS << "list initialization via constructor";
7180 break;
7181
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007182 case SK_ZeroInitialization:
7183 OS << "zero initialization";
7184 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007185
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007186 case SK_CAssignment:
7187 OS << "C assignment";
7188 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007189
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007190 case SK_StringInit:
7191 OS << "string initialization";
7192 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007193
7194 case SK_ObjCObjectConversion:
7195 OS << "Objective-C object conversion";
7196 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007197
7198 case SK_ArrayInit:
7199 OS << "array initialization";
7200 break;
John McCall31168b02011-06-15 23:02:42 +00007201
Richard Smithebeed412012-02-15 22:38:09 +00007202 case SK_ParenthesizedArrayInit:
7203 OS << "parenthesized array initialization";
7204 break;
7205
John McCall31168b02011-06-15 23:02:42 +00007206 case SK_PassByIndirectCopyRestore:
7207 OS << "pass by indirect copy and restore";
7208 break;
7209
7210 case SK_PassByIndirectRestore:
7211 OS << "pass by indirect restore";
7212 break;
7213
7214 case SK_ProduceObjCObject:
7215 OS << "Objective-C object retension";
7216 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007217
7218 case SK_StdInitializerList:
7219 OS << "std::initializer_list from initializer list";
7220 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007221
Richard Smithf8adcdc2014-07-17 05:12:35 +00007222 case SK_StdInitializerListConstructorCall:
7223 OS << "list initialization from std::initializer_list";
7224 break;
7225
Guy Benyei61054192013-02-07 10:55:47 +00007226 case SK_OCLSamplerInit:
7227 OS << "OpenCL sampler_t from integer constant";
7228 break;
7229
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007230 case SK_OCLZeroEvent:
7231 OS << "OpenCL event_t from zero";
7232 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007233 }
Richard Smith6b216962013-02-05 05:52:24 +00007234
7235 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007236 }
Richard Smith6b216962013-02-05 05:52:24 +00007237
7238 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007239}
7240
7241void InitializationSequence::dump() const {
7242 dump(llvm::errs());
7243}
7244
Richard Smithaaa0ec42013-09-21 21:19:19 +00007245static void DiagnoseNarrowingInInitList(Sema &S,
7246 const ImplicitConversionSequence &ICS,
7247 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007248 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007249 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007250 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007251 switch (ICS.getKind()) {
7252 case ImplicitConversionSequence::StandardConversion:
7253 SCS = &ICS.Standard;
7254 break;
7255 case ImplicitConversionSequence::UserDefinedConversion:
7256 SCS = &ICS.UserDefined.After;
7257 break;
7258 case ImplicitConversionSequence::AmbiguousConversion:
7259 case ImplicitConversionSequence::EllipsisConversion:
7260 case ImplicitConversionSequence::BadConversion:
7261 return;
7262 }
7263
Richard Smith66e05fe2012-01-18 05:21:49 +00007264 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7265 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007266 QualType ConstantType;
7267 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7268 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007269 case NK_Not_Narrowing:
7270 // No narrowing occurred.
7271 return;
7272
7273 case NK_Type_Narrowing:
7274 // This was a floating-to-integer conversion, which is always considered a
7275 // narrowing conversion even if the value is a constant and can be
7276 // represented exactly as an integer.
7277 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007278 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7279 ? diag::warn_init_list_type_narrowing
7280 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007281 << PostInit->getSourceRange()
7282 << PreNarrowingType.getLocalUnqualifiedType()
7283 << EntityType.getLocalUnqualifiedType();
7284 break;
7285
7286 case NK_Constant_Narrowing:
7287 // A constant value was narrowed.
7288 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007289 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7290 ? diag::warn_init_list_constant_narrowing
7291 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007292 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007293 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007294 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007295 break;
7296
7297 case NK_Variable_Narrowing:
7298 // A variable's value may have been narrowed.
7299 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007300 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7301 ? diag::warn_init_list_variable_narrowing
7302 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007303 << PostInit->getSourceRange()
7304 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007305 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007306 break;
7307 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007308
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007309 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007310 llvm::raw_svector_ostream OS(StaticCast);
7311 OS << "static_cast<";
7312 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7313 // It's important to use the typedef's name if there is one so that the
7314 // fixit doesn't break code using types like int64_t.
7315 //
7316 // FIXME: This will break if the typedef requires qualification. But
7317 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007318 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007319 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007320 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007321 else {
7322 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7323 // with a broken cast.
7324 return;
7325 }
7326 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007327 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007328 << PostInit->getSourceRange()
7329 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7330 << FixItHint::CreateInsertion(
7331 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007332}
7333
Douglas Gregore1314a62009-12-18 05:02:21 +00007334//===----------------------------------------------------------------------===//
7335// Initialization helper functions
7336//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007337bool
7338Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7339 ExprResult Init) {
7340 if (Init.isInvalid())
7341 return false;
7342
7343 Expr *InitE = Init.get();
7344 assert(InitE && "No initialization expression");
7345
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007346 InitializationKind Kind
7347 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007348 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007349 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007350}
7351
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007352ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007353Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7354 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007355 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007356 bool TopLevelOfInitList,
7357 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007358 if (Init.isInvalid())
7359 return ExprError();
7360
John McCall1f425642010-11-11 03:21:53 +00007361 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007362 assert(InitE && "No initialization expression?");
7363
7364 if (EqualLoc.isInvalid())
7365 EqualLoc = InitE->getLocStart();
7366
7367 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007368 EqualLoc,
7369 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007370 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007371 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007372
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007373 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007374
Richard Smith66e05fe2012-01-18 05:21:49 +00007375 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007376}