blob: b11769bf4289fc01f1831089ac932ad100e393ec [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
Steve Narofff8ecff22008-05-01 22:18:59 +000014#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000016#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000017#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000018#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000019#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Designator.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#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"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000028
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
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000207namespace {
208
Douglas Gregorcde232f2009-01-29 01:05:33 +0000209/// @brief Semantic checking for initializer lists.
210///
211/// The InitListChecker class contains a set of routines that each
212/// handle the initialization of a certain kind of entity, e.g.,
213/// arrays, vectors, struct/union types, scalars, etc. The
214/// InitListChecker itself performs a recursive walk of the subobject
215/// structure of the type to be initialized, while stepping through
216/// the initializer list one element at a time. The IList and Index
217/// parameters to each of the Check* routines contain the active
218/// (syntactic) initializer list and the index into that initializer
219/// list that represents the current initializer. Each routine is
220/// responsible for moving that Index forward as it consumes elements.
221///
222/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000223/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000224/// initializer list and the index into that initializer list where we
225/// are copying initializers as we map them over to the semantic
226/// list. Once we have completed our recursive walk of the subobject
227/// structure, we will have constructed a full semantic initializer
228/// list.
229///
230/// C99 designators cause changes in the initializer list traversal,
231/// because they make the initialization "jump" into a specific
232/// subobject and then continue the initialization from that
233/// point. CheckDesignatedInitializer() recursively steps into the
234/// designated subobject and manages backing out the recursion to
235/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000237 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000238 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000239 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000240 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000241 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000243
Anders Carlsson6cabf312010-01-23 23:23:01 +0000244 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000245 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000246 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000247 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000248 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000249 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000250 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000251 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000252 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000253 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000254 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000255 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000256 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000257 unsigned &StructuredIndex,
258 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000259 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000260 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000261 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000262 InitListExpr *StructuredList,
263 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000264 void CheckComplexType(const InitializedEntity &Entity,
265 InitListExpr *IList, QualType DeclType,
266 unsigned &Index,
267 InitListExpr *StructuredList,
268 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000269 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000270 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000271 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000272 InitListExpr *StructuredList,
273 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000274 void CheckReferenceType(const InitializedEntity &Entity,
275 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000276 unsigned &Index,
277 InitListExpr *StructuredList,
278 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000279 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000280 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000283 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000284 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000285 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000286 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000287 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000288 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000289 unsigned &StructuredIndex,
290 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000291 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000292 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000293 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000294 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000295 InitListExpr *StructuredList,
296 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000297 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000298 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000299 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000300 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000301 RecordDecl::field_iterator *NextField,
302 llvm::APSInt *NextElementIndex,
303 unsigned &Index,
304 InitListExpr *StructuredList,
305 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000306 bool FinishSubobjectInit,
307 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000308 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
309 QualType CurrentObjectType,
310 InitListExpr *StructuredList,
311 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000312 SourceRange InitRange,
313 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000314 void UpdateStructuredListElement(InitListExpr *StructuredList,
315 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000316 Expr *expr);
317 int numArrayElements(QualType DeclType);
318 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000319
Richard Smith454a7cd2014-06-03 08:26:00 +0000320 static ExprResult PerformEmptyInit(Sema &SemaRef,
321 SourceLocation Loc,
322 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000323 bool VerifyOnly,
324 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000325
326 // Explanation on the "FillWithNoInit" mode:
327 //
328 // Assume we have the following definitions (Case#1):
329 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
330 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
331 //
332 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
333 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
334 //
335 // But if we have (Case#2):
336 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
337 //
338 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
339 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
340 //
341 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
342 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
343 // initializers but with special "NoInitExpr" place holders, which tells the
344 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000345 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
346 const InitializedEntity &ParentEntity,
347 InitListExpr *ILE, bool &RequiresSecondPass,
348 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000349 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000351 InitListExpr *ILE, bool &RequiresSecondPass,
352 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000353 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000354 InitListExpr *ILE, bool &RequiresSecondPass,
355 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000356 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
357 Expr *InitExpr, FieldDecl *Field,
358 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000359 void CheckEmptyInitializable(const InitializedEntity &Entity,
360 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000361
Douglas Gregor85df8d82009-01-29 00:45:39 +0000362public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000363 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000364 InitListExpr *IL, QualType &T, bool VerifyOnly,
365 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000366 bool HadError() { return hadError; }
367
368 // @brief Retrieves the fully-structured initializer list used for
369 // semantic analysis and code generation.
370 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
371};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000372
Chris Lattner9ececce2009-02-24 22:48:58 +0000373} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000374
Richard Smith454a7cd2014-06-03 08:26:00 +0000375ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
376 SourceLocation Loc,
377 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000378 bool VerifyOnly,
379 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000380 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
381 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000382 MultiExprArg SubInit;
383 Expr *InitExpr;
384 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
385
386 // C++ [dcl.init.aggr]p7:
387 // If there are fewer initializer-clauses in the list than there are
388 // members in the aggregate, then each member not explicitly initialized
389 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000390 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
391 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
392 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000393 // C++1y / DR1070:
394 // shall be initialized [...] from an empty initializer list.
395 //
396 // We apply the resolution of this DR to C++11 but not C++98, since C++98
397 // does not have useful semantics for initialization from an init list.
398 // We treat this as copy-initialization, because aggregate initialization
399 // always performs copy-initialization on its elements.
400 //
401 // Only do this if we're initializing a class type, to avoid filling in
402 // the initializer list where possible.
403 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
404 InitListExpr(SemaRef.Context, Loc, None, Loc);
405 InitExpr->setType(SemaRef.Context.VoidTy);
406 SubInit = InitExpr;
407 Kind = InitializationKind::CreateCopy(Loc, Loc);
408 } else {
409 // C++03:
410 // shall be value-initialized.
411 }
412
413 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000414 // libstdc++4.6 marks the vector default constructor as explicit in
415 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
416 // stlport does so too. Look for std::__debug for libstdc++, and for
417 // std:: for stlport. This is effectively a compiler-side implementation of
418 // LWG2193.
419 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
420 InitializationSequence::FK_ExplicitConstructor) {
421 OverloadCandidateSet::iterator Best;
422 OverloadingResult O =
423 InitSeq.getFailedCandidateSet()
424 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
425 (void)O;
426 assert(O == OR_Success && "Inconsistent overload resolution");
427 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
428 CXXRecordDecl *R = CtorDecl->getParent();
429
430 if (CtorDecl->getMinRequiredArguments() == 0 &&
431 CtorDecl->isExplicit() && R->getDeclName() &&
432 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000433 bool IsInStd = false;
434 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000435 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000436 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
437 IsInStd = true;
438 }
439
440 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
441 .Cases("basic_string", "deque", "forward_list", true)
442 .Cases("list", "map", "multimap", "multiset", true)
443 .Cases("priority_queue", "queue", "set", "stack", true)
444 .Cases("unordered_map", "unordered_set", "vector", true)
445 .Default(false)) {
446 InitSeq.InitializeFrom(
447 SemaRef, Entity,
448 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000449 MultiExprArg(), /*TopLevelOfInitList=*/false,
450 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000451 // Emit a warning for this. System header warnings aren't shown
452 // by default, but people working on system headers should see it.
453 if (!VerifyOnly) {
454 SemaRef.Diag(CtorDecl->getLocation(),
455 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000456 if (Entity.getKind() == InitializedEntity::EK_Member)
457 SemaRef.Diag(Entity.getDecl()->getLocation(),
458 diag::note_used_in_initialization_here);
459 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
460 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000461 }
462 }
463 }
464 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000465 if (!InitSeq) {
466 if (!VerifyOnly) {
467 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
468 if (Entity.getKind() == InitializedEntity::EK_Member)
469 SemaRef.Diag(Entity.getDecl()->getLocation(),
470 diag::note_in_omitted_aggregate_initializer)
471 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000472 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
473 bool IsTrailingArrayNewMember =
474 Entity.getParent() &&
475 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000476 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000477 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
478 << Entity.getElementIndex();
479 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000480 }
481 return ExprError();
482 }
483
484 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
485 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
486}
487
488void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
489 SourceLocation Loc) {
490 assert(VerifyOnly &&
491 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000492 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
493 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000494 hadError = true;
495}
496
Richard Smith872307e2016-03-08 22:17:41 +0000497void InitListChecker::FillInEmptyInitForBase(
498 unsigned Init, const CXXBaseSpecifier &Base,
499 const InitializedEntity &ParentEntity, InitListExpr *ILE,
500 bool &RequiresSecondPass, bool FillWithNoInit) {
501 assert(Init < ILE->getNumInits() && "should have been expanded");
502
503 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
504 SemaRef.Context, &Base, false, &ParentEntity);
505
506 if (!ILE->getInit(Init)) {
507 ExprResult BaseInit =
508 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
509 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
Manman Ren073db022016-03-10 18:53:19 +0000510 /*VerifyOnly*/ false,
511 TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000512 if (BaseInit.isInvalid()) {
513 hadError = true;
514 return;
515 }
516
517 ILE->setInit(Init, BaseInit.getAs<Expr>());
518 } else if (InitListExpr *InnerILE =
519 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
520 FillInEmptyInitializations(BaseEntity, InnerILE,
521 RequiresSecondPass, FillWithNoInit);
522 } else if (DesignatedInitUpdateExpr *InnerDIUE =
523 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
524 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
525 RequiresSecondPass, /*FillWithNoInit =*/true);
526 }
527}
528
Richard Smith454a7cd2014-06-03 08:26:00 +0000529void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000530 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000532 bool &RequiresSecondPass,
533 bool FillWithNoInit) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000534 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000535 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000537 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000538
539 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
540 if (!RType->getDecl()->isUnion())
541 assert(Init < NumInits && "This ILE should have been expanded");
542
Douglas Gregor2bb07652009-12-22 00:05:34 +0000543 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000544 if (FillWithNoInit) {
545 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
546 if (Init < NumInits)
547 ILE->setInit(Init, Filler);
548 else
549 ILE->updateInit(SemaRef.Context, Init, Filler);
550 return;
551 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000552 // C++1y [dcl.init.aggr]p7:
553 // If there are fewer initializer-clauses in the list than there are
554 // members in the aggregate, then each member not explicitly initialized
555 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000556 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000557 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
558 if (DIE.isInvalid()) {
559 hadError = true;
560 return;
561 }
Richard Smith852c9db2013-04-20 22:23:05 +0000562 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000563 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000564 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000565 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000566 RequiresSecondPass = true;
567 }
568 return;
569 }
570
Douglas Gregor2bb07652009-12-22 00:05:34 +0000571 if (Field->getType()->isReferenceType()) {
572 // C++ [dcl.init.aggr]p9:
573 // If an incomplete or empty initializer-list leaves a
574 // member of reference type uninitialized, the program is
575 // ill-formed.
576 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
577 << Field->getType()
578 << ILE->getSyntacticForm()->getSourceRange();
579 SemaRef.Diag(Field->getLocation(),
580 diag::note_uninit_reference_member);
581 hadError = true;
582 return;
583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Richard Smith454a7cd2014-06-03 08:26:00 +0000585 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000586 /*VerifyOnly*/false,
587 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000588 if (MemberInit.isInvalid()) {
589 hadError = true;
590 return;
591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
Douglas Gregor2bb07652009-12-22 00:05:34 +0000593 if (hadError) {
594 // Do nothing
595 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000596 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000597 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
598 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000599 // extend the initializer list to include the constructor
600 // call and make a note that we'll need to take another pass
601 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000602 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000603 RequiresSecondPass = true;
604 }
605 } else if (InitListExpr *InnerILE
606 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000607 FillInEmptyInitializations(MemberEntity, InnerILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000608 RequiresSecondPass, FillWithNoInit);
609 else if (DesignatedInitUpdateExpr *InnerDIUE
610 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
611 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
612 RequiresSecondPass, /*FillWithNoInit =*/ true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000613}
614
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000615/// Recursively replaces NULL values within the given initializer list
616/// with expressions that perform value-initialization of the
617/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618void
Richard Smith454a7cd2014-06-03 08:26:00 +0000619InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000620 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000621 bool &RequiresSecondPass,
622 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000623 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000624 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000625
Richard Smith382bc512017-02-23 22:41:47 +0000626 // A transparent ILE is not performing aggregate initialization and should
627 // not be filled in.
628 if (ILE->isTransparent())
629 return;
630
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000631 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000632 const RecordDecl *RDecl = RType->getDecl();
633 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000634 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000635 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000636 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
637 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000638 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000639 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000640 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
641 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000642 break;
643 }
644 }
645 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000646 // The fields beyond ILE->getNumInits() are default initialized, so in
647 // order to leave them uninitialized, the ILE is expanded and the extra
648 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000649 unsigned NumElems = numStructUnionElements(ILE->getType());
650 if (RDecl->hasFlexibleArrayMember())
651 ++NumElems;
652 if (ILE->getNumInits() < NumElems)
653 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000654
Douglas Gregor2bb07652009-12-22 00:05:34 +0000655 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000656
657 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
658 for (auto &Base : CXXRD->bases()) {
659 if (hadError)
660 return;
661
662 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
663 FillWithNoInit);
664 ++Init;
665 }
666 }
667
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000668 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000669 if (Field->isUnnamedBitfield())
670 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000671
Douglas Gregor2bb07652009-12-22 00:05:34 +0000672 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000673 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000674
Yunzhong Gaocb779302015-06-10 00:27:52 +0000675 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
676 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000677 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000678 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000679
Douglas Gregor2bb07652009-12-22 00:05:34 +0000680 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000681
Douglas Gregor2bb07652009-12-22 00:05:34 +0000682 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000683 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000684 break;
685 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000686 }
687
688 return;
Mike Stump11289f42009-09-09 15:08:12 +0000689 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000690
691 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Douglas Gregor723796a2009-12-16 06:35:08 +0000693 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000694 unsigned NumInits = ILE->getNumInits();
695 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000696 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000697 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000698 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000699 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000700 // For an array new with an unknown bound, ask for one additional element
701 // in order to populate the array filler.
702 if (Entity.isVariableLengthArrayNew())
703 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000705 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000706 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000707 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000708 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000710 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000711 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000712 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000713
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000714 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000715 if (hadError)
716 return;
717
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000718 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
719 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000720 ElementEntity.setElementIndex(Init);
721
Craig Topperc3ec1492014-05-26 06:22:03 +0000722 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000723 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
724 ILE->setInit(Init, ILE->getArrayFiller());
725 else if (!InitExpr && !ILE->hasArrayFiller()) {
726 Expr *Filler = nullptr;
727
728 if (FillWithNoInit)
729 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
730 else {
731 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
732 ElementEntity,
Manman Ren073db022016-03-10 18:53:19 +0000733 /*VerifyOnly*/false,
734 TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000735 if (ElementInit.isInvalid()) {
736 hadError = true;
737 return;
738 }
739
740 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000741 }
742
743 if (hadError) {
744 // Do nothing
745 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000746 // For arrays, just set the expression used for value-initialization
747 // of the "holes" in the array.
748 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000749 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000750 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000751 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000752 } else {
753 // For arrays, just set the expression used for value-initialization
754 // of the rest of elements and exit.
755 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000756 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000757 return;
758 }
759
Yunzhong Gaocb779302015-06-10 00:27:52 +0000760 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000761 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000762 // extend the initializer list to include the constructor
763 // call and make a note that we'll need to take another pass
764 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000765 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000766 RequiresSecondPass = true;
767 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000768 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000769 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000770 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000771 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
772 FillWithNoInit);
773 else if (DesignatedInitUpdateExpr *InnerDIUE
774 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
775 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
776 RequiresSecondPass, /*FillWithNoInit =*/ true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000777 }
778}
779
Douglas Gregor723796a2009-12-16 06:35:08 +0000780InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000781 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000782 bool VerifyOnly,
783 bool TreatUnavailableAsInvalid)
784 : SemaRef(S), VerifyOnly(VerifyOnly),
785 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000786 // FIXME: Check that IL isn't already the semantic form of some other
787 // InitListExpr. If it is, we'd create a broken AST.
788
Steve Narofff8ecff22008-05-01 22:18:59 +0000789 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000790
Richard Smith4e0d2e42013-09-20 20:10:22 +0000791 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000792 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000793 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000794 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000795
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000797 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000798 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000799 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000800 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000801 RequiresSecondPass);
802 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000803}
804
805int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000806 // FIXME: use a proper constant
807 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000808 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000809 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000810 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
811 }
812 return maxElements;
813}
814
815int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000816 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000817 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000818 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
819 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000820 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000821 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000822 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000823
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000824 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000825 return std::min(InitializableMembers, 1);
826 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000827}
828
Richard Smith4e0d2e42013-09-20 20:10:22 +0000829/// Check whether the range of the initializer \p ParentIList from element
830/// \p Index onwards can be used to initialize an object of type \p T. Update
831/// \p Index to indicate how many elements of the list were consumed.
832///
833/// This also fills in \p StructuredList, from element \p StructuredIndex
834/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000835void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000836 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000837 QualType T, unsigned &Index,
838 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000839 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000840 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000841
Steve Narofff8ecff22008-05-01 22:18:59 +0000842 if (T->isArrayType())
843 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000844 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000845 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000846 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000847 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000848 else
David Blaikie83d382b2011-09-23 05:06:16 +0000849 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000850
Eli Friedmane0f832b2008-05-25 13:49:22 +0000851 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000852 if (!VerifyOnly)
853 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
854 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000855 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000856 hadError = true;
857 return;
858 }
859
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000860 // Build a structured initializer list corresponding to this subobject.
861 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000862 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
863 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000864 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000865 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000866 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000867
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000868 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000869 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000871 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000872 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000873 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000874
Richard Smithde229232013-06-06 11:41:05 +0000875 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000876 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000877
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000878 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000879 // Update the structured sub-object initializer so that it's ending
880 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000881 if (EndIndex < ParentIList->getNumInits() &&
882 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000883 SourceLocation EndLoc
884 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
885 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000888 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000889 if (T->isArrayType() || T->isRecordType()) {
890 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000891 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000892 << StructuredSubobjectInitList->getSourceRange()
893 << FixItHint::CreateInsertion(
894 StructuredSubobjectInitList->getLocStart(), "{")
895 << FixItHint::CreateInsertion(
896 SemaRef.getLocForEndOfToken(
897 StructuredSubobjectInitList->getLocEnd()),
898 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000899 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000900 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000901}
902
Richard Smith420fa122015-02-12 01:50:05 +0000903/// Warn that \p Entity was of scalar type and was initialized by a
904/// single-element braced initializer list.
905static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
906 SourceRange Braces) {
907 // Don't warn during template instantiation. If the initialization was
908 // non-dependent, we warned during the initial parse; otherwise, the
909 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000910 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000911 return;
912
913 unsigned DiagID = 0;
914
915 switch (Entity.getKind()) {
916 case InitializedEntity::EK_VectorElement:
917 case InitializedEntity::EK_ComplexElement:
918 case InitializedEntity::EK_ArrayElement:
919 case InitializedEntity::EK_Parameter:
920 case InitializedEntity::EK_Parameter_CF_Audited:
921 case InitializedEntity::EK_Result:
922 // Extra braces here are suspicious.
923 DiagID = diag::warn_braces_around_scalar_init;
924 break;
925
926 case InitializedEntity::EK_Member:
927 // Warn on aggregate initialization but not on ctor init list or
928 // default member initializer.
929 if (Entity.getParent())
930 DiagID = diag::warn_braces_around_scalar_init;
931 break;
932
933 case InitializedEntity::EK_Variable:
934 case InitializedEntity::EK_LambdaCapture:
935 // No warning, might be direct-list-initialization.
936 // FIXME: Should we warn for copy-list-initialization in these cases?
937 break;
938
939 case InitializedEntity::EK_New:
940 case InitializedEntity::EK_Temporary:
941 case InitializedEntity::EK_CompoundLiteralInit:
942 // No warning, braces are part of the syntax of the underlying construct.
943 break;
944
945 case InitializedEntity::EK_RelatedResult:
946 // No warning, we already warned when initializing the result.
947 break;
948
949 case InitializedEntity::EK_Exception:
950 case InitializedEntity::EK_Base:
951 case InitializedEntity::EK_Delegating:
952 case InitializedEntity::EK_BlockElement:
Richard Smith7873de02016-08-11 22:25:46 +0000953 case InitializedEntity::EK_Binding:
Richard Smith420fa122015-02-12 01:50:05 +0000954 llvm_unreachable("unexpected braced scalar init");
955 }
956
957 if (DiagID) {
958 S.Diag(Braces.getBegin(), DiagID)
959 << Braces
960 << FixItHint::CreateRemoval(Braces.getBegin())
961 << FixItHint::CreateRemoval(Braces.getEnd());
962 }
963}
964
Richard Smith4e0d2e42013-09-20 20:10:22 +0000965/// Check whether the initializer \p IList (that was written with explicit
966/// braces) can be used to initialize an object of type \p T.
967///
968/// This also fills in \p StructuredList with the fully-braced, desugared
969/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000970void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000971 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000972 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000973 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000974 if (!VerifyOnly) {
975 SyntacticToSemantic[IList] = StructuredList;
976 StructuredList->setSyntacticForm(IList);
977 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000978
979 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000980 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000981 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000982 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000983 QualType ExprTy = T;
984 if (!ExprTy->isArrayType())
985 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000986 IList->setType(ExprTy);
987 StructuredList->setType(ExprTy);
988 }
Eli Friedman85f54972008-05-25 13:22:35 +0000989 if (hadError)
990 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000991
Eli Friedman85f54972008-05-25 13:22:35 +0000992 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000993 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000994 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000995 if (SemaRef.getLangOpts().CPlusPlus ||
996 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000997 IList->getType()->isVectorType())) {
998 hadError = true;
999 }
1000 return;
1001 }
1002
Eli Friedmanbd327452009-05-29 20:20:05 +00001003 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001004 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1005 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001006 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001007 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001008 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001009 hadError = true;
1010 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001011 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +00001012 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +00001013 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001014 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001015 // Don't complain for incomplete types, since we'll get an error
1016 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001017 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001018 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001019 CurrentObjectType->isArrayType()? 0 :
1020 CurrentObjectType->isVectorType()? 1 :
1021 CurrentObjectType->isScalarType()? 2 :
1022 CurrentObjectType->isUnionType()? 3 :
1023 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001024
Richard Smith1b98ccc2014-07-19 01:39:17 +00001025 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001026 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001027 DK = diag::err_excess_initializers;
1028 hadError = true;
1029 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001030 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001031 DK = diag::err_excess_initializers;
1032 hadError = true;
1033 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001034
Chris Lattnerb0912a52009-02-24 22:50:46 +00001035 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001036 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001037 }
1038 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001039
Richard Smith420fa122015-02-12 01:50:05 +00001040 if (!VerifyOnly && T->isScalarType() &&
1041 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1042 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +00001043}
1044
Anders Carlsson6cabf312010-01-23 23:23:01 +00001045void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001046 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001047 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001048 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001049 unsigned &Index,
1050 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001051 unsigned &StructuredIndex,
1052 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001053 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1054 // Explicitly braced initializer for complex type can be real+imaginary
1055 // parts.
1056 CheckComplexType(Entity, IList, DeclType, Index,
1057 StructuredList, StructuredIndex);
1058 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001059 CheckScalarType(Entity, IList, DeclType, Index,
1060 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001061 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001063 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001064 } else if (DeclType->isRecordType()) {
1065 assert(DeclType->isAggregateType() &&
1066 "non-aggregate records should be handed in CheckSubElementType");
1067 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001068 auto Bases =
1069 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1070 CXXRecordDecl::base_class_iterator());
1071 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1072 Bases = CXXRD->bases();
1073 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1074 SubobjectIsDesignatorContext, Index, StructuredList,
1075 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001076 } else if (DeclType->isArrayType()) {
1077 llvm::APSInt Zero(
1078 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1079 false);
1080 CheckArrayType(Entity, IList, DeclType, Zero,
1081 SubobjectIsDesignatorContext, Index,
1082 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001083 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1084 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001085 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001086 if (!VerifyOnly)
1087 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1088 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001089 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001090 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001091 CheckReferenceType(Entity, IList, DeclType, Index,
1092 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001093 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001094 if (!VerifyOnly)
1095 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1096 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001097 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001098 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001099 if (!VerifyOnly)
1100 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1101 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001102 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001103 }
1104}
1105
Anders Carlsson6cabf312010-01-23 23:23:01 +00001106void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001107 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001108 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001109 unsigned &Index,
1110 InitListExpr *StructuredList,
1111 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001112 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001113
1114 if (ElemType->isReferenceType())
1115 return CheckReferenceType(Entity, IList, ElemType, Index,
1116 StructuredList, StructuredIndex);
1117
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001118 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001119 if (SubInitList->getNumInits() == 1 &&
1120 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1121 SIF_None) {
1122 expr = SubInitList->getInit(0);
1123 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001124 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001125 = getStructuredSubobjectInit(IList, Index, ElemType,
1126 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001127 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001128 CheckExplicitInitList(Entity, SubInitList, ElemType,
1129 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001130
1131 if (!hadError && !VerifyOnly) {
1132 bool RequiresSecondPass = false;
1133 FillInEmptyInitializations(Entity, InnerStructuredList,
1134 RequiresSecondPass);
1135 if (RequiresSecondPass && !hadError)
1136 FillInEmptyInitializations(Entity, InnerStructuredList,
1137 RequiresSecondPass);
1138 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001139 ++StructuredIndex;
1140 ++Index;
1141 return;
1142 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001143 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001144 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001145 // This happens during template instantiation when we see an InitListExpr
1146 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001147 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001148 "found implicit initialization for the wrong type");
1149 if (!VerifyOnly)
1150 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1151 ++Index;
1152 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001153 }
1154
Richard Smith3c567fc2015-02-12 01:55:09 +00001155 if (SemaRef.getLangOpts().CPlusPlus) {
1156 // C++ [dcl.init.aggr]p2:
1157 // Each member is copy-initialized from the corresponding
1158 // initializer-clause.
1159
1160 // FIXME: Better EqualLoc?
1161 InitializationKind Kind =
1162 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1163 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1164 /*TopLevelOfInitList*/ true);
1165
1166 // C++14 [dcl.init.aggr]p13:
1167 // If the assignment-expression can initialize a member, the member is
1168 // initialized. Otherwise [...] brace elision is assumed
1169 //
1170 // Brace elision is never performed if the element is not an
1171 // assignment-expression.
1172 if (Seq || isa<InitListExpr>(expr)) {
1173 if (!VerifyOnly) {
1174 ExprResult Result =
1175 Seq.Perform(SemaRef, Entity, Kind, expr);
1176 if (Result.isInvalid())
1177 hadError = true;
1178
1179 UpdateStructuredListElement(StructuredList, StructuredIndex,
1180 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001181 } else if (!Seq)
1182 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001183 ++Index;
1184 return;
1185 }
1186
1187 // Fall through for subaggregate initialization
1188 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1189 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001190 return CheckScalarType(Entity, IList, ElemType, Index,
1191 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001192 } else if (const ArrayType *arrayType =
1193 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001194 // arrayType can be incomplete if we're initializing a flexible
1195 // array member. There's nothing we can do with the completed
1196 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001197
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001198 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001199 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001200 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1201 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001202 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001203 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001204 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001205 }
John McCall5decec92011-02-21 07:57:55 +00001206
1207 // Fall through for subaggregate initialization.
1208
John McCall5decec92011-02-21 07:57:55 +00001209 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001210 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1211 ElemType->isClkEventT()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001212
John McCall5decec92011-02-21 07:57:55 +00001213 // C99 6.7.8p13:
1214 //
1215 // The initializer for a structure or union object that has
1216 // automatic storage duration shall be either an initializer
1217 // list as described below, or a single expression that has
1218 // compatible structure or union type. In the latter case, the
1219 // initial value of the object, including unnamed members, is
1220 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001221 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001222 if (SemaRef.CheckSingleAssignmentConstraints(
1223 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001224 if (ExprRes.isInvalid())
1225 hadError = true;
1226 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001227 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001228 if (ExprRes.isInvalid())
1229 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001230 }
1231 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001232 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001233 ++Index;
1234 return;
1235 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001236 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001237 // Fall through for subaggregate initialization
1238 }
1239
1240 // C++ [dcl.init.aggr]p12:
1241 //
1242 // [...] Otherwise, if the member is itself a non-empty
1243 // subaggregate, brace elision is assumed and the initializer is
1244 // considered for the initialization of the first member of
1245 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001246 // OpenCL vector initializer is handled elsewhere.
1247 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1248 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001249 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1250 StructuredIndex);
1251 ++StructuredIndex;
1252 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001253 if (!VerifyOnly) {
1254 // We cannot initialize this element, so let
1255 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001256 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001257 /*TopLevelOfInitList=*/true);
1258 }
John McCall5decec92011-02-21 07:57:55 +00001259 hadError = true;
1260 ++Index;
1261 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001262 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001263}
1264
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001265void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1266 InitListExpr *IList, QualType DeclType,
1267 unsigned &Index,
1268 InitListExpr *StructuredList,
1269 unsigned &StructuredIndex) {
1270 assert(Index == 0 && "Index in explicit init list must be zero");
1271
1272 // As an extension, clang supports complex initializers, which initialize
1273 // a complex number component-wise. When an explicit initializer list for
1274 // a complex number contains two two initializers, this extension kicks in:
1275 // it exepcts the initializer list to contain two elements convertible to
1276 // the element type of the complex type. The first element initializes
1277 // the real part, and the second element intitializes the imaginary part.
1278
1279 if (IList->getNumInits() != 2)
1280 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1281 StructuredIndex);
1282
1283 // This is an extension in C. (The builtin _Complex type does not exist
1284 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001285 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001286 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1287 << IList->getSourceRange();
1288
1289 // Initialize the complex number.
1290 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1291 InitializedEntity ElementEntity =
1292 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1293
1294 for (unsigned i = 0; i < 2; ++i) {
1295 ElementEntity.setElementIndex(Index);
1296 CheckSubElementType(ElementEntity, IList, elementType, Index,
1297 StructuredList, StructuredIndex);
1298 }
1299}
1300
Anders Carlsson6cabf312010-01-23 23:23:01 +00001301void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001302 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001303 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001304 InitListExpr *StructuredList,
1305 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001306 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001307 if (!VerifyOnly)
1308 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001309 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001310 diag::warn_cxx98_compat_empty_scalar_initializer :
1311 diag::err_empty_scalar_initializer)
1312 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001313 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001314 ++Index;
1315 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001316 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001317 }
John McCall643169b2010-11-11 00:46:36 +00001318
1319 Expr *expr = IList->getInit(Index);
1320 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001321 // FIXME: This is invalid, and accepting it causes overload resolution
1322 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001323 if (!VerifyOnly)
1324 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001325 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001326 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001327
1328 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1329 StructuredIndex);
1330 return;
1331 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001332 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001333 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001334 diag::err_designator_for_scalar_init)
1335 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001336 hadError = true;
1337 ++Index;
1338 ++StructuredIndex;
1339 return;
1340 }
1341
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001342 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001343 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001344 hadError = true;
1345 ++Index;
1346 return;
1347 }
1348
John McCall643169b2010-11-11 00:46:36 +00001349 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001350 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001351 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001352
Craig Topperc3ec1492014-05-26 06:22:03 +00001353 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001354
1355 if (Result.isInvalid())
1356 hadError = true; // types weren't compatible.
1357 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001358 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
John McCall643169b2010-11-11 00:46:36 +00001360 if (ResultExpr != expr) {
1361 // The type was promoted, update initializer list.
1362 IList->setInit(Index, ResultExpr);
1363 }
1364 }
1365 if (hadError)
1366 ++StructuredIndex;
1367 else
1368 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1369 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001370}
1371
Anders Carlsson6cabf312010-01-23 23:23:01 +00001372void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1373 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001374 unsigned &Index,
1375 InitListExpr *StructuredList,
1376 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001377 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001378 // FIXME: It would be wonderful if we could point at the actual member. In
1379 // general, it would be useful to pass location information down the stack,
1380 // so that we know the location (or decl) of the "current object" being
1381 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001382 if (!VerifyOnly)
1383 SemaRef.Diag(IList->getLocStart(),
1384 diag::err_init_reference_member_uninitialized)
1385 << DeclType
1386 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001387 hadError = true;
1388 ++Index;
1389 ++StructuredIndex;
1390 return;
1391 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001392
1393 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001394 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001395 if (!VerifyOnly)
1396 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1397 << DeclType << IList->getSourceRange();
1398 hadError = true;
1399 ++Index;
1400 ++StructuredIndex;
1401 return;
1402 }
1403
1404 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001405 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001406 hadError = true;
1407 ++Index;
1408 return;
1409 }
1410
1411 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001412 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1413 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001414
1415 if (Result.isInvalid())
1416 hadError = true;
1417
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001418 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001419 IList->setInit(Index, expr);
1420
1421 if (hadError)
1422 ++StructuredIndex;
1423 else
1424 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1425 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001426}
1427
Anders Carlsson6cabf312010-01-23 23:23:01 +00001428void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001429 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001430 unsigned &Index,
1431 InitListExpr *StructuredList,
1432 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001433 const VectorType *VT = DeclType->getAs<VectorType>();
1434 unsigned maxElements = VT->getNumElements();
1435 unsigned numEltsInit = 0;
1436 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001437
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001438 if (Index >= IList->getNumInits()) {
1439 // Make sure the element type can be value-initialized.
1440 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001441 CheckEmptyInitializable(
1442 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1443 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001444 return;
1445 }
1446
David Blaikiebbafb8a2012-03-11 07:00:24 +00001447 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001448 // If the initializing element is a vector, try to copy-initialize
1449 // instead of breaking it apart (which is doomed to failure anyway).
1450 Expr *Init = IList->getInit(Index);
1451 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001452 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001453 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001454 hadError = true;
1455 ++Index;
1456 return;
1457 }
1458
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001459 ExprResult Result =
1460 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1461 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001462
Craig Topperc3ec1492014-05-26 06:22:03 +00001463 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001464 if (Result.isInvalid())
1465 hadError = true; // types weren't compatible.
1466 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001467 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
John McCall6a16b2f2010-10-30 00:11:39 +00001469 if (ResultExpr != Init) {
1470 // The type was promoted, update initializer list.
1471 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001472 }
1473 }
John McCall6a16b2f2010-10-30 00:11:39 +00001474 if (hadError)
1475 ++StructuredIndex;
1476 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001477 UpdateStructuredListElement(StructuredList, StructuredIndex,
1478 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001479 ++Index;
1480 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001481 }
Mike Stump11289f42009-09-09 15:08:12 +00001482
John McCall6a16b2f2010-10-30 00:11:39 +00001483 InitializedEntity ElementEntity =
1484 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
John McCall6a16b2f2010-10-30 00:11:39 +00001486 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1487 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001488 if (Index >= IList->getNumInits()) {
1489 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001490 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001491 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001493
John McCall6a16b2f2010-10-30 00:11:39 +00001494 ElementEntity.setElementIndex(Index);
1495 CheckSubElementType(ElementEntity, IList, elementType, Index,
1496 StructuredList, StructuredIndex);
1497 }
James Molloy9eef2652014-06-20 14:35:13 +00001498
1499 if (VerifyOnly)
1500 return;
1501
1502 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1503 const VectorType *T = Entity.getType()->getAs<VectorType>();
1504 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1505 T->getVectorKind() == VectorType::NeonPolyVector)) {
1506 // The ability to use vector initializer lists is a GNU vector extension
1507 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1508 // endian machines it works fine, however on big endian machines it
1509 // exhibits surprising behaviour:
1510 //
1511 // uint32x2_t x = {42, 64};
1512 // return vget_lane_u32(x, 0); // Will return 64.
1513 //
1514 // Because of this, explicitly call out that it is non-portable.
1515 //
1516 SemaRef.Diag(IList->getLocStart(),
1517 diag::warn_neon_vector_initializer_non_portable);
1518
1519 const char *typeCode;
1520 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1521
1522 if (elementType->isFloatingType())
1523 typeCode = "f";
1524 else if (elementType->isSignedIntegerType())
1525 typeCode = "s";
1526 else if (elementType->isUnsignedIntegerType())
1527 typeCode = "u";
1528 else
1529 llvm_unreachable("Invalid element type!");
1530
1531 SemaRef.Diag(IList->getLocStart(),
1532 SemaRef.Context.getTypeSize(VT) > 64 ?
1533 diag::note_neon_vector_initializer_non_portable_q :
1534 diag::note_neon_vector_initializer_non_portable)
1535 << typeCode << typeSize;
1536 }
1537
John McCall6a16b2f2010-10-30 00:11:39 +00001538 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001539 }
John McCall6a16b2f2010-10-30 00:11:39 +00001540
1541 InitializedEntity ElementEntity =
1542 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543
John McCall6a16b2f2010-10-30 00:11:39 +00001544 // OpenCL initializers allows vectors to be constructed from vectors.
1545 for (unsigned i = 0; i < maxElements; ++i) {
1546 // Don't attempt to go past the end of the init list
1547 if (Index >= IList->getNumInits())
1548 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001549
John McCall6a16b2f2010-10-30 00:11:39 +00001550 ElementEntity.setElementIndex(Index);
1551
1552 QualType IType = IList->getInit(Index)->getType();
1553 if (!IType->isVectorType()) {
1554 CheckSubElementType(ElementEntity, IList, elementType, Index,
1555 StructuredList, StructuredIndex);
1556 ++numEltsInit;
1557 } else {
1558 QualType VecType;
1559 const VectorType *IVT = IType->getAs<VectorType>();
1560 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001561
John McCall6a16b2f2010-10-30 00:11:39 +00001562 if (IType->isExtVectorType())
1563 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1564 else
1565 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001566 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001567 CheckSubElementType(ElementEntity, IList, VecType, Index,
1568 StructuredList, StructuredIndex);
1569 numEltsInit += numIElts;
1570 }
1571 }
1572
1573 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001574 if (numEltsInit != maxElements) {
1575 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001576 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001577 diag::err_vector_incorrect_num_initializers)
1578 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1579 hadError = true;
1580 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001581}
1582
Anders Carlsson6cabf312010-01-23 23:23:01 +00001583void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001584 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001585 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001586 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001587 unsigned &Index,
1588 InitListExpr *StructuredList,
1589 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001590 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1591
Steve Narofff8ecff22008-05-01 22:18:59 +00001592 // Check for the special-case of initializing an array with a string.
1593 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001594 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1595 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001596 // We place the string literal directly into the resulting
1597 // initializer list. This is the only place where the structure
1598 // of the structured initializer list doesn't match exactly,
1599 // because doing so would involve allocating one character
1600 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001601 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001602 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1603 UpdateStructuredListElement(StructuredList, StructuredIndex,
1604 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001605 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1606 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001607 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001608 return;
1609 }
1610 }
John McCall66884dd2011-02-21 07:22:22 +00001611 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001612 // Check for VLAs; in standard C it would be possible to check this
1613 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1614 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001615 if (!VerifyOnly)
1616 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1617 diag::err_variable_object_no_init)
1618 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001619 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001620 ++Index;
1621 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001622 return;
1623 }
1624
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001625 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001626 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1627 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001628 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001629 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001630 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001631 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001632 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001633 maxElementsKnown = true;
1634 }
1635
John McCall66884dd2011-02-21 07:22:22 +00001636 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001637 while (Index < IList->getNumInits()) {
1638 Expr *Init = IList->getInit(Index);
1639 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001640 // If we're not the subobject that matches up with the '{' for
1641 // the designator, we shouldn't be handling the
1642 // designator. Return immediately.
1643 if (!SubobjectIsDesignatorContext)
1644 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001645
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001646 // Handle this designated initializer. elementIndex will be
1647 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001648 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001649 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001650 StructuredList, StructuredIndex, true,
1651 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001652 hadError = true;
1653 continue;
1654 }
1655
Douglas Gregor033d1252009-01-23 16:54:12 +00001656 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001657 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001658 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001659 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001660 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001661
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001662 // If the array is of incomplete type, keep track of the number of
1663 // elements in the initializer.
1664 if (!maxElementsKnown && elementIndex > maxElements)
1665 maxElements = elementIndex;
1666
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001667 continue;
1668 }
1669
1670 // If we know the maximum number of elements, and we've already
1671 // hit it, stop consuming elements in the initializer list.
1672 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001673 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001674
Anders Carlsson6cabf312010-01-23 23:23:01 +00001675 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001677 Entity);
1678 // Check this element.
1679 CheckSubElementType(ElementEntity, IList, elementType, Index,
1680 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001681 ++elementIndex;
1682
1683 // If the array is of incomplete type, keep track of the number of
1684 // elements in the initializer.
1685 if (!maxElementsKnown && elementIndex > maxElements)
1686 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001687 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001688 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001689 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001690 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001691 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001692 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001693 // Sizing an array implicitly to zero is not allowed by ISO C,
1694 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001695 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001696 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001697 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001698
Mike Stump11289f42009-09-09 15:08:12 +00001699 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001700 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001701 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001702 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001703 // If there are any members of the array that get value-initialized, check
1704 // that is possible. That happens if we know the bound and don't have
1705 // enough elements, or if we're performing an array new with an unknown
1706 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001707 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001708 if ((maxElementsKnown && elementIndex < maxElements) ||
1709 Entity.isVariableLengthArrayNew())
Richard Smith454a7cd2014-06-03 08:26:00 +00001710 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1711 SemaRef.Context, 0, Entity),
1712 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001713 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001714}
1715
Eli Friedman3fa64df2011-08-23 22:24:57 +00001716bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1717 Expr *InitExpr,
1718 FieldDecl *Field,
1719 bool TopLevelObject) {
1720 // Handle GNU flexible array initializers.
1721 unsigned FlexArrayDiag;
1722 if (isa<InitListExpr>(InitExpr) &&
1723 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1724 // Empty flexible array init always allowed as an extension
1725 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001726 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001727 // Disallow flexible array init in C++; it is not required for gcc
1728 // compatibility, and it needs work to IRGen correctly in general.
1729 FlexArrayDiag = diag::err_flexible_array_init;
1730 } else if (!TopLevelObject) {
1731 // Disallow flexible array init on non-top-level object
1732 FlexArrayDiag = diag::err_flexible_array_init;
1733 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1734 // Disallow flexible array init on anything which is not a variable.
1735 FlexArrayDiag = diag::err_flexible_array_init;
1736 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1737 // Disallow flexible array init on local variables.
1738 FlexArrayDiag = diag::err_flexible_array_init;
1739 } else {
1740 // Allow other cases.
1741 FlexArrayDiag = diag::ext_flexible_array_init;
1742 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001743
1744 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001745 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001746 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001747 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001748 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1749 << Field;
1750 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001751
1752 return FlexArrayDiag != diag::ext_flexible_array_init;
1753}
1754
Richard Smith872307e2016-03-08 22:17:41 +00001755void InitListChecker::CheckStructUnionTypes(
1756 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1757 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1758 bool SubobjectIsDesignatorContext, unsigned &Index,
1759 InitListExpr *StructuredList, unsigned &StructuredIndex,
1760 bool TopLevelObject) {
1761 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001762
Eli Friedman23a9e312008-05-19 19:16:24 +00001763 // If the record is invalid, some of it's members are invalid. To avoid
1764 // confusion, we forgo checking the intializer for the entire record.
1765 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001766 // Assume it was supposed to consume a single initializer.
1767 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001768 hadError = true;
1769 return;
Mike Stump11289f42009-09-09 15:08:12 +00001770 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001771
1772 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001773 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001774
1775 // If there's a default initializer, use it.
1776 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1777 if (VerifyOnly)
1778 return;
1779 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1780 Field != FieldEnd; ++Field) {
1781 if (Field->hasInClassInitializer()) {
1782 StructuredList->setInitializedFieldInUnion(*Field);
1783 // FIXME: Actually build a CXXDefaultInitExpr?
1784 return;
1785 }
1786 }
1787 }
1788
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001789 // Value-initialize the first member of the union that isn't an unnamed
1790 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001791 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1792 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001793 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001794 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001795 CheckEmptyInitializable(
1796 InitializedEntity::InitializeMember(*Field, &Entity),
1797 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001798 else
David Blaikie40ed2972012-06-06 20:45:41 +00001799 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001800 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001801 }
1802 }
1803 return;
1804 }
1805
Richard Smith872307e2016-03-08 22:17:41 +00001806 bool InitializedSomething = false;
1807
1808 // If we have any base classes, they are initialized prior to the fields.
1809 for (auto &Base : Bases) {
1810 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1811 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1812
1813 // Designated inits always initialize fields, so if we see one, all
1814 // remaining base classes have no explicit initializer.
1815 if (Init && isa<DesignatedInitExpr>(Init))
1816 Init = nullptr;
1817
1818 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1819 SemaRef.Context, &Base, false, &Entity);
1820 if (Init) {
1821 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1822 StructuredList, StructuredIndex);
1823 InitializedSomething = true;
1824 } else if (VerifyOnly) {
1825 CheckEmptyInitializable(BaseEntity, InitLoc);
1826 }
1827 }
1828
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001829 // If structDecl is a forward declaration, this loop won't do
1830 // anything except look at designated initializers; That's okay,
1831 // because an error should get printed out elsewhere. It might be
1832 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001833 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001834 RecordDecl::field_iterator FieldEnd = RD->field_end();
John McCalle40b58e2010-03-11 19:32:38 +00001835 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001836 while (Index < IList->getNumInits()) {
1837 Expr *Init = IList->getInit(Index);
1838
1839 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001840 // If we're not the subobject that matches up with the '{' for
1841 // the designator, we shouldn't be handling the
1842 // designator. Return immediately.
1843 if (!SubobjectIsDesignatorContext)
1844 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001845
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001846 // Handle this designated initializer. Field will be updated to
1847 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001848 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001849 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001850 StructuredList, StructuredIndex,
1851 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001852 hadError = true;
1853
Douglas Gregora9add4e2009-02-12 19:00:39 +00001854 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001855
1856 // Disable check for missing fields when designators are used.
1857 // This matches gcc behaviour.
1858 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001859 continue;
1860 }
1861
1862 if (Field == FieldEnd) {
1863 // We've run out of fields. We're done.
1864 break;
1865 }
1866
Douglas Gregora9add4e2009-02-12 19:00:39 +00001867 // We've already initialized a member of a union. We're done.
1868 if (InitializedSomething && DeclType->isUnionType())
1869 break;
1870
Douglas Gregor91f84212008-12-11 16:49:14 +00001871 // If we've hit the flexible array member at the end, we're done.
1872 if (Field->getType()->isIncompleteArrayType())
1873 break;
1874
Douglas Gregor51695702009-01-29 16:53:55 +00001875 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001876 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001877 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001878 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001879 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001880
Douglas Gregora82064c2011-06-29 21:51:31 +00001881 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001882 bool InvalidUse;
1883 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00001884 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001885 else
David Blaikie40ed2972012-06-06 20:45:41 +00001886 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001887 IList->getInit(Index)->getLocStart());
1888 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001889 ++Index;
1890 ++Field;
1891 hadError = true;
1892 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001893 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001894
Anders Carlsson6cabf312010-01-23 23:23:01 +00001895 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001896 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001897 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1898 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001899 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001900
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001901 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001902 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001903 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001904 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905
1906 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001907 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001908
John McCalle40b58e2010-03-11 19:32:38 +00001909 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001910 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1911 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1912 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001913 // It is possible we have one or more unnamed bitfields remaining.
1914 // Find first (if any) named field and emit warning.
1915 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1916 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001917 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001918 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001919 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001920 break;
1921 }
1922 }
1923 }
1924
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001925 // Check that any remaining fields can be value-initialized.
1926 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1927 !Field->getType()->isIncompleteArrayType()) {
1928 // FIXME: Should check for holes left by designated initializers too.
1929 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001930 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001931 CheckEmptyInitializable(
1932 InitializedEntity::InitializeMember(*Field, &Entity),
1933 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001934 }
1935 }
1936
Mike Stump11289f42009-09-09 15:08:12 +00001937 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001938 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001939 return;
1940
David Blaikie40ed2972012-06-06 20:45:41 +00001941 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001942 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001943 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001944 ++Index;
1945 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001946 }
1947
Anders Carlsson6cabf312010-01-23 23:23:01 +00001948 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001949 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001950
Anders Carlsson6cabf312010-01-23 23:23:01 +00001951 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001953 StructuredList, StructuredIndex);
1954 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001955 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001956 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001957}
Steve Narofff8ecff22008-05-01 22:18:59 +00001958
Douglas Gregord5846a12009-04-15 06:41:24 +00001959/// \brief Expand a field designator that refers to a member of an
1960/// anonymous struct or union into a series of field designators that
1961/// refers to the field within the appropriate subobject.
1962///
Douglas Gregord5846a12009-04-15 06:41:24 +00001963static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001964 DesignatedInitExpr *DIE,
1965 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001966 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001967 typedef DesignatedInitExpr::Designator Designator;
1968
Douglas Gregord5846a12009-04-15 06:41:24 +00001969 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001970 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001971 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1972 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1973 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001974 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001975 DIE->getDesignator(DesigIdx)->getDotLoc(),
1976 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1977 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001978 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1979 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001980 assert(isa<FieldDecl>(*PI));
1981 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001982 }
1983
1984 // Expand the current designator into the set of replacement
1985 // designators, so we have a full subobject path down to where the
1986 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001987 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001988 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001989}
Mike Stump11289f42009-09-09 15:08:12 +00001990
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001991static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1992 DesignatedInitExpr *DIE) {
1993 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1994 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1995 for (unsigned I = 0; I < NumIndexExprs; ++I)
1996 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00001997 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
1998 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001999 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002000 DIE->usesGNUSyntax(), DIE->getInit());
2001}
2002
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002003namespace {
2004
2005// Callback to only accept typo corrections that are for field members of
2006// the given struct or union.
2007class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2008 public:
2009 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2010 : Record(RD) {}
2011
Craig Toppere14c0f82014-03-12 04:55:44 +00002012 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002013 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2014 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2015 }
2016
2017 private:
2018 RecordDecl *Record;
2019};
2020
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002021} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002022
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002023/// @brief Check the well-formedness of a C99 designated initializer.
2024///
2025/// Determines whether the designated initializer @p DIE, which
2026/// resides at the given @p Index within the initializer list @p
2027/// IList, is well-formed for a current object of type @p DeclType
2028/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002029/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002030/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002031///
2032/// @param IList The initializer list in which this designated
2033/// initializer occurs.
2034///
Douglas Gregora5324162009-04-15 04:56:10 +00002035/// @param DIE The designated initializer expression.
2036///
2037/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002038///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002039/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002040/// into which the designation in @p DIE should refer.
2041///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002042/// @param NextField If non-NULL and the first designator in @p DIE is
2043/// a field, this will be set to the field declaration corresponding
2044/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002045///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002046/// @param NextElementIndex If non-NULL and the first designator in @p
2047/// DIE is an array designator or GNU array-range designator, this
2048/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002049///
2050/// @param Index Index into @p IList where the designated initializer
2051/// @p DIE occurs.
2052///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002053/// @param StructuredList The initializer list expression that
2054/// describes all of the subobject initializers in the order they'll
2055/// actually be initialized.
2056///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002057/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002058bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002059InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002060 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002061 DesignatedInitExpr *DIE,
2062 unsigned DesigIdx,
2063 QualType &CurrentObjectType,
2064 RecordDecl::field_iterator *NextField,
2065 llvm::APSInt *NextElementIndex,
2066 unsigned &Index,
2067 InitListExpr *StructuredList,
2068 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002069 bool FinishSubobjectInit,
2070 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002071 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002072 // Check the actual initialization for the designated object type.
2073 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002074
2075 // Temporarily remove the designator expression from the
2076 // initializer list that the child calls see, so that we don't try
2077 // to re-process the designator.
2078 unsigned OldIndex = Index;
2079 IList->setInit(OldIndex, DIE->getInit());
2080
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002081 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002082 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002083
2084 // Restore the designated initializer expression in the syntactic
2085 // form of the initializer list.
2086 if (IList->getInit(OldIndex) != DIE->getInit())
2087 DIE->setInit(IList->getInit(OldIndex));
2088 IList->setInit(OldIndex, DIE);
2089
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002090 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002091 }
2092
Douglas Gregora5324162009-04-15 04:56:10 +00002093 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002094 bool IsFirstDesignator = (DesigIdx == 0);
2095 if (!VerifyOnly) {
2096 assert((IsFirstDesignator || StructuredList) &&
2097 "Need a non-designated initializer list to start from");
2098
2099 // Determine the structural initializer list that corresponds to the
2100 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002101 if (IsFirstDesignator)
2102 StructuredList = SyntacticToSemantic.lookup(IList);
2103 else {
2104 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2105 StructuredList->getInit(StructuredIndex) : nullptr;
2106 if (!ExistingInit && StructuredList->hasArrayFiller())
2107 ExistingInit = StructuredList->getArrayFiller();
2108
2109 if (!ExistingInit)
2110 StructuredList =
2111 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2112 StructuredList, StructuredIndex,
2113 SourceRange(D->getLocStart(),
2114 DIE->getLocEnd()));
2115 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2116 StructuredList = Result;
2117 else {
2118 if (DesignatedInitUpdateExpr *E =
2119 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2120 StructuredList = E->getUpdater();
2121 else {
2122 DesignatedInitUpdateExpr *DIUE =
2123 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2124 D->getLocStart(), ExistingInit,
2125 DIE->getLocEnd());
2126 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2127 StructuredList = DIUE->getUpdater();
2128 }
2129
2130 // We need to check on source range validity because the previous
2131 // initializer does not have to be an explicit initializer. e.g.,
2132 //
2133 // struct P { int a, b; };
2134 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2135 //
2136 // There is an overwrite taking place because the first braced initializer
2137 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2138 if (ExistingInit->getSourceRange().isValid()) {
2139 // We are creating an initializer list that initializes the
2140 // subobjects of the current object, but there was already an
2141 // initialization that completely initialized the current
2142 // subobject, e.g., by a compound literal:
2143 //
2144 // struct X { int a, b; };
2145 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2146 //
2147 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2148 // designated initializer re-initializes the whole
2149 // subobject [0], overwriting previous initializers.
2150 SemaRef.Diag(D->getLocStart(),
2151 diag::warn_subobject_initializer_overrides)
2152 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2153
2154 SemaRef.Diag(ExistingInit->getLocStart(),
2155 diag::note_previous_initializer)
2156 << /*FIXME:has side effects=*/0
2157 << ExistingInit->getSourceRange();
2158 }
2159 }
2160 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002161 assert(StructuredList && "Expected a structured initializer list");
2162 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002163
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002164 if (D->isFieldDesignator()) {
2165 // C99 6.7.8p7:
2166 //
2167 // If a designator has the form
2168 //
2169 // . identifier
2170 //
2171 // then the current object (defined below) shall have
2172 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002173 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002174 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002175 if (!RT) {
2176 SourceLocation Loc = D->getDotLoc();
2177 if (Loc.isInvalid())
2178 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002179 if (!VerifyOnly)
2180 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002181 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002182 ++Index;
2183 return true;
2184 }
2185
Douglas Gregord5846a12009-04-15 06:41:24 +00002186 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002187 if (!KnownField) {
2188 IdentifierInfo *FieldName = D->getFieldName();
2189 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2190 for (NamedDecl *ND : Lookup) {
2191 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2192 KnownField = FD;
2193 break;
2194 }
2195 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002196 // In verify mode, don't modify the original.
2197 if (VerifyOnly)
2198 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002199 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002200 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002201 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002202 break;
2203 }
2204 }
David Majnemer36ef8982014-08-11 18:33:59 +00002205 if (!KnownField) {
2206 if (VerifyOnly) {
2207 ++Index;
2208 return true; // No typo correction when just trying this out.
2209 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002210
David Majnemer36ef8982014-08-11 18:33:59 +00002211 // Name lookup found something, but it wasn't a field.
2212 if (!Lookup.empty()) {
2213 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2214 << FieldName;
2215 SemaRef.Diag(Lookup.front()->getLocation(),
2216 diag::note_field_designator_found);
2217 ++Index;
2218 return true;
2219 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002220
David Majnemer36ef8982014-08-11 18:33:59 +00002221 // Name lookup didn't find anything.
2222 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002223 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2224 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002225 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002226 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2227 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002228 SemaRef.diagnoseTypo(
2229 Corrected,
2230 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002231 << FieldName << CurrentObjectType);
2232 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002233 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002234 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002235 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002236 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2237 << FieldName << CurrentObjectType;
2238 ++Index;
2239 return true;
2240 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002241 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002242 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002243
David Majnemer58e4ea92014-08-23 01:48:50 +00002244 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002245
2246 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2247 FieldIndex = CXXRD->getNumBases();
2248
David Majnemer58e4ea92014-08-23 01:48:50 +00002249 for (auto *FI : RT->getDecl()->fields()) {
2250 if (FI->isUnnamedBitfield())
2251 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002252 if (declaresSameEntity(KnownField, FI)) {
2253 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002254 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002255 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002256 ++FieldIndex;
2257 }
2258
David Majnemer36ef8982014-08-11 18:33:59 +00002259 RecordDecl::field_iterator Field =
2260 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2261
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002262 // All of the fields of a union are located at the same place in
2263 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002264 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002265 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002266 if (!VerifyOnly) {
2267 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002268 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002269 assert(StructuredList->getNumInits() == 1
2270 && "A union should never have more than one initializer!");
2271
Richard Smithfe1bc702016-04-08 19:57:40 +00002272 // We're about to throw away an initializer, emit warning.
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002273 SemaRef.Diag(D->getFieldLoc(),
2274 diag::warn_initializer_overrides)
2275 << D->getSourceRange();
2276 Expr *ExistingInit = StructuredList->getInit(0);
2277 SemaRef.Diag(ExistingInit->getLocStart(),
2278 diag::note_previous_initializer)
2279 << /*FIXME:has side effects=*/0
2280 << ExistingInit->getSourceRange();
2281
2282 // remove existing initializer
2283 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002284 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002285 }
2286
David Blaikie40ed2972012-06-06 20:45:41 +00002287 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002288 }
Douglas Gregor51695702009-01-29 16:53:55 +00002289 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002290
Douglas Gregora82064c2011-06-29 21:51:31 +00002291 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002292 bool InvalidUse;
2293 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002294 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002295 else
David Blaikie40ed2972012-06-06 20:45:41 +00002296 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002297 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002298 ++Index;
2299 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002300 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002301
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002302 if (!VerifyOnly) {
2303 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002304 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002305
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002306 // Make sure that our non-designated initializer list has space
2307 // for a subobject corresponding to this field.
2308 if (FieldIndex >= StructuredList->getNumInits())
2309 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2310 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002311
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002312 // This designator names a flexible array member.
2313 if (Field->getType()->isIncompleteArrayType()) {
2314 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002315 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002316 // We can't designate an object within the flexible array
2317 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002318 if (!VerifyOnly) {
2319 DesignatedInitExpr::Designator *NextD
2320 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002321 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002322 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002323 << SourceRange(NextD->getLocStart(),
2324 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002325 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002326 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002327 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002328 Invalid = true;
2329 }
2330
Chris Lattner001b29c2010-10-10 17:49:49 +00002331 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2332 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002333 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002334 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002335 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002336 diag::err_flexible_array_init_needs_braces)
2337 << DIE->getInit()->getSourceRange();
2338 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002339 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002340 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002341 Invalid = true;
2342 }
2343
Eli Friedman3fa64df2011-08-23 22:24:57 +00002344 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002345 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002346 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002347 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002348
2349 if (Invalid) {
2350 ++Index;
2351 return true;
2352 }
2353
2354 // Initialize the array.
2355 bool prevHadError = hadError;
2356 unsigned newStructuredIndex = FieldIndex;
2357 unsigned OldIndex = Index;
2358 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002359
2360 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002361 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002362 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002363 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002364
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002365 IList->setInit(OldIndex, DIE);
2366 if (hadError && !prevHadError) {
2367 ++Field;
2368 ++FieldIndex;
2369 if (NextField)
2370 *NextField = Field;
2371 StructuredIndex = FieldIndex;
2372 return true;
2373 }
2374 } else {
2375 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002376 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002377 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002378
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002379 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002380 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002381 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002382 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002383 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002384 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002385 return true;
2386 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002387
2388 // Find the position of the next field to be initialized in this
2389 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002390 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002391 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002392
2393 // If this the first designator, our caller will continue checking
2394 // the rest of this struct/class/union subobject.
2395 if (IsFirstDesignator) {
2396 if (NextField)
2397 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002398 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002399 return false;
2400 }
2401
Douglas Gregor17bd0942009-01-28 23:36:17 +00002402 if (!FinishSubobjectInit)
2403 return false;
2404
Douglas Gregord5846a12009-04-15 06:41:24 +00002405 // We've already initialized something in the union; we're done.
2406 if (RT->getDecl()->isUnion())
2407 return hadError;
2408
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002409 // Check the remaining fields within this class/struct/union subobject.
2410 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002411
Richard Smith872307e2016-03-08 22:17:41 +00002412 auto NoBases =
2413 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2414 CXXRecordDecl::base_class_iterator());
2415 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2416 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002417 return hadError && !prevHadError;
2418 }
2419
2420 // C99 6.7.8p6:
2421 //
2422 // If a designator has the form
2423 //
2424 // [ constant-expression ]
2425 //
2426 // then the current object (defined below) shall have array
2427 // type and the expression shall be an integer constant
2428 // expression. If the array is of unknown size, any
2429 // nonnegative value is valid.
2430 //
2431 // Additionally, cope with the GNU extension that permits
2432 // designators of the form
2433 //
2434 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002435 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002436 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002437 if (!VerifyOnly)
2438 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2439 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002440 ++Index;
2441 return true;
2442 }
2443
Craig Topperc3ec1492014-05-26 06:22:03 +00002444 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002445 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2446 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002447 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002448 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002449 DesignatedEndIndex = DesignatedStartIndex;
2450 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002451 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002452
Mike Stump11289f42009-09-09 15:08:12 +00002453 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002454 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002455 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002456 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002457 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002458
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002459 // Codegen can't handle evaluating array range designators that have side
2460 // effects, because we replicate the AST value for each initialized element.
2461 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2462 // elements with something that has a side effect, so codegen can emit an
2463 // "error unsupported" error instead of miscompiling the app.
2464 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002465 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002466 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002467 }
2468
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002469 if (isa<ConstantArrayType>(AT)) {
2470 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002471 DesignatedStartIndex
2472 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002473 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002474 DesignatedEndIndex
2475 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002476 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2477 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002478 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002479 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002480 diag::err_array_designator_too_large)
2481 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2482 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002483 ++Index;
2484 return true;
2485 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002486 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002487 unsigned DesignatedIndexBitWidth =
2488 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2489 DesignatedStartIndex =
2490 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2491 DesignatedEndIndex =
2492 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002493 DesignatedStartIndex.setIsUnsigned(true);
2494 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002495 }
Mike Stump11289f42009-09-09 15:08:12 +00002496
Eli Friedman1f16b742013-06-11 21:48:11 +00002497 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2498 // We're modifying a string literal init; we have to decompose the string
2499 // so we can modify the individual characters.
2500 ASTContext &Context = SemaRef.Context;
2501 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2502
2503 // Compute the character type
2504 QualType CharTy = AT->getElementType();
2505
2506 // Compute the type of the integer literals.
2507 QualType PromotedCharTy = CharTy;
2508 if (CharTy->isPromotableIntegerType())
2509 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2510 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2511
2512 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2513 // Get the length of the string.
2514 uint64_t StrLen = SL->getLength();
2515 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2516 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2517 StructuredList->resizeInits(Context, StrLen);
2518
2519 // Build a literal for each character in the string, and put them into
2520 // the init list.
2521 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2522 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2523 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002524 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002525 if (CharTy != PromotedCharTy)
2526 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002527 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002528 StructuredList->updateInit(Context, i, Init);
2529 }
2530 } else {
2531 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2532 std::string Str;
2533 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2534
2535 // Get the length of the string.
2536 uint64_t StrLen = Str.size();
2537 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2538 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2539 StructuredList->resizeInits(Context, StrLen);
2540
2541 // Build a literal for each character in the string, and put them into
2542 // the init list.
2543 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2544 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2545 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002546 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002547 if (CharTy != PromotedCharTy)
2548 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002549 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002550 StructuredList->updateInit(Context, i, Init);
2551 }
2552 }
2553 }
2554
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002555 // Make sure that our non-designated initializer list has space
2556 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002557 if (!VerifyOnly &&
2558 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002559 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002560 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002561
Douglas Gregor17bd0942009-01-28 23:36:17 +00002562 // Repeatedly perform subobject initializations in the range
2563 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002564
Douglas Gregor17bd0942009-01-28 23:36:17 +00002565 // Move to the next designator
2566 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2567 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002568
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002569 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002570 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002571
Douglas Gregor17bd0942009-01-28 23:36:17 +00002572 while (DesignatedStartIndex <= DesignatedEndIndex) {
2573 // Recurse to check later designated subobjects.
2574 QualType ElementType = AT->getElementType();
2575 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002577 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002578 if (CheckDesignatedInitializer(
2579 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2580 nullptr, Index, StructuredList, ElementIndex,
2581 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2582 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002583 return true;
2584
2585 // Move to the next index in the array that we'll be initializing.
2586 ++DesignatedStartIndex;
2587 ElementIndex = DesignatedStartIndex.getZExtValue();
2588 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002589
2590 // If this the first designator, our caller will continue checking
2591 // the rest of this array subobject.
2592 if (IsFirstDesignator) {
2593 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002594 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002595 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002596 return false;
2597 }
Mike Stump11289f42009-09-09 15:08:12 +00002598
Douglas Gregor17bd0942009-01-28 23:36:17 +00002599 if (!FinishSubobjectInit)
2600 return false;
2601
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002602 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002603 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002604 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002605 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002606 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002607 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002608}
2609
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002610// Get the structured initializer list for a subobject of type
2611// @p CurrentObjectType.
2612InitListExpr *
2613InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2614 QualType CurrentObjectType,
2615 InitListExpr *StructuredList,
2616 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002617 SourceRange InitRange,
2618 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002619 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002620 return nullptr; // No structured list in verification-only mode.
2621 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002622 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002623 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002624 else if (StructuredIndex < StructuredList->getNumInits())
2625 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002626
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002627 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002628 // There might have already been initializers for subobjects of the current
2629 // object, but a subsequent initializer list will overwrite the entirety
2630 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2631 //
2632 // struct P { char x[6]; };
2633 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2634 //
2635 // The first designated initializer is ignored, and l.x is just "f".
2636 if (!IsFullyOverwritten)
2637 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002638
2639 if (ExistingInit) {
2640 // We are creating an initializer list that initializes the
2641 // subobjects of the current object, but there was already an
2642 // initialization that completely initialized the current
2643 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002644 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002645 // struct X { int a, b; };
2646 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002647 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002648 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2649 // designated initializer re-initializes the whole
2650 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002651 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002652 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002653 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002654 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002655 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002656 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002657 << ExistingInit->getSourceRange();
2658 }
2659
Mike Stump11289f42009-09-09 15:08:12 +00002660 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002661 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002662 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002663 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002664
Eli Friedman91f5ae52012-02-23 02:25:10 +00002665 QualType ResultType = CurrentObjectType;
2666 if (!ResultType->isArrayType())
2667 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2668 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002669
Douglas Gregor6d00c992009-03-20 23:58:33 +00002670 // Pre-allocate storage for the structured initializer list.
2671 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002672 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002673 bool GotNumInits = false;
2674 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002675 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002676 GotNumInits = true;
2677 } else if (Index < IList->getNumInits()) {
2678 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002679 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002680 GotNumInits = true;
2681 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002682 }
2683
Mike Stump11289f42009-09-09 15:08:12 +00002684 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002685 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2686 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2687 NumElements = CAType->getSize().getZExtValue();
2688 // Simple heuristic so that we don't allocate a very large
2689 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002690 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002691 NumElements = 0;
2692 }
John McCall9dd450b2009-09-21 23:43:11 +00002693 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002694 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002695 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002696 RecordDecl *RDecl = RType->getDecl();
2697 if (RDecl->isUnion())
2698 NumElements = 1;
2699 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002700 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002701 }
2702
Ted Kremenekac034612010-04-13 23:39:13 +00002703 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002704
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002705 // Link this new initializer list into the structured initializer
2706 // lists.
2707 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002708 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002709 else {
2710 Result->setSyntacticForm(IList);
2711 SyntacticToSemantic[IList] = Result;
2712 }
2713
2714 return Result;
2715}
2716
2717/// Update the initializer at index @p StructuredIndex within the
2718/// structured initializer list to the value @p expr.
2719void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2720 unsigned &StructuredIndex,
2721 Expr *expr) {
2722 // No structured initializer list to update
2723 if (!StructuredList)
2724 return;
2725
Ted Kremenekac034612010-04-13 23:39:13 +00002726 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2727 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002728 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002729 // We need to check on source range validity because the previous
2730 // initializer does not have to be an explicit initializer.
2731 // struct P { int a, b; };
2732 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2733 // There is an overwrite taking place because the first braced initializer
2734 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2735 if (PrevInit->getSourceRange().isValid()) {
2736 SemaRef.Diag(expr->getLocStart(),
2737 diag::warn_initializer_overrides)
2738 << expr->getSourceRange();
2739
2740 SemaRef.Diag(PrevInit->getLocStart(),
2741 diag::note_previous_initializer)
2742 << /*FIXME:has side effects=*/0
2743 << PrevInit->getSourceRange();
2744 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002745 }
Mike Stump11289f42009-09-09 15:08:12 +00002746
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002747 ++StructuredIndex;
2748}
2749
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002750/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002751/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002752/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002753/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002754/// failure. Returns the index expression, possibly with an implicit cast
2755/// added, on success. If everything went okay, Value will receive the
2756/// value of the constant expression.
2757static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002758CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002759 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002760
2761 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002762 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2763 if (Result.isInvalid())
2764 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002765
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002766 if (Value.isSigned() && Value.isNegative())
2767 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002768 << Value.toString(10) << Index->getSourceRange();
2769
Douglas Gregor51650d32009-01-23 21:04:18 +00002770 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002771 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002772}
2773
John McCalldadc5752010-08-24 06:29:42 +00002774ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002775 SourceLocation Loc,
2776 bool GNUSyntax,
2777 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002778 typedef DesignatedInitExpr::Designator ASTDesignator;
2779
2780 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002781 SmallVector<ASTDesignator, 32> Designators;
2782 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002783
2784 // Build designators and check array designator expressions.
2785 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2786 const Designator &D = Desig.getDesignator(Idx);
2787 switch (D.getKind()) {
2788 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002789 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002790 D.getFieldLoc()));
2791 break;
2792
2793 case Designator::ArrayDesignator: {
2794 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2795 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002796 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002797 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002798 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002799 Invalid = true;
2800 else {
2801 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002802 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002803 D.getRBracketLoc()));
2804 InitExpressions.push_back(Index);
2805 }
2806 break;
2807 }
2808
2809 case Designator::ArrayRangeDesignator: {
2810 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2811 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2812 llvm::APSInt StartValue;
2813 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002814 bool StartDependent = StartIndex->isTypeDependent() ||
2815 StartIndex->isValueDependent();
2816 bool EndDependent = EndIndex->isTypeDependent() ||
2817 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002818 if (!StartDependent)
2819 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002820 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002821 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002822 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002823
2824 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002825 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002826 else {
2827 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002828 if (StartDependent || EndDependent) {
2829 // Nothing to compute.
2830 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002831 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002832 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002833 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002834
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002835 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002836 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002837 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002838 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2839 Invalid = true;
2840 } else {
2841 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002842 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002843 D.getEllipsisLoc(),
2844 D.getRBracketLoc()));
2845 InitExpressions.push_back(StartIndex);
2846 InitExpressions.push_back(EndIndex);
2847 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002848 }
2849 break;
2850 }
2851 }
2852 }
2853
2854 if (Invalid || Init.isInvalid())
2855 return ExprError();
2856
2857 // Clear out the expressions within the designation.
2858 Desig.ClearExprs(*this);
2859
2860 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002861 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00002862 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002863 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002864 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002865
David Blaikiebbafb8a2012-03-11 07:00:24 +00002866 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002867 Diag(DIE->getLocStart(), diag::ext_designated_init)
2868 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002869
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002870 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002871}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002872
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002873//===----------------------------------------------------------------------===//
2874// Initialization entity
2875//===----------------------------------------------------------------------===//
2876
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002877InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002878 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002879 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002880{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002881 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2882 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002883 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002884 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002885 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002886 Type = VT->getElementType();
2887 } else {
2888 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2889 assert(CT && "Unexpected type");
2890 Kind = EK_ComplexElement;
2891 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002892 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002893}
2894
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002895InitializedEntity
2896InitializedEntity::InitializeBase(ASTContext &Context,
2897 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00002898 bool IsInheritedVirtualBase,
2899 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002900 InitializedEntity Result;
2901 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00002902 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002903 Result.Base = reinterpret_cast<uintptr_t>(Base);
2904 if (IsInheritedVirtualBase)
2905 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002906
Douglas Gregor1b303932009-12-22 15:35:07 +00002907 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002908 return Result;
2909}
2910
Douglas Gregor85dabae2009-12-16 01:38:02 +00002911DeclarationName InitializedEntity::getName() const {
2912 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002913 case EK_Parameter:
2914 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002915 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2916 return (D ? D->getDeclName() : DeclarationName());
2917 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002918
2919 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002920 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002921 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002922 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002923
Douglas Gregor19666fb2012-02-15 16:57:26 +00002924 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002925 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002926
Douglas Gregor85dabae2009-12-16 01:38:02 +00002927 case EK_Result:
2928 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002929 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002930 case EK_Temporary:
2931 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002932 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002933 case EK_ArrayElement:
2934 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002935 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002936 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002937 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002938 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002939 return DeclarationName();
2940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002941
David Blaikie8a40f702012-01-17 06:56:22 +00002942 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002943}
2944
Richard Smith7873de02016-08-11 22:25:46 +00002945ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00002946 switch (getKind()) {
2947 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002948 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002949 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002950 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002951
John McCall31168b02011-06-15 23:02:42 +00002952 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002953 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002954 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2955
Douglas Gregora4b592a2009-12-19 03:01:41 +00002956 case EK_Result:
2957 case EK_Exception:
2958 case EK_New:
2959 case EK_Temporary:
2960 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002961 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002962 case EK_ArrayElement:
2963 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002964 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002965 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002966 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002967 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002968 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002969 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002971
David Blaikie8a40f702012-01-17 06:56:22 +00002972 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002973}
2974
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002975bool InitializedEntity::allowsNRVO() const {
2976 switch (getKind()) {
2977 case EK_Result:
2978 case EK_Exception:
2979 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002981 case EK_Variable:
2982 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002983 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002984 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002985 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002986 case EK_New:
2987 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002988 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002989 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002990 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002991 case EK_ArrayElement:
2992 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002993 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002994 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002995 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002996 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002997 break;
2998 }
2999
3000 return false;
3001}
3002
Richard Smithe6c01442013-06-05 00:46:14 +00003003unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003004 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003005 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3006 for (unsigned I = 0; I != Depth; ++I)
3007 OS << "`-";
3008
3009 switch (getKind()) {
3010 case EK_Variable: OS << "Variable"; break;
3011 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003012 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3013 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003014 case EK_Result: OS << "Result"; break;
3015 case EK_Exception: OS << "Exception"; break;
3016 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003017 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003018 case EK_New: OS << "New"; break;
3019 case EK_Temporary: OS << "Temporary"; break;
3020 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003021 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003022 case EK_Base: OS << "Base"; break;
3023 case EK_Delegating: OS << "Delegating"; break;
3024 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3025 case EK_VectorElement: OS << "VectorElement " << Index; break;
3026 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3027 case EK_BlockElement: OS << "Block"; break;
3028 case EK_LambdaCapture:
3029 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003030 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003031 break;
3032 }
3033
Richard Smith7873de02016-08-11 22:25:46 +00003034 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003035 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003036 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003037 }
3038
3039 OS << " '" << getType().getAsString() << "'\n";
3040
3041 return Depth + 1;
3042}
3043
Yaron Kerencdae9412016-01-29 19:38:18 +00003044LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003045 dumpImpl(llvm::errs());
3046}
3047
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003048//===----------------------------------------------------------------------===//
3049// Initialization sequence
3050//===----------------------------------------------------------------------===//
3051
3052void InitializationSequence::Step::Destroy() {
3053 switch (Kind) {
3054 case SK_ResolveAddressOfOverloadedFunction:
3055 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003056 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003057 case SK_CastDerivedToBaseLValue:
3058 case SK_BindReference:
3059 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003060 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003061 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003062 case SK_UserConversion:
3063 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003064 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003065 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003066 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003067 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003068 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003069 case SK_UnwrapInitList:
3070 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003071 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003072 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003073 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003074 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003075 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003076 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003077 case SK_ArrayLoopIndex:
3078 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003079 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003080 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003081 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003082 case SK_PassByIndirectCopyRestore:
3083 case SK_PassByIndirectRestore:
3084 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003085 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003086 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003087 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003088 case SK_OCLZeroEvent:
Egor Churaev89831422016-12-23 14:55:49 +00003089 case SK_OCLZeroQueue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003090 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003091
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003092 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003093 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003094 delete ICS;
3095 }
3096}
3097
Douglas Gregor838fcc32010-03-26 20:14:36 +00003098bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003099 // There can be some lvalue adjustments after the SK_BindReference step.
3100 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3101 if (I->Kind == SK_BindReference)
3102 return true;
3103 if (I->Kind == SK_BindReferenceToTemporary)
3104 return false;
3105 }
3106 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003107}
3108
3109bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003110 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003111 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112
Douglas Gregor838fcc32010-03-26 20:14:36 +00003113 switch (getFailureKind()) {
3114 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003115 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003116 case FK_ArrayNeedsInitList:
3117 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003118 case FK_ArrayNeedsInitListOrWideStringLiteral:
3119 case FK_NarrowStringIntoWideCharArray:
3120 case FK_WideStringIntoCharArray:
3121 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003122 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3123 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003124 case FK_NonConstLValueReferenceBindingToBitfield:
3125 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003126 case FK_NonConstLValueReferenceBindingToUnrelated:
3127 case FK_RValueReferenceBindingToLValue:
3128 case FK_ReferenceInitDropsQualifiers:
3129 case FK_ReferenceInitFailed:
3130 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003131 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003132 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003133 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003134 case FK_ReferenceBindingToInitList:
3135 case FK_InitListBadDestinationType:
3136 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003137 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003138 case FK_ArrayTypeMismatch:
3139 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003140 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003141 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003142 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003143 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003144 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003145 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146
Douglas Gregor838fcc32010-03-26 20:14:36 +00003147 case FK_ReferenceInitOverloadFailed:
3148 case FK_UserConversionOverloadFailed:
3149 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003150 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003151 return FailedOverloadResult == OR_Ambiguous;
3152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
David Blaikie8a40f702012-01-17 06:56:22 +00003154 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003155}
3156
Douglas Gregorb33eed02010-04-16 22:09:46 +00003157bool InitializationSequence::isConstructorInitialization() const {
3158 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3159}
3160
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003161void
3162InitializationSequence
3163::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3164 DeclAccessPair Found,
3165 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003166 Step S;
3167 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3168 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003169 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003170 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003171 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003172 Steps.push_back(S);
3173}
3174
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003176 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003177 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003178 switch (VK) {
3179 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3180 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3181 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003182 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003183 S.Type = BaseType;
3184 Steps.push_back(S);
3185}
3186
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003188 bool BindingTemporary) {
3189 Step S;
3190 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3191 S.Type = T;
3192 Steps.push_back(S);
3193}
3194
Richard Smithb8c0f552016-12-09 18:49:13 +00003195void InitializationSequence::AddFinalCopy(QualType T) {
3196 Step S;
3197 S.Kind = SK_FinalCopy;
3198 S.Type = T;
3199 Steps.push_back(S);
3200}
3201
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003202void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3203 Step S;
3204 S.Kind = SK_ExtraneousCopyToTemporary;
3205 S.Type = T;
3206 Steps.push_back(S);
3207}
3208
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003209void
3210InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3211 DeclAccessPair FoundDecl,
3212 QualType T,
3213 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003214 Step S;
3215 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003216 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003217 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003218 S.Function.Function = Function;
3219 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003220 Steps.push_back(S);
3221}
3222
3223void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003224 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003225 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003226 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003227 switch (VK) {
3228 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003229 S.Kind = SK_QualificationConversionRValue;
3230 break;
John McCall2536c6d2010-08-25 10:28:54 +00003231 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003232 S.Kind = SK_QualificationConversionXValue;
3233 break;
John McCall2536c6d2010-08-25 10:28:54 +00003234 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003235 S.Kind = SK_QualificationConversionLValue;
3236 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003237 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 S.Type = Ty;
3239 Steps.push_back(S);
3240}
3241
Richard Smith77be48a2014-07-31 06:31:19 +00003242void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3243 Step S;
3244 S.Kind = SK_AtomicConversion;
3245 S.Type = Ty;
3246 Steps.push_back(S);
3247}
3248
Jordan Roseb1312a52013-04-11 00:58:58 +00003249void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3250 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3251
3252 Step S;
3253 S.Kind = SK_LValueToRValue;
3254 S.Type = Ty;
3255 Steps.push_back(S);
3256}
3257
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003258void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003259 const ImplicitConversionSequence &ICS, QualType T,
3260 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003261 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003262 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3263 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003264 S.Type = T;
3265 S.ICS = new ImplicitConversionSequence(ICS);
3266 Steps.push_back(S);
3267}
3268
Douglas Gregor51e77d52009-12-10 17:56:55 +00003269void InitializationSequence::AddListInitializationStep(QualType T) {
3270 Step S;
3271 S.Kind = SK_ListInitialization;
3272 S.Type = T;
3273 Steps.push_back(S);
3274}
3275
Richard Smith55c28882016-05-12 23:45:49 +00003276void InitializationSequence::AddConstructorInitializationStep(
3277 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3278 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003279 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003280 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003281 : SK_ConstructorInitializationFromList
3282 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003283 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003284 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003285 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003286 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003287 Steps.push_back(S);
3288}
3289
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003290void InitializationSequence::AddZeroInitializationStep(QualType T) {
3291 Step S;
3292 S.Kind = SK_ZeroInitialization;
3293 S.Type = T;
3294 Steps.push_back(S);
3295}
3296
Douglas Gregore1314a62009-12-18 05:02:21 +00003297void InitializationSequence::AddCAssignmentStep(QualType T) {
3298 Step S;
3299 S.Kind = SK_CAssignment;
3300 S.Type = T;
3301 Steps.push_back(S);
3302}
3303
Eli Friedman78275202009-12-19 08:11:05 +00003304void InitializationSequence::AddStringInitStep(QualType T) {
3305 Step S;
3306 S.Kind = SK_StringInit;
3307 S.Type = T;
3308 Steps.push_back(S);
3309}
3310
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003311void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3312 Step S;
3313 S.Kind = SK_ObjCObjectConversion;
3314 S.Type = T;
3315 Steps.push_back(S);
3316}
3317
Richard Smith378b8c82016-12-14 03:22:16 +00003318void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003319 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003320 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003321 S.Type = T;
3322 Steps.push_back(S);
3323}
3324
Richard Smith410306b2016-12-12 02:53:20 +00003325void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3326 Step S;
3327 S.Kind = SK_ArrayLoopIndex;
3328 S.Type = EltT;
3329 Steps.insert(Steps.begin(), S);
3330
3331 S.Kind = SK_ArrayLoopInit;
3332 S.Type = T;
3333 Steps.push_back(S);
3334}
3335
Richard Smithebeed412012-02-15 22:38:09 +00003336void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3337 Step S;
3338 S.Kind = SK_ParenthesizedArrayInit;
3339 S.Type = T;
3340 Steps.push_back(S);
3341}
3342
John McCall31168b02011-06-15 23:02:42 +00003343void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3344 bool shouldCopy) {
3345 Step s;
3346 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3347 : SK_PassByIndirectRestore);
3348 s.Type = type;
3349 Steps.push_back(s);
3350}
3351
3352void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3353 Step S;
3354 S.Kind = SK_ProduceObjCObject;
3355 S.Type = T;
3356 Steps.push_back(S);
3357}
3358
Sebastian Redlc1839b12012-01-17 22:49:42 +00003359void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3360 Step S;
3361 S.Kind = SK_StdInitializerList;
3362 S.Type = T;
3363 Steps.push_back(S);
3364}
3365
Guy Benyei61054192013-02-07 10:55:47 +00003366void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3367 Step S;
3368 S.Kind = SK_OCLSamplerInit;
3369 S.Type = T;
3370 Steps.push_back(S);
3371}
3372
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003373void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3374 Step S;
3375 S.Kind = SK_OCLZeroEvent;
3376 S.Type = T;
3377 Steps.push_back(S);
3378}
3379
Egor Churaev89831422016-12-23 14:55:49 +00003380void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3381 Step S;
3382 S.Kind = SK_OCLZeroQueue;
3383 S.Type = T;
3384 Steps.push_back(S);
3385}
3386
Sebastian Redl29526f02011-11-27 16:50:07 +00003387void InitializationSequence::RewrapReferenceInitList(QualType T,
3388 InitListExpr *Syntactic) {
3389 assert(Syntactic->getNumInits() == 1 &&
3390 "Can only rewrap trivial init lists.");
3391 Step S;
3392 S.Kind = SK_UnwrapInitList;
3393 S.Type = Syntactic->getInit(0)->getType();
3394 Steps.insert(Steps.begin(), S);
3395
3396 S.Kind = SK_RewrapInitList;
3397 S.Type = T;
3398 S.WrappingSyntacticList = Syntactic;
3399 Steps.push_back(S);
3400}
3401
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003403 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003404 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003405 this->Failure = Failure;
3406 this->FailedOverloadResult = Result;
3407}
3408
3409//===----------------------------------------------------------------------===//
3410// Attempt initialization
3411//===----------------------------------------------------------------------===//
3412
Nico Weber337d5aa2015-04-17 08:32:38 +00003413/// Tries to add a zero initializer. Returns true if that worked.
3414static bool
3415maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3416 const InitializedEntity &Entity) {
3417 if (Entity.getKind() != InitializedEntity::EK_Variable)
3418 return false;
3419
3420 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3421 if (VD->getInit() || VD->getLocEnd().isMacroID())
3422 return false;
3423
3424 QualType VariableTy = VD->getType().getCanonicalType();
3425 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3426 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3427 if (!Init.empty()) {
3428 Sequence.AddZeroInitializationStep(Entity.getType());
3429 Sequence.SetZeroInitializationFixit(Init, Loc);
3430 return true;
3431 }
3432 return false;
3433}
3434
John McCall31168b02011-06-15 23:02:42 +00003435static void MaybeProduceObjCObject(Sema &S,
3436 InitializationSequence &Sequence,
3437 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003438 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003439
3440 /// When initializing a parameter, produce the value if it's marked
3441 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003442 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003443 if (!Entity.isParameterConsumed())
3444 return;
3445
3446 assert(Entity.getType()->isObjCRetainableType() &&
3447 "consuming an object of unretainable type?");
3448 Sequence.AddProduceObjCObjectStep(Entity.getType());
3449
3450 /// When initializing a return value, if the return type is a
3451 /// retainable type, then returns need to immediately retain the
3452 /// object. If an autorelease is required, it will be done at the
3453 /// last instant.
3454 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3455 if (!Entity.getType()->isObjCRetainableType())
3456 return;
3457
3458 Sequence.AddProduceObjCObjectStep(Entity.getType());
3459 }
3460}
3461
Richard Smithcc1b96d2013-06-12 22:31:48 +00003462static void TryListInitialization(Sema &S,
3463 const InitializedEntity &Entity,
3464 const InitializationKind &Kind,
3465 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003466 InitializationSequence &Sequence,
3467 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003468
Richard Smithd86812d2012-07-05 08:39:21 +00003469/// \brief When initializing from init list via constructor, handle
3470/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003471///
Richard Smithd86812d2012-07-05 08:39:21 +00003472/// \return true if we have handled initialization of an object of type
3473/// std::initializer_list<T>, false otherwise.
3474static bool TryInitializerListConstruction(Sema &S,
3475 InitListExpr *List,
3476 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003477 InitializationSequence &Sequence,
3478 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003479 QualType E;
3480 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003481 return false;
3482
Richard Smithdb0ac552015-12-18 22:40:25 +00003483 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003484 Sequence.setIncompleteTypeFailure(E);
3485 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003486 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003487
3488 // Try initializing a temporary array from the init list.
3489 QualType ArrayType = S.Context.getConstantArrayType(
3490 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3491 List->getNumInits()),
3492 clang::ArrayType::Normal, 0);
3493 InitializedEntity HiddenArray =
3494 InitializedEntity::InitializeTemporary(ArrayType);
3495 InitializationKind Kind =
3496 InitializationKind::CreateDirectList(List->getExprLoc());
Manman Ren073db022016-03-10 18:53:19 +00003497 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3498 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003499 if (Sequence)
3500 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003501 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003502}
3503
Richard Smith7c2bcc92016-09-07 02:14:33 +00003504/// Determine if the constructor has the signature of a copy or move
3505/// constructor for the type T of the class in which it was found. That is,
3506/// determine if its first parameter is of type T or reference to (possibly
3507/// cv-qualified) T.
3508static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3509 const ConstructorInfo &Info) {
3510 if (Info.Constructor->getNumParams() == 0)
3511 return false;
3512
3513 QualType ParmT =
3514 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3515 QualType ClassT =
3516 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3517
3518 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3519}
3520
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003521static OverloadingResult
3522ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003523 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003524 OverloadCandidateSet &CandidateSet,
Richard Smith40c78062015-02-21 02:31:57 +00003525 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003526 OverloadCandidateSet::iterator &Best,
3527 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003528 bool OnlyListConstructors, bool IsListInit,
3529 bool SecondStepOfCopyInit = false) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003530 CandidateSet.clear();
3531
Richard Smith40c78062015-02-21 02:31:57 +00003532 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003533 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003534 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003535 continue;
3536
Richard Smith7c2bcc92016-09-07 02:14:33 +00003537 if (!AllowExplicit && Info.Constructor->isExplicit())
3538 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003539
Richard Smith7c2bcc92016-09-07 02:14:33 +00003540 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3541 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003542
Richard Smith7c2bcc92016-09-07 02:14:33 +00003543 // C++11 [over.best.ics]p4:
3544 // ... and the constructor or user-defined conversion function is a
3545 // candidate by
3546 // - 13.3.1.3, when the argument is the temporary in the second step
3547 // of a class copy-initialization, or
3548 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3549 // - the second phase of 13.3.1.7 when the initializer list has exactly
3550 // one element that is itself an initializer list, and the target is
3551 // the first parameter of a constructor of class X, and the conversion
3552 // is to X or reference to (possibly cv-qualified X),
3553 // user-defined conversion sequences are not considered.
3554 bool SuppressUserConversions =
3555 SecondStepOfCopyInit ||
3556 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3557 hasCopyOrMoveCtorParam(S.Context, Info));
3558
3559 if (Info.ConstructorTmpl)
3560 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3561 /*ExplicitArgs*/ nullptr, Args,
3562 CandidateSet, SuppressUserConversions);
3563 else {
3564 // C++ [over.match.copy]p1:
3565 // - When initializing a temporary to be bound to the first parameter
3566 // of a constructor [for type T] that takes a reference to possibly
3567 // cv-qualified T as its first argument, called with a single
3568 // argument in the context of direct-initialization, explicit
3569 // conversion functions are also considered.
3570 // FIXME: What if a constructor template instantiates to such a signature?
3571 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3572 Args.size() == 1 &&
3573 hasCopyOrMoveCtorParam(S.Context, Info);
3574 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3575 CandidateSet, SuppressUserConversions,
3576 /*PartialOverloading=*/false,
3577 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003578 }
3579 }
3580
3581 // Perform overload resolution and return the result.
3582 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3583}
3584
Sebastian Redled2e5322011-12-22 14:44:04 +00003585/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3586/// enumerates the constructors of the initialized entity and performs overload
3587/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003588/// \param DestType The destination class type.
3589/// \param DestArrayType The destination type, which is either DestType or
3590/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003591/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003592/// \param IsInitListCopy Is this non-list-initialization resulting from a
3593/// list-initialization from {x} where x is the same
3594/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003595static void TryConstructorInitialization(Sema &S,
3596 const InitializedEntity &Entity,
3597 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003598 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003599 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003600 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003601 bool IsListInit = false,
3602 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003603 assert(((!IsListInit && !IsInitListCopy) ||
3604 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3605 "IsListInit/IsInitListCopy must come with a single initializer list "
3606 "argument.");
3607 InitListExpr *ILE =
3608 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3609 MultiExprArg UnwrappedArgs =
3610 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003611
Sebastian Redled2e5322011-12-22 14:44:04 +00003612 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003613 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003614 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003615 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003616 }
3617
Richard Smith122f88d2016-12-06 23:52:28 +00003618 // C++1z [dcl.init]p17:
3619 // - If the initializer expression is a prvalue and the cv-unqualified
3620 // version of the source type is the same class as the class of the
3621 // destination, the initializer expression is used to initialize the
3622 // destination object.
3623 // Per DR (no number yet), this does not apply when initializing a base
3624 // class or delegating to another constructor from a mem-initializer.
3625 if (S.getLangOpts().CPlusPlus1z &&
3626 Entity.getKind() != InitializedEntity::EK_Base &&
3627 Entity.getKind() != InitializedEntity::EK_Delegating &&
3628 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3629 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3630 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003631 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003632 if (ILE)
3633 Sequence.RewrapReferenceInitList(DestType, ILE);
3634 return;
3635 }
3636
Sebastian Redled2e5322011-12-22 14:44:04 +00003637 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3638 assert(DestRecordType && "Constructor initialization requires record type");
3639 CXXRecordDecl *DestRecordDecl
3640 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3641
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003642 // Build the candidate set directly in the initialization sequence
3643 // structure, so that it will persist if we fail.
3644 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3645
3646 // Determine whether we are allowed to call explicit constructors or
3647 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003648 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003649 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003650
Sebastian Redled2e5322011-12-22 14:44:04 +00003651 // - Otherwise, if T is a class type, constructors are considered. The
3652 // applicable constructors are enumerated, and the best one is chosen
3653 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003654 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003655
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003656 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003657 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003658 bool AsInitializerList = false;
3659
Larisse Voufo19d08672015-01-27 18:47:05 +00003660 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003661 // When objects of non-aggregate type T are list-initialized, such that
3662 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3663 // according to the rules in this section, overload resolution selects
3664 // the constructor in two phases:
3665 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003666 // - Initially, the candidate functions are the initializer-list
3667 // constructors of the class T and the argument list consists of the
3668 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003669 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003670 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003671
3672 // If the initializer list has no elements and T has a default constructor,
3673 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003674 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003675 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003676 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003677 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003678 /*OnlyListConstructor=*/true,
3679 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003680 }
3681
3682 // C++11 [over.match.list]p1:
3683 // - If no viable initializer-list constructor is found, overload resolution
3684 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003685 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003686 // elements of the initializer list.
3687 if (Result == OR_No_Viable_Function) {
3688 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003689 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003690 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003691 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003692 /*OnlyListConstructors=*/false,
3693 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003694 }
3695 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003696 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003697 InitializationSequence::FK_ListConstructorOverloadFailed :
3698 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003699 Result);
3700 return;
3701 }
3702
Richard Smithd86812d2012-07-05 08:39:21 +00003703 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003704 // If a program calls for the default initialization of an object
3705 // of a const-qualified type T, T shall be a class type with a
3706 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003707 // C++ core issue 253 proposal:
3708 // If the implicit default constructor initializes all subobjects, no
3709 // initializer should be required.
3710 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3711 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003712 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003713 Entity.getType().isConstQualified()) {
3714 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3715 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3716 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3717 return;
3718 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003719 }
3720
Sebastian Redl048a6d72012-04-01 19:54:59 +00003721 // C++11 [over.match.list]p1:
3722 // In copy-list-initialization, if an explicit constructor is chosen, the
3723 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003724 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003725 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3726 return;
3727 }
3728
Sebastian Redled2e5322011-12-22 14:44:04 +00003729 // Add the constructor initialization step. Any cv-qualification conversion is
3730 // subsumed by the initialization.
3731 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithed83ebd2015-02-05 07:02:11 +00003732 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003733 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003734 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003735}
3736
Sebastian Redl29526f02011-11-27 16:50:07 +00003737static bool
3738ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3739 Expr *Initializer,
3740 QualType &SourceType,
3741 QualType &UnqualifiedSourceType,
3742 QualType UnqualifiedTargetType,
3743 InitializationSequence &Sequence) {
3744 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3745 S.Context.OverloadTy) {
3746 DeclAccessPair Found;
3747 bool HadMultipleCandidates = false;
3748 if (FunctionDecl *Fn
3749 = S.ResolveAddressOfOverloadedFunction(Initializer,
3750 UnqualifiedTargetType,
3751 false, Found,
3752 &HadMultipleCandidates)) {
3753 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3754 HadMultipleCandidates);
3755 SourceType = Fn->getType();
3756 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3757 } else if (!UnqualifiedTargetType->isRecordType()) {
3758 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3759 return true;
3760 }
3761 }
3762 return false;
3763}
3764
3765static void TryReferenceInitializationCore(Sema &S,
3766 const InitializedEntity &Entity,
3767 const InitializationKind &Kind,
3768 Expr *Initializer,
3769 QualType cv1T1, QualType T1,
3770 Qualifiers T1Quals,
3771 QualType cv2T2, QualType T2,
3772 Qualifiers T2Quals,
3773 InitializationSequence &Sequence);
3774
Richard Smithd86812d2012-07-05 08:39:21 +00003775static void TryValueInitialization(Sema &S,
3776 const InitializedEntity &Entity,
3777 const InitializationKind &Kind,
3778 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003779 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003780
Sebastian Redl29526f02011-11-27 16:50:07 +00003781/// \brief Attempt list initialization of a reference.
3782static void TryReferenceListInitialization(Sema &S,
3783 const InitializedEntity &Entity,
3784 const InitializationKind &Kind,
3785 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003786 InitializationSequence &Sequence,
3787 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003788 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003789 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003790 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3791 return;
3792 }
David Majnemer9370dc22015-04-26 07:35:03 +00003793 // Can't reference initialize a compound literal.
3794 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3795 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3796 return;
3797 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003798
3799 QualType DestType = Entity.getType();
3800 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3801 Qualifiers T1Quals;
3802 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3803
3804 // Reference initialization via an initializer list works thus:
3805 // If the initializer list consists of a single element that is
3806 // reference-related to the referenced type, bind directly to that element
3807 // (possibly creating temporaries).
3808 // Otherwise, initialize a temporary with the initializer list and
3809 // bind to that.
3810 if (InitList->getNumInits() == 1) {
3811 Expr *Initializer = InitList->getInit(0);
3812 QualType cv2T2 = Initializer->getType();
3813 Qualifiers T2Quals;
3814 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3815
3816 // If this fails, creating a temporary wouldn't work either.
3817 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3818 T1, Sequence))
3819 return;
3820
3821 SourceLocation DeclLoc = Initializer->getLocStart();
3822 bool dummy1, dummy2, dummy3;
3823 Sema::ReferenceCompareResult RefRelationship
3824 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3825 dummy2, dummy3);
3826 if (RefRelationship >= Sema::Ref_Related) {
3827 // Try to bind the reference here.
3828 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3829 T1Quals, cv2T2, T2, T2Quals, Sequence);
3830 if (Sequence)
3831 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3832 return;
3833 }
Richard Smith03d93932013-01-15 07:58:29 +00003834
3835 // Update the initializer if we've resolved an overloaded function.
3836 if (Sequence.step_begin() != Sequence.step_end())
3837 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003838 }
3839
3840 // Not reference-related. Create a temporary and bind to that.
3841 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3842
Manman Ren073db022016-03-10 18:53:19 +00003843 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3844 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00003845 if (Sequence) {
3846 if (DestType->isRValueReferenceType() ||
3847 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3848 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3849 else
3850 Sequence.SetFailed(
3851 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3852 }
3853}
3854
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003855/// \brief Attempt list initialization (C++0x [dcl.init.list])
3856static void TryListInitialization(Sema &S,
3857 const InitializedEntity &Entity,
3858 const InitializationKind &Kind,
3859 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003860 InitializationSequence &Sequence,
3861 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003862 QualType DestType = Entity.getType();
3863
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003864 // C++ doesn't allow scalar initialization with more than one argument.
3865 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003866 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003867 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3868 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3869 return;
3870 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003871 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00003872 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
3873 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003874 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003875 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003876
Larisse Voufod2010992015-01-24 23:09:54 +00003877 if (DestType->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00003878 !S.isCompleteType(InitList->getLocStart(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00003879 Sequence.setIncompleteTypeFailure(DestType);
3880 return;
3881 }
Richard Smithd86812d2012-07-05 08:39:21 +00003882
Larisse Voufo19d08672015-01-27 18:47:05 +00003883 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003884 // - If T is a class type and the initializer list has a single element of
3885 // type cv U, where U is T or a class derived from T, the object is
3886 // initialized from that element (by copy-initialization for
3887 // copy-list-initialization, or by direct-initialization for
3888 // direct-list-initialization).
3889 // - Otherwise, if T is a character array and the initializer list has a
3890 // single element that is an appropriately-typed string literal
3891 // (8.5.2 [dcl.init.string]), initialization is performed as described
3892 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003893 // - Otherwise, if T is an aggregate, [...] (continue below).
3894 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003895 if (DestType->isRecordType()) {
3896 QualType InitType = InitList->getInit(0)->getType();
3897 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00003898 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00003899 Expr *InitListAsExpr = InitList;
3900 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003901 DestType, Sequence,
3902 /*InitListSyntax*/false,
3903 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00003904 return;
3905 }
3906 }
3907 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3908 Expr *SubInit[1] = {InitList->getInit(0)};
3909 if (!isa<VariableArrayType>(DestAT) &&
3910 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3911 InitializationKind SubKind =
3912 Kind.getKind() == InitializationKind::IK_DirectList
3913 ? InitializationKind::CreateDirect(Kind.getLocation(),
3914 InitList->getLBraceLoc(),
3915 InitList->getRBraceLoc())
3916 : Kind;
3917 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00003918 /*TopLevelOfInitList*/ true,
3919 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00003920
3921 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3922 // the element is not an appropriately-typed string literal, in which
3923 // case we should proceed as in C++11 (below).
3924 if (Sequence) {
3925 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3926 return;
3927 }
3928 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003929 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003930 }
Larisse Voufod2010992015-01-24 23:09:54 +00003931
3932 // C++11 [dcl.init.list]p3:
3933 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00003934 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
3935 (S.getLangOpts().CPlusPlus11 &&
3936 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00003937 if (S.getLangOpts().CPlusPlus11) {
3938 // - Otherwise, if the initializer list has no elements and T is a
3939 // class type with a default constructor, the object is
3940 // value-initialized.
3941 if (InitList->getNumInits() == 0) {
3942 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3943 if (RD->hasDefaultConstructor()) {
3944 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3945 return;
3946 }
3947 }
3948
3949 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3950 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00003951 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
3952 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00003953 return;
3954
3955 // - Otherwise, if T is a class type, constructors are considered.
3956 Expr *InitListAsExpr = InitList;
3957 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003958 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00003959 } else
3960 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3961 return;
3962 }
3963
Richard Smith089c3162013-09-21 21:55:46 +00003964 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00003965 InitList->getNumInits() == 1) {
3966 Expr *E = InitList->getInit(0);
3967
3968 // - Otherwise, if T is an enumeration with a fixed underlying type,
3969 // the initializer-list has a single element v, and the initialization
3970 // is direct-list-initialization, the object is initialized with the
3971 // value T(v); if a narrowing conversion is required to convert v to
3972 // the underlying type of T, the program is ill-formed.
3973 auto *ET = DestType->getAs<EnumType>();
3974 if (S.getLangOpts().CPlusPlus1z &&
3975 Kind.getKind() == InitializationKind::IK_DirectList &&
3976 ET && ET->getDecl()->isFixed() &&
3977 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
3978 (E->getType()->isIntegralOrEnumerationType() ||
3979 E->getType()->isFloatingType())) {
3980 // There are two ways that T(v) can work when T is an enumeration type.
3981 // If there is either an implicit conversion sequence from v to T or
3982 // a conversion function that can convert from v to T, then we use that.
3983 // Otherwise, if v is of integral, enumeration, or floating-point type,
3984 // it is converted to the enumeration type via its underlying type.
3985 // There is no overlap possible between these two cases (except when the
3986 // source value is already of the destination type), and the first
3987 // case is handled by the general case for single-element lists below.
3988 ImplicitConversionSequence ICS;
3989 ICS.setStandard();
3990 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00003991 if (!E->isRValue())
3992 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00003993 // If E is of a floating-point type, then the conversion is ill-formed
3994 // due to narrowing, but go through the motions in order to produce the
3995 // right diagnostic.
3996 ICS.Standard.Second = E->getType()->isFloatingType()
3997 ? ICK_Floating_Integral
3998 : ICK_Integral_Conversion;
3999 ICS.Standard.setFromType(E->getType());
4000 ICS.Standard.setToType(0, E->getType());
4001 ICS.Standard.setToType(1, DestType);
4002 ICS.Standard.setToType(2, DestType);
4003 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4004 /*TopLevelOfInitList*/true);
4005 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4006 return;
4007 }
4008
Richard Smith089c3162013-09-21 21:55:46 +00004009 // - Otherwise, if the initializer list has a single element of type E
4010 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004011 // initialized from that element (by copy-initialization for
4012 // copy-list-initialization, or by direct-initialization for
4013 // direct-list-initialization); if a narrowing conversion is required
4014 // to convert the element to T, the program is ill-formed.
4015 //
Richard Smith089c3162013-09-21 21:55:46 +00004016 // Per core-24034, this is direct-initialization if we were performing
4017 // direct-list-initialization and copy-initialization otherwise.
4018 // We can't use InitListChecker for this, because it always performs
4019 // copy-initialization. This only matters if we might use an 'explicit'
4020 // conversion operator, so we only need to handle the cases where the source
4021 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004022 if (InitList->getInit(0)->getType()->isRecordType()) {
4023 InitializationKind SubKind =
4024 Kind.getKind() == InitializationKind::IK_DirectList
4025 ? InitializationKind::CreateDirect(Kind.getLocation(),
4026 InitList->getLBraceLoc(),
4027 InitList->getRBraceLoc())
4028 : Kind;
4029 Expr *SubInit[1] = { InitList->getInit(0) };
4030 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4031 /*TopLevelOfInitList*/true,
4032 TreatUnavailableAsInvalid);
4033 if (Sequence)
4034 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4035 return;
4036 }
Richard Smith089c3162013-09-21 21:55:46 +00004037 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004038
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004039 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004040 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004041 if (CheckInitList.HadError()) {
4042 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4043 return;
4044 }
4045
4046 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004047 Sequence.AddListInitializationStep(DestType);
4048}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004049
4050/// \brief Try a reference initialization that involves calling a conversion
4051/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004052static OverloadingResult TryRefInitWithConversionFunction(
4053 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4054 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4055 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004056 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4058 QualType T1 = cv1T1.getUnqualifiedType();
4059 QualType cv2T2 = Initializer->getType();
4060 QualType T2 = cv2T2.getUnqualifiedType();
4061
4062 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004063 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004064 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004066 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004067 ObjCConversion,
4068 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004069 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004070 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004071 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004072 (void)ObjCLifetimeConversion;
4073
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004074 // Build the candidate set directly in the initialization sequence
4075 // structure, so that it will persist if we fail.
4076 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4077 CandidateSet.clear();
4078
4079 // Determine whether we are allowed to call explicit constructors or
4080 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004081 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00004082 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4083
Craig Topperc3ec1492014-05-26 06:22:03 +00004084 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004085 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004086 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004087 // The type we're converting to is a class type. Enumerate its constructors
4088 // to see if there is a suitable conversion.
4089 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004090
Richard Smith40c78062015-02-21 02:31:57 +00004091 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004092 auto Info = getConstructorInfo(D);
4093 if (!Info.Constructor)
4094 continue;
John McCalla0296f72010-03-19 07:35:19 +00004095
Richard Smithc2bebe92016-05-11 20:37:46 +00004096 if (!Info.Constructor->isInvalidDecl() &&
4097 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4098 if (Info.ConstructorTmpl)
4099 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004100 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004101 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004102 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004103 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004104 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004105 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004106 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004109 }
John McCall3696dcb2010-08-17 07:23:57 +00004110 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4111 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004112
Craig Topperc3ec1492014-05-26 06:22:03 +00004113 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004114 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004115 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004116 // The type we're converting from is a class type, enumerate its conversion
4117 // functions.
4118 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4119
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004120 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4121 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004122 NamedDecl *D = *I;
4123 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4124 if (isa<UsingShadowDecl>(D))
4125 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004127 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4128 CXXConversionDecl *Conv;
4129 if (ConvTemplate)
4130 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4131 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004132 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004134 // If the conversion function doesn't return a reference type,
4135 // it can't be considered for this conversion unless we're allowed to
4136 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137 // FIXME: Do we need to make sure that we only consider conversion
4138 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004139 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004140 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004141 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4142 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004143 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004144 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004145 DestType, CandidateSet,
4146 /*AllowObjCConversionOnExplicit=*/
4147 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004148 else
John McCalla0296f72010-03-19 07:35:19 +00004149 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004150 Initializer, DestType, CandidateSet,
4151 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004152 }
4153 }
4154 }
John McCall3696dcb2010-08-17 07:23:57 +00004155 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4156 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004157
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004158 SourceLocation DeclLoc = Initializer->getLocStart();
4159
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004161 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004163 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004164 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004165
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004166 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004167 // This is the overload that will be used for this initialization step if we
4168 // use this initialization. Mark it as referenced.
4169 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004170
Richard Smithb8c0f552016-12-09 18:49:13 +00004171 // Compute the returned type and value kind of the conversion.
4172 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004173 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004174 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004175 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004176 cv3T3 = T1;
4177
4178 ExprValueKind VK = VK_RValue;
4179 if (cv3T3->isLValueReferenceType())
4180 VK = VK_LValue;
4181 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4182 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4183 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004184
4185 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004186 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004187 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004188 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004189
Richard Smithb8c0f552016-12-09 18:49:13 +00004190 // Determine whether we'll need to perform derived-to-base adjustments or
4191 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004192 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004193 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004194 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004195 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004196 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004197 NewDerivedToBase, NewObjCConversion,
4198 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004199
4200 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004201 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004202 assert(!isa<CXXConstructorDecl>(Function) &&
4203 "should not have conversion after constructor");
4204
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004205 ImplicitConversionSequence ICS;
4206 ICS.setStandard();
4207 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004208 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4209
4210 // Every implicit conversion results in a prvalue, except for a glvalue
4211 // derived-to-base conversion, which we handle below.
4212 cv3T3 = ICS.Standard.getToType(2);
4213 VK = VK_RValue;
4214 }
4215
4216 // If the converted initializer is a prvalue, its type T4 is adjusted to
4217 // type "cv1 T4" and the temporary materialization conversion is applied.
4218 //
4219 // We adjust the cv-qualifications to match the reference regardless of
4220 // whether we have a prvalue so that the AST records the change. In this
4221 // case, T4 is "cv3 T3".
4222 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4223 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4224 Sequence.AddQualificationConversionStep(cv1T4, VK);
4225 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4226 VK = IsLValueRef ? VK_LValue : VK_XValue;
4227
4228 if (NewDerivedToBase)
4229 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004230 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004231 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004232
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004233 return OR_Success;
4234}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235
Richard Smithc620f552011-10-19 16:55:56 +00004236static void CheckCXX98CompatAccessibleCopy(Sema &S,
4237 const InitializedEntity &Entity,
4238 Expr *CurInitExpr);
4239
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4241static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004242 const InitializedEntity &Entity,
4243 const InitializationKind &Kind,
4244 Expr *Initializer,
4245 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004246 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004247 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004248 Qualifiers T1Quals;
4249 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004250 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004251 Qualifiers T2Quals;
4252 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004253
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004254 // If the initializer is the address of an overloaded function, try
4255 // to resolve the overloaded function. If all goes well, T2 is the
4256 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004257 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4258 T1, Sequence))
4259 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004260
Sebastian Redl29526f02011-11-27 16:50:07 +00004261 // Delegate everything else to a subfunction.
4262 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4263 T1Quals, cv2T2, T2, T2Quals, Sequence);
4264}
4265
Richard Smithb8c0f552016-12-09 18:49:13 +00004266/// Determine whether an expression is a non-referenceable glvalue (one to
4267/// which a reference can never bind). Attemting to bind a reference to
4268/// such a glvalue will always create a temporary.
4269static bool isNonReferenceableGLValue(Expr *E) {
4270 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004271}
4272
Sebastian Redl29526f02011-11-27 16:50:07 +00004273/// \brief Reference initialization without resolving overloaded functions.
4274static void TryReferenceInitializationCore(Sema &S,
4275 const InitializedEntity &Entity,
4276 const InitializationKind &Kind,
4277 Expr *Initializer,
4278 QualType cv1T1, QualType T1,
4279 Qualifiers T1Quals,
4280 QualType cv2T2, QualType T2,
4281 Qualifiers T2Quals,
4282 InitializationSequence &Sequence) {
4283 QualType DestType = Entity.getType();
4284 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 // Compute some basic properties of the types and the initializer.
4286 bool isLValueRef = DestType->isLValueReferenceType();
4287 bool isRValueRef = !isLValueRef;
4288 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004289 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004290 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004291 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004292 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004293 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004294 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004295
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004296 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 // "cv2 T2" as follows:
4299 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004301 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004302 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004303 // there are no function rvalues in C++, rvalue refs to functions are treated
4304 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004305 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004306 bool T1Function = T1->isFunctionType();
4307 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004308 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004309 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004311 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004313 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004314 if (T1Quals != T2Quals)
4315 // Convert to cv1 T2. This should only add qualifiers unless this is a
4316 // c-style cast. The removal of qualifiers in that case notionally
4317 // happens after the reference binding, but that doesn't matter.
4318 Sequence.AddQualificationConversionStep(
4319 S.Context.getQualifiedType(T2, T1Quals),
4320 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004321 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004322 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004323 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004324 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004325
Richard Smithb8c0f552016-12-09 18:49:13 +00004326 // We only create a temporary here when binding a reference to a
4327 // bit-field or vector element. Those cases are't supposed to be
4328 // handled by this bullet, but the outcome is the same either way.
4329 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004330 return;
4331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332
4333 // - has a class type (i.e., T2 is a class type), where T1 is not
4334 // reference-related to T2, and can be implicitly converted to an
4335 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4336 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004337 // applicable conversion functions (13.3.1.6) and choosing the best
4338 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004339 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004340 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004341 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4342 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004343 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004344 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4345 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004346 if (ConvOvlResult == OR_Success)
4347 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004348 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004349 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004350 InitializationSequence::FK_ReferenceInitOverloadFailed,
4351 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004352 }
4353 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004354
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004356 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004357 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004358 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004359 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4360 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4361 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004362 Sequence.SetOverloadFailure(
4363 InitializationSequence::FK_ReferenceInitOverloadFailed,
4364 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004365 else if (!InitCategory.isLValue())
4366 Sequence.SetFailed(
4367 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4368 else {
4369 InitializationSequence::FailureKind FK;
4370 switch (RefRelationship) {
4371 case Sema::Ref_Compatible:
4372 if (Initializer->refersToBitField())
4373 FK = InitializationSequence::
4374 FK_NonConstLValueReferenceBindingToBitfield;
4375 else if (Initializer->refersToVectorElement())
4376 FK = InitializationSequence::
4377 FK_NonConstLValueReferenceBindingToVectorElement;
4378 else
4379 llvm_unreachable("unexpected kind of compatible initializer");
4380 break;
4381 case Sema::Ref_Related:
4382 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4383 break;
4384 case Sema::Ref_Incompatible:
4385 FK = InitializationSequence::
4386 FK_NonConstLValueReferenceBindingToUnrelated;
4387 break;
4388 }
4389 Sequence.SetFailed(FK);
4390 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004391 return;
4392 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004393
Douglas Gregor92e460e2011-01-20 16:44:54 +00004394 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004395 // - is an
4396 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4397 // [1z] rvalue (but not a bit-field) or
4398 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4399 //
4400 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004401 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004402 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004403 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004404 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004405 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004406 (InitCategory.isPRValue() &&
4407 (S.getLangOpts().CPlusPlus1z || T2->isRecordType() ||
4408 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004409 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004410 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004411 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4412 // compiler the freedom to perform a copy here or bind to the
4413 // object, while C++0x requires that we bind directly to the
4414 // object. Hence, we always bind to the object without making an
4415 // extra copy. However, in C++03 requires that we check for the
4416 // presence of a suitable copy constructor:
4417 //
4418 // The constructor that would be used to make the copy shall
4419 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004420 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004421 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004422 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004423 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425
Richard Smithb8c0f552016-12-09 18:49:13 +00004426 // C++1z [dcl.init.ref]/5.2.1.2:
4427 // If the converted initializer is a prvalue, its type T4 is adjusted
4428 // to type "cv1 T4" and the temporary materialization conversion is
4429 // applied.
4430 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4431 if (T1Quals != T2Quals)
4432 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4433 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4434 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4435
4436 // In any case, the reference is bound to the resulting glvalue (or to
4437 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004438 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004439 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004440 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004441 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004443 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444
4445 // - has a class type (i.e., T2 is a class type), where T1 is not
4446 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004447 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4448 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004449 //
4450 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004451 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004452 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004453 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004454 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4455 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004456 if (ConvOvlResult)
4457 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004458 InitializationSequence::FK_ReferenceInitOverloadFailed,
4459 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004461 return;
4462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463
Richard Smithce766292016-10-21 23:01:55 +00004464 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004465 isRValueRef && InitCategory.isLValue()) {
4466 Sequence.SetFailed(
4467 InitializationSequence::FK_RValueReferenceBindingToLValue);
4468 return;
4469 }
4470
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004471 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4472 return;
4473 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004474
4475 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004476 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004477 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004478 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004479
John McCallec6f4e92010-06-04 02:29:22 +00004480 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4481
Richard Smith2eabf782013-06-13 00:57:57 +00004482 // FIXME: Why do we use an implicit conversion here rather than trying
4483 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004484 ImplicitConversionSequence ICS
4485 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004486 /*SuppressUserConversions=*/false,
4487 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004488 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004489 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4490 /*AllowObjCWritebackConversion=*/false);
4491
4492 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004493 // FIXME: Use the conversion function set stored in ICS to turn
4494 // this into an overloading ambiguity diagnostic. However, we need
4495 // to keep that set as an OverloadCandidateSet rather than as some
4496 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004497 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4498 Sequence.SetOverloadFailure(
4499 InitializationSequence::FK_ReferenceInitOverloadFailed,
4500 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004501 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4502 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004503 else
4504 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004505 return;
John McCall31168b02011-06-15 23:02:42 +00004506 } else {
4507 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004508 }
4509
4510 // [...] If T1 is reference-related to T2, cv1 must be the
4511 // same cv-qualification as, or greater cv-qualification
4512 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004513 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4514 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004516 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004517 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4518 return;
4519 }
4520
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004522 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004524 InitCategory.isLValue()) {
4525 Sequence.SetFailed(
4526 InitializationSequence::FK_RValueReferenceBindingToLValue);
4527 return;
4528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004529
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004530 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004531}
4532
4533/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534/// (C++ [dcl.init.string], C99 6.7.8).
4535static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004536 const InitializedEntity &Entity,
4537 const InitializationKind &Kind,
4538 Expr *Initializer,
4539 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004540 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004541}
4542
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004543/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004544static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004545 const InitializedEntity &Entity,
4546 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004547 InitializationSequence &Sequence,
4548 InitListExpr *InitList) {
4549 assert((!InitList || InitList->getNumInits() == 0) &&
4550 "Shouldn't use value-init for non-empty init lists");
4551
Richard Smith1bfe0682012-02-14 21:14:13 +00004552 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004553 //
4554 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004555 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004557 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004558 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004560 if (const RecordType *RT = T->getAs<RecordType>()) {
4561 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004562 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004563 // C++98:
4564 // -- if T is a class type (clause 9) with a user-declared constructor
4565 // (12.1), then the default constructor for T is called (and the
4566 // initialization is ill-formed if T has no accessible default
4567 // constructor);
4568 // C++11:
4569 // -- if T is a class type (clause 9) with either no default constructor
4570 // (12.1 [class.ctor]) or a default constructor that is user-provided
4571 // or deleted, then the object is default-initialized;
4572 //
4573 // Note that the C++11 rule is the same as the C++98 rule if there are no
4574 // defaulted or deleted constructors, so we just use it unconditionally.
4575 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4576 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4577 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
Richard Smith1bfe0682012-02-14 21:14:13 +00004579 // -- if T is a (possibly cv-qualified) non-union class type without a
4580 // user-provided or deleted default constructor, then the object is
4581 // zero-initialized and, if T has a non-trivial default constructor,
4582 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004583 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4584 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004585 if (NeedZeroInitialization)
4586 Sequence.AddZeroInitializationStep(Entity.getType());
4587
Richard Smith593f9932012-12-08 02:01:17 +00004588 // C++03:
4589 // -- if T is a non-union class type without a user-declared constructor,
4590 // then every non-static data member and base class component of T is
4591 // value-initialized;
4592 // [...] A program that calls for [...] value-initialization of an
4593 // entity of reference type is ill-formed.
4594 //
4595 // C++11 doesn't need this handling, because value-initialization does not
4596 // occur recursively there, and the implicit default constructor is
4597 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004598 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004599 ClassDecl->hasUninitializedReferenceMember()) {
4600 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4601 return;
4602 }
4603
Richard Smithd86812d2012-07-05 08:39:21 +00004604 // If this is list-value-initialization, pass the empty init list on when
4605 // building the constructor call. This affects the semantics of a few
4606 // things (such as whether an explicit default constructor can be called).
4607 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004608 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004609 bool InitListSyntax = InitList;
4610
Richard Smith81f5ade2016-12-15 02:28:18 +00004611 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004612 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4613 return TryConstructorInitialization(
4614 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004615 }
4616 }
4617
Douglas Gregor1b303932009-12-22 15:35:07 +00004618 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004619}
4620
Douglas Gregor85dabae2009-12-16 01:38:02 +00004621/// \brief Attempt default initialization (C++ [dcl.init]p6).
4622static void TryDefaultInitialization(Sema &S,
4623 const InitializedEntity &Entity,
4624 const InitializationKind &Kind,
4625 InitializationSequence &Sequence) {
4626 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627
Douglas Gregor85dabae2009-12-16 01:38:02 +00004628 // C++ [dcl.init]p6:
4629 // To default-initialize an object of type T means:
4630 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004631 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4632
Douglas Gregor85dabae2009-12-16 01:38:02 +00004633 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4634 // constructor for T is called (and the initialization is ill-formed if
4635 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004636 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004637 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4638 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004639 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004641
Douglas Gregor85dabae2009-12-16 01:38:02 +00004642 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004643
Douglas Gregor85dabae2009-12-16 01:38:02 +00004644 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004646 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004647 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004648 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4649 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004650 return;
4651 }
4652
4653 // If the destination type has a lifetime property, zero-initialize it.
4654 if (DestType.getQualifiers().hasObjCLifetime()) {
4655 Sequence.AddZeroInitializationStep(Entity.getType());
4656 return;
4657 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004658}
4659
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004660/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4661/// which enumerates all conversion functions and performs overload resolution
4662/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004664 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004665 const InitializationKind &Kind,
4666 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004667 InitializationSequence &Sequence,
4668 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004669 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4670 QualType SourceType = Initializer->getType();
4671 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4672 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673
Douglas Gregor540c3b02009-12-14 17:27:33 +00004674 // Build the candidate set directly in the initialization sequence
4675 // structure, so that it will persist if we fail.
4676 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4677 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004678
Douglas Gregor540c3b02009-12-14 17:27:33 +00004679 // Determine whether we are allowed to call explicit constructors or
4680 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004681 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004682
Douglas Gregor540c3b02009-12-14 17:27:33 +00004683 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4684 // The type we're converting to is a class type. Enumerate its constructors
4685 // to see if there is a suitable conversion.
4686 CXXRecordDecl *DestRecordDecl
4687 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688
Douglas Gregord9848152010-04-26 14:36:57 +00004689 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004690 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004691 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004692 auto Info = getConstructorInfo(D);
4693 if (!Info.Constructor)
4694 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695
Richard Smithc2bebe92016-05-11 20:37:46 +00004696 if (!Info.Constructor->isInvalidDecl() &&
4697 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4698 if (Info.ConstructorTmpl)
4699 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004700 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004701 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004702 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004703 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004704 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004705 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004706 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708 }
Douglas Gregord9848152010-04-26 14:36:57 +00004709 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004710 }
Eli Friedman78275202009-12-19 08:11:05 +00004711
4712 SourceLocation DeclLoc = Initializer->getLocStart();
4713
Douglas Gregor540c3b02009-12-14 17:27:33 +00004714 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4715 // The type we're converting from is a class type, enumerate its conversion
4716 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004717
Eli Friedman4afe9a32009-12-20 22:12:03 +00004718 // We can only enumerate the conversion functions for a complete type; if
4719 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004720 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004721 CXXRecordDecl *SourceRecordDecl
4722 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004724 const auto &Conversions =
4725 SourceRecordDecl->getVisibleConversionFunctions();
4726 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004727 NamedDecl *D = *I;
4728 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4729 if (isa<UsingShadowDecl>(D))
4730 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
Eli Friedman4afe9a32009-12-20 22:12:03 +00004732 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4733 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004734 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004735 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004736 else
John McCallda4458e2010-03-31 01:36:47 +00004737 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Eli Friedman4afe9a32009-12-20 22:12:03 +00004739 if (AllowExplicit || !Conv->isExplicit()) {
4740 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004741 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004742 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004743 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004744 else
John McCalla0296f72010-03-19 07:35:19 +00004745 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004746 Initializer, DestType, CandidateSet,
4747 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004748 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004749 }
4750 }
4751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752
4753 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004754 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004755 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004756 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004757 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004759 Result);
4760 return;
4761 }
John McCall0d1da222010-01-12 00:44:57 +00004762
Douglas Gregor540c3b02009-12-14 17:27:33 +00004763 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004764 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004765 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004766
Douglas Gregor540c3b02009-12-14 17:27:33 +00004767 if (isa<CXXConstructorDecl>(Function)) {
4768 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004769 // subsumed by the initialization. Per DR5, the created temporary is of the
4770 // cv-unqualified type of the destination.
4771 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4772 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004773 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00004774
4775 // C++14 and before:
4776 // - if the function is a constructor, the call initializes a temporary
4777 // of the cv-unqualified version of the destination type. The [...]
4778 // temporary [...] is then used to direct-initialize, according to the
4779 // rules above, the object that is the destination of the
4780 // copy-initialization.
4781 // Note that this just performs a simple object copy from the temporary.
4782 //
4783 // C++1z:
4784 // - if the function is a constructor, the call is a prvalue of the
4785 // cv-unqualified version of the destination type whose return object
4786 // is initialized by the constructor. The call is used to
4787 // direct-initialize, according to the rules above, the object that
4788 // is the destination of the copy-initialization.
4789 // Therefore we need to do nothing further.
4790 //
4791 // FIXME: Mark this copy as extraneous.
4792 if (!S.getLangOpts().CPlusPlus1z)
4793 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004794 else if (DestType.hasQualifiers())
4795 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004796 return;
4797 }
4798
4799 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004800 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004801 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4802 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Richard Smithb8c0f552016-12-09 18:49:13 +00004804 if (ConvType->getAs<RecordType>()) {
4805 // The call is used to direct-initialize [...] the object that is the
4806 // destination of the copy-initialization.
4807 //
4808 // In C++1z, this does not call a constructor if we enter /17.6.1:
4809 // - If the initializer expression is a prvalue and the cv-unqualified
4810 // version of the source type is the same as the class of the
4811 // destination [... do not make an extra copy]
4812 //
4813 // FIXME: Mark this copy as extraneous.
4814 if (!S.getLangOpts().CPlusPlus1z ||
4815 Function->getReturnType()->isReferenceType() ||
4816 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4817 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004818 else if (!S.Context.hasSameType(ConvType, DestType))
4819 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00004820 return;
4821 }
4822
Douglas Gregor5ab11652010-04-17 22:01:05 +00004823 // If the conversion following the call to the conversion function
4824 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004825 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4826 Best->FinalConversion.Third) {
4827 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004828 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004829 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004830 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004831 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004832}
4833
Richard Smithf032001b2013-06-20 02:18:31 +00004834/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4835/// a function with a pointer return type contains a 'return false;' statement.
4836/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4837/// code using that header.
4838///
4839/// Work around this by treating 'return false;' as zero-initializing the result
4840/// if it's used in a pointer-returning function in a system header.
4841static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4842 const InitializedEntity &Entity,
4843 const Expr *Init) {
4844 return S.getLangOpts().CPlusPlus11 &&
4845 Entity.getKind() == InitializedEntity::EK_Result &&
4846 Entity.getType()->isPointerType() &&
4847 isa<CXXBoolLiteralExpr>(Init) &&
4848 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4849 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4850}
4851
John McCall31168b02011-06-15 23:02:42 +00004852/// The non-zero enum values here are indexes into diagnostic alternatives.
4853enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4854
4855/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004856static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004857 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004858 // Skip parens.
4859 e = e->IgnoreParens();
4860
4861 // Skip address-of nodes.
4862 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4863 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004864 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4865 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004866
4867 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004868 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4869 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004870 case CK_Dependent:
4871 case CK_BitCast:
4872 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004873 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004874 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004875
4876 case CK_ArrayToPointerDecay:
4877 return IIK_nonscalar;
4878
4879 case CK_NullToPointer:
4880 return IIK_okay;
4881
4882 default:
4883 break;
4884 }
4885
4886 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004887 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004888 // set isWeakAccess to true, to mean that there will be an implicit
4889 // load which requires a cleanup.
4890 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4891 isWeakAccess = true;
4892
John McCall63f84442011-06-27 23:59:58 +00004893 if (!isAddressOf) return IIK_nonlocal;
4894
John McCall113bee02012-03-10 09:33:50 +00004895 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4896 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004897
4898 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004899
4900 // If we have a conditional operator, check both sides.
4901 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004902 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4903 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004904 return iik;
4905
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004906 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004907
4908 // These are never scalar.
4909 } else if (isa<ArraySubscriptExpr>(e)) {
4910 return IIK_nonscalar;
4911
4912 // Otherwise, it needs to be a null pointer constant.
4913 } else {
4914 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4915 ? IIK_okay : IIK_nonlocal);
4916 }
4917
4918 return IIK_nonlocal;
4919}
4920
4921/// Check whether the given expression is a valid operand for an
4922/// indirect copy/restore.
4923static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4924 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004925 bool isWeakAccess = false;
4926 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4927 // If isWeakAccess to true, there will be an implicit
4928 // load which requires a cleanup.
4929 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00004930 S.Cleanup.setExprNeedsCleanups(true);
4931
John McCall31168b02011-06-15 23:02:42 +00004932 if (iik == IIK_okay) return;
4933
4934 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4935 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4936 << src->getSourceRange();
4937}
4938
Douglas Gregore2f943b2011-02-22 18:29:51 +00004939/// \brief Determine whether we have compatible array types for the
4940/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00004941static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00004942 const ArrayType *Source) {
4943 // If the source and destination array types are equivalent, we're
4944 // done.
4945 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4946 return true;
4947
4948 // Make sure that the element types are the same.
4949 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4950 return false;
4951
4952 // The only mismatch we allow is when the destination is an
4953 // incomplete array type and the source is a constant array type.
4954 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4955}
4956
John McCall31168b02011-06-15 23:02:42 +00004957static bool tryObjCWritebackConversion(Sema &S,
4958 InitializationSequence &Sequence,
4959 const InitializedEntity &Entity,
4960 Expr *Initializer) {
4961 bool ArrayDecay = false;
4962 QualType ArgType = Initializer->getType();
4963 QualType ArgPointee;
4964 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4965 ArrayDecay = true;
4966 ArgPointee = ArgArrayType->getElementType();
4967 ArgType = S.Context.getPointerType(ArgPointee);
4968 }
4969
4970 // Handle write-back conversion.
4971 QualType ConvertedArgType;
4972 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4973 ConvertedArgType))
4974 return false;
4975
4976 // We should copy unless we're passing to an argument explicitly
4977 // marked 'out'.
4978 bool ShouldCopy = true;
4979 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4980 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4981
4982 // Do we need an lvalue conversion?
4983 if (ArrayDecay || Initializer->isGLValue()) {
4984 ImplicitConversionSequence ICS;
4985 ICS.setStandard();
4986 ICS.Standard.setAsIdentityConversion();
4987
4988 QualType ResultType;
4989 if (ArrayDecay) {
4990 ICS.Standard.First = ICK_Array_To_Pointer;
4991 ResultType = S.Context.getPointerType(ArgPointee);
4992 } else {
4993 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4994 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4995 }
4996
4997 Sequence.AddConversionSequenceStep(ICS, ResultType);
4998 }
4999
5000 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5001 return true;
5002}
5003
Guy Benyei61054192013-02-07 10:55:47 +00005004static bool TryOCLSamplerInitialization(Sema &S,
5005 InitializationSequence &Sequence,
5006 QualType DestType,
5007 Expr *Initializer) {
5008 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005009 (!Initializer->isIntegerConstantExpr(S.Context) &&
5010 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005011 return false;
5012
5013 Sequence.AddOCLSamplerInitStep(DestType);
5014 return true;
5015}
5016
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005017//
5018// OpenCL 1.2 spec, s6.12.10
5019//
5020// The event argument can also be used to associate the
5021// async_work_group_copy with a previous async copy allowing
5022// an event to be shared by multiple async copies; otherwise
5023// event should be zero.
5024//
5025static bool TryOCLZeroEventInitialization(Sema &S,
5026 InitializationSequence &Sequence,
5027 QualType DestType,
5028 Expr *Initializer) {
5029 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5030 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5031 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5032 return false;
5033
5034 Sequence.AddOCLZeroEventStep(DestType);
5035 return true;
5036}
5037
Egor Churaev89831422016-12-23 14:55:49 +00005038static bool TryOCLZeroQueueInitialization(Sema &S,
5039 InitializationSequence &Sequence,
5040 QualType DestType,
5041 Expr *Initializer) {
5042 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5043 !DestType->isQueueT() ||
5044 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5045 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5046 return false;
5047
5048 Sequence.AddOCLZeroQueueStep(DestType);
5049 return true;
5050}
5051
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005052InitializationSequence::InitializationSequence(Sema &S,
5053 const InitializedEntity &Entity,
5054 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005055 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005056 bool TopLevelOfInitList,
5057 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005058 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005059 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5060 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005061}
5062
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005063/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5064/// address of that function, this returns true. Otherwise, it returns false.
5065static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5066 auto *DRE = dyn_cast<DeclRefExpr>(E);
5067 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5068 return false;
5069
5070 return !S.checkAddressOfFunctionIsAvailable(
5071 cast<FunctionDecl>(DRE->getDecl()));
5072}
5073
Richard Smith410306b2016-12-12 02:53:20 +00005074/// Determine whether we can perform an elementwise array copy for this kind
5075/// of entity.
5076static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5077 switch (Entity.getKind()) {
5078 case InitializedEntity::EK_LambdaCapture:
5079 // C++ [expr.prim.lambda]p24:
5080 // For array members, the array elements are direct-initialized in
5081 // increasing subscript order.
5082 return true;
5083
5084 case InitializedEntity::EK_Variable:
5085 // C++ [dcl.decomp]p1:
5086 // [...] each element is copy-initialized or direct-initialized from the
5087 // corresponding element of the assignment-expression [...]
5088 return isa<DecompositionDecl>(Entity.getDecl());
5089
5090 case InitializedEntity::EK_Member:
5091 // C++ [class.copy.ctor]p14:
5092 // - if the member is an array, each element is direct-initialized with
5093 // the corresponding subobject of x
5094 return Entity.isImplicitMemberInitializer();
5095
5096 case InitializedEntity::EK_ArrayElement:
5097 // All the above cases are intended to apply recursively, even though none
5098 // of them actually say that.
5099 if (auto *E = Entity.getParent())
5100 return canPerformArrayCopy(*E);
5101 break;
5102
5103 default:
5104 break;
5105 }
5106
5107 return false;
5108}
5109
Richard Smith089c3162013-09-21 21:55:46 +00005110void InitializationSequence::InitializeFrom(Sema &S,
5111 const InitializedEntity &Entity,
5112 const InitializationKind &Kind,
5113 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005114 bool TopLevelOfInitList,
5115 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005116 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
John McCall5e77d762013-04-16 07:28:30 +00005118 // Eliminate non-overload placeholder types in the arguments. We
5119 // need to do this before checking whether types are dependent
5120 // because lowering a pseudo-object expression might well give us
5121 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005122 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005123 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5124 // FIXME: should we be doing this here?
5125 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5126 if (result.isInvalid()) {
5127 SetFailed(FK_PlaceholderType);
5128 return;
5129 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005130 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005131 }
5132
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005133 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005134 // The semantics of initializers are as follows. The destination type is
5135 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005136 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005137 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005138 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005139 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005140
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005141 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005142 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005143 SequenceKind = DependentSequence;
5144 return;
5145 }
5146
Sebastian Redld201edf2011-06-05 13:59:11 +00005147 // Almost everything is a normal sequence.
5148 setSequenceKind(NormalSequence);
5149
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005150 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005151 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005152 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005153 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005154 if (S.getLangOpts().ObjC1) {
5155 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5156 DestType, Initializer->getType(),
5157 Initializer) ||
5158 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5159 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005160 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005161 if (!isa<InitListExpr>(Initializer))
5162 SourceType = Initializer->getType();
5163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005164
Sebastian Redl0501c632012-02-12 16:37:36 +00005165 // - If the initializer is a (non-parenthesized) braced-init-list, the
5166 // object is list-initialized (8.5.4).
5167 if (Kind.getKind() != InitializationKind::IK_Direct) {
5168 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005169 TryListInitialization(S, Entity, Kind, InitList, *this,
5170 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005171 return;
5172 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005174
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005175 // - If the destination type is a reference type, see 8.5.3.
5176 if (DestType->isReferenceType()) {
5177 // C++0x [dcl.init.ref]p1:
5178 // A variable declared to be a T& or T&&, that is, "reference to type T"
5179 // (8.3.2), shall be initialized by an object, or function, of type T or
5180 // by an object that can be converted into a T.
5181 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005182 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005183 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005184 // C++17 [dcl.init.ref]p5:
5185 // A reference [...] is initialized by an expression [...] as follows:
5186 // If the initializer is not an expression, presumably we should reject,
5187 // but the standard fails to actually say so.
5188 else if (isa<InitListExpr>(Args[0]))
5189 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005190 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005191 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005192 return;
5193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005194
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005195 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005196 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005197 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005198 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005199 return;
5200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005201
Douglas Gregor85dabae2009-12-16 01:38:02 +00005202 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005203 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005204 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005205 return;
5206 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005207
John McCall66884dd2011-02-21 07:22:22 +00005208 // - If the destination type is an array of characters, an array of
5209 // char16_t, an array of char32_t, or an array of wchar_t, and the
5210 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005211 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005212 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005213 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005214 if (Initializer && isa<VariableArrayType>(DestAT)) {
5215 SetFailed(FK_VariableLengthArrayHasInitializer);
5216 return;
5217 }
5218
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005219 if (Initializer) {
5220 switch (IsStringInit(Initializer, DestAT, Context)) {
5221 case SIF_None:
5222 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5223 return;
5224 case SIF_NarrowStringIntoWideChar:
5225 SetFailed(FK_NarrowStringIntoWideCharArray);
5226 return;
5227 case SIF_WideStringIntoChar:
5228 SetFailed(FK_WideStringIntoCharArray);
5229 return;
5230 case SIF_IncompatWideStringIntoWideChar:
5231 SetFailed(FK_IncompatWideStringIntoWideChar);
5232 return;
5233 case SIF_Other:
5234 break;
5235 }
John McCall66884dd2011-02-21 07:22:22 +00005236 }
5237
Richard Smith410306b2016-12-12 02:53:20 +00005238 // Some kinds of initialization permit an array to be initialized from
5239 // another array of the same type, and perform elementwise initialization.
5240 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5241 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5242 Entity.getType()) &&
5243 canPerformArrayCopy(Entity)) {
5244 // If source is a prvalue, use it directly.
5245 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005246 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005247 return;
5248 }
5249
5250 // Emit element-at-a-time copy loop.
5251 InitializedEntity Element =
5252 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5253 QualType InitEltT =
5254 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005255 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5256 Initializer->getValueKind(),
5257 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005258 Expr *OVEAsExpr = &OVE;
5259 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5260 TreatUnavailableAsInvalid);
5261 if (!Failed())
5262 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5263 return;
5264 }
5265
Douglas Gregore2f943b2011-02-22 18:29:51 +00005266 // Note: as an GNU C extension, we allow initialization of an
5267 // array from a compound literal that creates an array of the same
5268 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005269 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005270 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5271 Initializer->getType()->isArrayType()) {
5272 const ArrayType *SourceAT
5273 = Context.getAsArrayType(Initializer->getType());
5274 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005275 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005276 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005277 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005278 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005279 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005280 }
Richard Smithebeed412012-02-15 22:38:09 +00005281 }
Richard Smithd86812d2012-07-05 08:39:21 +00005282 // Note: as a GNU C++ extension, we allow list-initialization of a
5283 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005284 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005285 Entity.getKind() == InitializedEntity::EK_Member &&
5286 Initializer && isa<InitListExpr>(Initializer)) {
5287 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005288 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005289 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005290 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005291 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005292 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5293 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005294 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005295 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005296
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005297 return;
5298 }
Eli Friedman78275202009-12-19 08:11:05 +00005299
Larisse Voufod2010992015-01-24 23:09:54 +00005300 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005301 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005302 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005303 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005304
5305 // We're at the end of the line for C: it's either a write-back conversion
5306 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005307 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005308 // If allowed, check whether this is an Objective-C writeback conversion.
5309 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005310 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005311 return;
5312 }
Guy Benyei61054192013-02-07 10:55:47 +00005313
5314 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5315 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005316
5317 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5318 return;
5319
Egor Churaev89831422016-12-23 14:55:49 +00005320 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5321 return;
5322
John McCall31168b02011-06-15 23:02:42 +00005323 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005324 AddCAssignmentStep(DestType);
5325 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005326 return;
5327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328
David Blaikiebbafb8a2012-03-11 07:00:24 +00005329 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005330
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005331 // - If the destination type is a (possibly cv-qualified) class type:
5332 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005333 // - If the initialization is direct-initialization, or if it is
5334 // copy-initialization where the cv-unqualified version of the
5335 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005336 // class of the destination, constructors are considered. [...]
5337 if (Kind.getKind() == InitializationKind::IK_Direct ||
5338 (Kind.getKind() == InitializationKind::IK_Copy &&
5339 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005340 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005341 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005342 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005344 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005345 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005346 // used) to a derived class thereof are enumerated as described in
5347 // 13.3.1.4, and the best one is chosen through overload resolution
5348 // (13.3).
5349 else
Richard Smith77be48a2014-07-31 06:31:19 +00005350 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005351 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005352 return;
5353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354
Richard Smith49a6b6e2017-03-24 01:14:25 +00005355 assert(Args.size() >= 1 && "Zero-argument case handled above");
5356
5357 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005358 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005359 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005360 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005361 } else if (isa<InitListExpr>(Args[0])) {
5362 SetFailed(FK_ParenthesizedListInitForScalar);
5363 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005365
5366 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005367 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005368 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005369 // For a conversion to _Atomic(T) from either T or a class type derived
5370 // from T, initialize the T object then convert to _Atomic type.
5371 bool NeedAtomicConversion = false;
5372 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5373 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005374 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5375 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005376 DestType = Atomic->getValueType();
5377 NeedAtomicConversion = true;
5378 }
5379 }
5380
5381 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005382 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005383 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005384 if (!Failed() && NeedAtomicConversion)
5385 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005386 return;
5387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005388
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005389 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005390 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005391 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005392 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005393 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005394
John McCall31168b02011-06-15 23:02:42 +00005395 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005396 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005397 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005398 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005399 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005400 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5401 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005402
5403 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005404 ICS.Standard.Second == ICK_Writeback_Conversion) {
5405 // Objective-C ARC writeback conversion.
5406
5407 // We should copy unless we're passing to an argument explicitly
5408 // marked 'out'.
5409 bool ShouldCopy = true;
5410 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5411 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5412
5413 // If there was an lvalue adjustment, add it as a separate conversion.
5414 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5415 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5416 ImplicitConversionSequence LvalueICS;
5417 LvalueICS.setStandard();
5418 LvalueICS.Standard.setAsIdentityConversion();
5419 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5420 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005421 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005422 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005423
Richard Smith77be48a2014-07-31 06:31:19 +00005424 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005425 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005426 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005427 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5428 AddZeroInitializationStep(Entity.getType());
5429 } else if (Initializer->getType() == Context.OverloadTy &&
5430 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5431 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005432 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005433 else if (Initializer->getType()->isFunctionType() &&
5434 isExprAnUnaddressableFunction(S, Initializer))
5435 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005436 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005437 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005438 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005439 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005440
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005441 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005442 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005443}
5444
5445InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005446 for (auto &S : Steps)
5447 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005448}
5449
5450//===----------------------------------------------------------------------===//
5451// Perform initialization
5452//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005453static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005454getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005455 switch(Entity.getKind()) {
5456 case InitializedEntity::EK_Variable:
5457 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005458 case InitializedEntity::EK_Exception:
5459 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005460 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005461 return Sema::AA_Initializing;
5462
5463 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005465 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5466 return Sema::AA_Sending;
5467
Douglas Gregore1314a62009-12-18 05:02:21 +00005468 return Sema::AA_Passing;
5469
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005470 case InitializedEntity::EK_Parameter_CF_Audited:
5471 if (Entity.getDecl() &&
5472 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5473 return Sema::AA_Sending;
5474
5475 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5476
Douglas Gregore1314a62009-12-18 05:02:21 +00005477 case InitializedEntity::EK_Result:
5478 return Sema::AA_Returning;
5479
Douglas Gregore1314a62009-12-18 05:02:21 +00005480 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005481 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005482 // FIXME: Can we tell apart casting vs. converting?
5483 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484
Douglas Gregore1314a62009-12-18 05:02:21 +00005485 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005486 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005487 case InitializedEntity::EK_ArrayElement:
5488 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005489 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005490 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005491 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005492 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005493 return Sema::AA_Initializing;
5494 }
5495
David Blaikie8a40f702012-01-17 06:56:22 +00005496 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005497}
5498
Richard Smith27874d62013-01-08 00:08:23 +00005499/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005500/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005501static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005502 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005503 case InitializedEntity::EK_ArrayElement:
5504 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005505 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00005506 case InitializedEntity::EK_New:
5507 case InitializedEntity::EK_Variable:
5508 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005509 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005510 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005511 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005512 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005513 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005514 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005515 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005516 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517
Douglas Gregore1314a62009-12-18 05:02:21 +00005518 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005519 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005520 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005521 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005522 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005523 return true;
5524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525
Douglas Gregore1314a62009-12-18 05:02:21 +00005526 llvm_unreachable("missed an InitializedEntity kind?");
5527}
5528
Douglas Gregor95562572010-04-24 23:45:46 +00005529/// \brief Whether the given entity, when initialized with an object
5530/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005531static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005532 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005533 case InitializedEntity::EK_Result:
5534 case InitializedEntity::EK_New:
5535 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005536 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005537 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005538 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005539 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005540 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005541 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005542
Richard Smith27874d62013-01-08 00:08:23 +00005543 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005544 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005545 case InitializedEntity::EK_Variable:
5546 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005547 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005548 case InitializedEntity::EK_Temporary:
5549 case InitializedEntity::EK_ArrayElement:
5550 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005551 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005552 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005553 return true;
5554 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
5556 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005557}
5558
Richard Smithc620f552011-10-19 16:55:56 +00005559/// \brief Get the location at which initialization diagnostics should appear.
5560static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5561 Expr *Initializer) {
5562 switch (Entity.getKind()) {
5563 case InitializedEntity::EK_Result:
5564 return Entity.getReturnLoc();
5565
5566 case InitializedEntity::EK_Exception:
5567 return Entity.getThrowLoc();
5568
5569 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005570 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005571 return Entity.getDecl()->getLocation();
5572
Douglas Gregor19666fb2012-02-15 16:57:26 +00005573 case InitializedEntity::EK_LambdaCapture:
5574 return Entity.getCaptureLoc();
5575
Richard Smithc620f552011-10-19 16:55:56 +00005576 case InitializedEntity::EK_ArrayElement:
5577 case InitializedEntity::EK_Member:
5578 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005579 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005580 case InitializedEntity::EK_Temporary:
5581 case InitializedEntity::EK_New:
5582 case InitializedEntity::EK_Base:
5583 case InitializedEntity::EK_Delegating:
5584 case InitializedEntity::EK_VectorElement:
5585 case InitializedEntity::EK_ComplexElement:
5586 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005587 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005588 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005589 return Initializer->getLocStart();
5590 }
5591 llvm_unreachable("missed an InitializedEntity kind?");
5592}
5593
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005594/// \brief Make a (potentially elidable) temporary copy of the object
5595/// provided by the given initializer by calling the appropriate copy
5596/// constructor.
5597///
5598/// \param S The Sema object used for type-checking.
5599///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005600/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005601/// the type of the initializer expression or a superclass thereof.
5602///
James Dennett634962f2012-06-14 21:40:34 +00005603/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005604///
5605/// \param CurInit The initializer expression.
5606///
5607/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5608/// is permitted in C++03 (but not C++0x) when binding a reference to
5609/// an rvalue.
5610///
5611/// \returns An expression that copies the initializer expression into
5612/// a temporary object, or an error expression if a copy could not be
5613/// created.
John McCalldadc5752010-08-24 06:29:42 +00005614static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005615 QualType T,
5616 const InitializedEntity &Entity,
5617 ExprResult CurInit,
5618 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005619 if (CurInit.isInvalid())
5620 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005621 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005622 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005623 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005624 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005625 Class = cast<CXXRecordDecl>(Record->getDecl());
5626 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005627 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005628
Richard Smithc620f552011-10-19 16:55:56 +00005629 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005630
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005631 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005632 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005633 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005634
Richard Smith7c2bcc92016-09-07 02:14:33 +00005635 // Perform overload resolution using the class's constructors. Per
5636 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005637 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005638 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005639 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005640
Douglas Gregore1314a62009-12-18 05:02:21 +00005641 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005642 switch (ResolveConstructorOverload(
5643 S, Loc, CurInitExpr, CandidateSet, Ctors, Best,
5644 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5645 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5646 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005647 case OR_Success:
5648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Douglas Gregore1314a62009-12-18 05:02:21 +00005650 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005651 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5652 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5653 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005654 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005655 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005656 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005657 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005658 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005659 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregore1314a62009-12-18 05:02:21 +00005661 case OR_Ambiguous:
5662 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005663 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005664 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005665 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005666 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005667
Douglas Gregore1314a62009-12-18 05:02:21 +00005668 case OR_Deleted:
5669 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005670 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005671 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005672 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005673 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005674 }
5675
Richard Smith7c2bcc92016-09-07 02:14:33 +00005676 bool HadMultipleCandidates = CandidateSet.size() > 1;
5677
Douglas Gregor5ab11652010-04-17 22:01:05 +00005678 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005679 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005680 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005681
Richard Smith5179eb72016-06-28 19:03:57 +00005682 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5683 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005684
5685 if (IsExtraneousCopy) {
5686 // If this is a totally extraneous copy for C++03 reference
5687 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005688 // expression. We don't generate an (elided) copy operation here
5689 // because doing so would require us to pass down a flag to avoid
5690 // infinite recursion, where each step adds another extraneous,
5691 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005692
Douglas Gregor30b52772010-04-18 07:57:34 +00005693 // Instantiate the default arguments of any extra parameters in
5694 // the selected copy constructor, as if we were going to create a
5695 // proper call to the copy constructor.
5696 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5697 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5698 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005699 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005700 break;
5701
5702 // Build the default argument expression; we don't actually care
5703 // if this succeeds or not, because this routine will complain
5704 // if there was a problem.
5705 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5706 }
5707
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005708 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005710
Douglas Gregor5ab11652010-04-17 22:01:05 +00005711 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005712 // constructor call (we might have derived-to-base conversions, or
5713 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005714 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005715 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005716
Richard Smith7c2bcc92016-09-07 02:14:33 +00005717 // C++0x [class.copy]p32:
5718 // When certain criteria are met, an implementation is allowed to
5719 // omit the copy/move construction of a class object, even if the
5720 // copy/move constructor and/or destructor for the object have
5721 // side effects. [...]
5722 // - when a temporary class object that has not been bound to a
5723 // reference (12.2) would be copied/moved to a class object
5724 // with the same cv-unqualified type, the copy/move operation
5725 // can be omitted by constructing the temporary object
5726 // directly into the target of the omitted copy/move
5727 //
5728 // Note that the other three bullets are handled elsewhere. Copy
5729 // elision for return statements and throw expressions are handled as part
5730 // of constructor initialization, while copy elision for exception handlers
5731 // is handled by the run-time.
5732 //
5733 // FIXME: If the function parameter is not the same type as the temporary, we
5734 // should still be able to elide the copy, but we don't have a way to
5735 // represent in the AST how much should be elided in this case.
5736 bool Elidable =
5737 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5738 S.Context.hasSameUnqualifiedType(
5739 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5740 CurInitExpr->getType());
5741
Douglas Gregord0ace022010-04-25 00:55:24 +00005742 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00005743 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5744 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005745 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005746 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005747 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005748 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005749 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005750 CXXConstructExpr::CK_Complete,
5751 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005752
Douglas Gregord0ace022010-04-25 00:55:24 +00005753 // If we're supposed to bind temporaries, do so.
5754 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005755 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005756 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005757}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005758
Richard Smithc620f552011-10-19 16:55:56 +00005759/// \brief Check whether elidable copy construction for binding a reference to
5760/// a temporary would have succeeded if we were building in C++98 mode, for
5761/// -Wc++98-compat.
5762static void CheckCXX98CompatAccessibleCopy(Sema &S,
5763 const InitializedEntity &Entity,
5764 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005765 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005766
5767 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5768 if (!Record)
5769 return;
5770
5771 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005772 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005773 return;
5774
5775 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005776 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005777 DeclContext::lookup_result Ctors =
5778 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00005779
5780 // Perform overload resolution.
5781 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005782 OverloadingResult OR = ResolveConstructorOverload(
5783 S, Loc, CurInitExpr, CandidateSet, Ctors, Best,
5784 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5785 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5786 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00005787
5788 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5789 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5790 << CurInitExpr->getSourceRange();
5791
5792 switch (OR) {
5793 case OR_Success:
5794 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00005795 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005796 // FIXME: Check default arguments as far as that's possible.
5797 break;
5798
5799 case OR_No_Viable_Function:
5800 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005801 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005802 break;
5803
5804 case OR_Ambiguous:
5805 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005806 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005807 break;
5808
5809 case OR_Deleted:
5810 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005811 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005812 break;
5813 }
5814}
5815
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005816void InitializationSequence::PrintInitLocationNote(Sema &S,
5817 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005818 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005819 if (Entity.getDecl()->getLocation().isInvalid())
5820 return;
5821
5822 if (Entity.getDecl()->getDeclName())
5823 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5824 << Entity.getDecl()->getDeclName();
5825 else
5826 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5827 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005828 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5829 Entity.getMethodDecl())
5830 S.Diag(Entity.getMethodDecl()->getLocation(),
5831 diag::note_method_return_type_change)
5832 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005833}
5834
Jordan Rose6c0505e2013-05-06 16:48:12 +00005835/// Returns true if the parameters describe a constructor initialization of
5836/// an explicit temporary object, e.g. "Point(x, y)".
5837static bool isExplicitTemporary(const InitializedEntity &Entity,
5838 const InitializationKind &Kind,
5839 unsigned NumArgs) {
5840 switch (Entity.getKind()) {
5841 case InitializedEntity::EK_Temporary:
5842 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005843 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005844 break;
5845 default:
5846 return false;
5847 }
5848
5849 switch (Kind.getKind()) {
5850 case InitializationKind::IK_DirectList:
5851 return true;
5852 // FIXME: Hack to work around cast weirdness.
5853 case InitializationKind::IK_Direct:
5854 case InitializationKind::IK_Value:
5855 return NumArgs != 1;
5856 default:
5857 return false;
5858 }
5859}
5860
Sebastian Redled2e5322011-12-22 14:44:04 +00005861static ExprResult
5862PerformConstructorInitialization(Sema &S,
5863 const InitializedEntity &Entity,
5864 const InitializationKind &Kind,
5865 MultiExprArg Args,
5866 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005867 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005868 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005869 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005870 SourceLocation LBraceLoc,
5871 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005872 unsigned NumArgs = Args.size();
5873 CXXConstructorDecl *Constructor
5874 = cast<CXXConstructorDecl>(Step.Function.Function);
5875 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5876
5877 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005878 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005879 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5880 ? Kind.getEqualLoc()
5881 : Kind.getLocation();
5882
5883 if (Kind.getKind() == InitializationKind::IK_Default) {
5884 // Force even a trivial, implicit default constructor to be
5885 // semantically checked. We do this explicitly because we don't build
5886 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005887 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005888 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005889 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005890 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5891 }
5892
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005893 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005894
Douglas Gregor6073dca2012-02-24 23:56:31 +00005895 // C++ [over.match.copy]p1:
5896 // - When initializing a temporary to be bound to the first parameter
5897 // of a constructor that takes a reference to possibly cv-qualified
5898 // T as its first argument, called with a single argument in the
5899 // context of direct-initialization, explicit conversion functions
5900 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00005901 bool AllowExplicitConv =
5902 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
5903 hasCopyOrMoveCtorParam(S.Context,
5904 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00005905
Sebastian Redled2e5322011-12-22 14:44:04 +00005906 // Determine the arguments required to actually perform the constructor
5907 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005908 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005909 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005910 AllowExplicitConv,
5911 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005912 return ExprError();
5913
5914
Jordan Rose6c0505e2013-05-06 16:48:12 +00005915 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005916 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00005917 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5918 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005919
5920 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5921 if (!TSInfo)
5922 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005923 SourceRange ParenOrBraceRange =
5924 (Kind.getKind() == InitializationKind::IK_DirectList)
5925 ? SourceRange(LBraceLoc, RBraceLoc)
5926 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005927
Richard Smith5179eb72016-06-28 19:03:57 +00005928 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00005929 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00005930 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00005931 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5932 return ExprError();
5933 }
Richard Smith5179eb72016-06-28 19:03:57 +00005934 S.MarkFunctionReferenced(Loc, Constructor);
5935
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005936 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00005937 S.Context, Constructor,
5938 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00005939 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
5940 IsListInitialization, IsStdInitListInitialization,
5941 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005942 } else {
5943 CXXConstructExpr::ConstructionKind ConstructKind =
5944 CXXConstructExpr::CK_Complete;
5945
5946 if (Entity.getKind() == InitializedEntity::EK_Base) {
5947 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5948 CXXConstructExpr::CK_VirtualBase :
5949 CXXConstructExpr::CK_NonVirtualBase;
5950 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5951 ConstructKind = CXXConstructExpr::CK_Delegating;
5952 }
5953
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005954 // Only get the parenthesis or brace range if it is a list initialization or
5955 // direct construction.
5956 SourceRange ParenOrBraceRange;
5957 if (IsListInitialization)
5958 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5959 else if (Kind.getKind() == InitializationKind::IK_Direct)
5960 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005961
5962 // If the entity allows NRVO, mark the construction as elidable
5963 // unconditionally.
5964 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00005965 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00005966 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00005967 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005968 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005969 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005970 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005971 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005972 ConstructorInitRequiresZeroInit,
5973 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005974 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005975 else
Richard Smith410306b2016-12-12 02:53:20 +00005976 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00005977 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00005978 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005979 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005980 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005981 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005982 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005983 ConstructorInitRequiresZeroInit,
5984 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005985 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005986 }
5987 if (CurInit.isInvalid())
5988 return ExprError();
5989
5990 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00005991 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00005992 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5993 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005994
5995 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005996 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005997
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005998 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005999}
6000
Richard Smitheb3cad52012-06-04 22:27:30 +00006001/// Determine whether the specified InitializedEntity definitely has a lifetime
6002/// longer than the current full-expression. Conservatively returns false if
6003/// it's unclear.
6004static bool
6005InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6006 const InitializedEntity *Top = &Entity;
6007 while (Top->getParent())
6008 Top = Top->getParent();
6009
6010 switch (Top->getKind()) {
6011 case InitializedEntity::EK_Variable:
6012 case InitializedEntity::EK_Result:
6013 case InitializedEntity::EK_Exception:
6014 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00006015 case InitializedEntity::EK_Binding:
Richard Smitheb3cad52012-06-04 22:27:30 +00006016 case InitializedEntity::EK_New:
6017 case InitializedEntity::EK_Base:
6018 case InitializedEntity::EK_Delegating:
6019 return true;
6020
6021 case InitializedEntity::EK_ArrayElement:
6022 case InitializedEntity::EK_VectorElement:
6023 case InitializedEntity::EK_BlockElement:
6024 case InitializedEntity::EK_ComplexElement:
6025 // Could not determine what the full initialization is. Assume it might not
6026 // outlive the full-expression.
6027 return false;
6028
6029 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006030 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00006031 case InitializedEntity::EK_Temporary:
6032 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006033 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006034 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00006035 // The entity being initialized might not outlive the full-expression.
6036 return false;
6037 }
6038
6039 llvm_unreachable("unknown entity kind");
6040}
6041
Richard Smithe6c01442013-06-05 00:46:14 +00006042/// Determine the declaration which an initialized entity ultimately refers to,
6043/// for the purpose of lifetime-extending a temporary bound to a reference in
6044/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00006045static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
6046 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00006047 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006048 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006049 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006050 case InitializedEntity::EK_Variable:
6051 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00006052 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006053
6054 case InitializedEntity::EK_Member:
6055 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006056 if (Entity->getParent())
6057 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6058 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006059
6060 // except:
6061 // -- A temporary bound to a reference member in a constructor's
6062 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00006063 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006064
Richard Smith7873de02016-08-11 22:25:46 +00006065 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006066 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6067 // type.
6068 return Entity;
Richard Smith7873de02016-08-11 22:25:46 +00006069
Richard Smithe6c01442013-06-05 00:46:14 +00006070 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006071 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006072 // -- A temporary bound to a reference parameter in a function call
6073 // persists until the completion of the full-expression containing
6074 // the call.
6075 case InitializedEntity::EK_Result:
6076 // -- The lifetime of a temporary bound to the returned value in a
6077 // function return statement is not extended; the temporary is
6078 // destroyed at the end of the full-expression in the return statement.
6079 case InitializedEntity::EK_New:
6080 // -- A temporary bound to a reference in a new-initializer persists
6081 // until the completion of the full-expression containing the
6082 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006083 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006084
6085 case InitializedEntity::EK_Temporary:
6086 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006087 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006088 // We don't yet know the storage duration of the surrounding temporary.
6089 // Assume it's got full-expression duration for now, it will patch up our
6090 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00006091 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006092
6093 case InitializedEntity::EK_ArrayElement:
6094 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006095 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6096 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00006097
6098 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006099 // For subobjects, we look at the complete object.
6100 if (Entity->getParent())
6101 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6102 Entity);
6103 // Fall through.
Richard Smithe6c01442013-06-05 00:46:14 +00006104 case InitializedEntity::EK_Delegating:
6105 // We can reach this case for aggregate initialization in a constructor:
6106 // struct A { int &&r; };
6107 // struct B : A { B() : A{0} {} };
6108 // In this case, use the innermost field decl as the context.
6109 return FallbackDecl;
6110
6111 case InitializedEntity::EK_BlockElement:
6112 case InitializedEntity::EK_LambdaCapture:
6113 case InitializedEntity::EK_Exception:
6114 case InitializedEntity::EK_VectorElement:
6115 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00006116 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006117 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006118 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006119}
6120
David Majnemerdaff3702014-05-01 17:50:17 +00006121static void performLifetimeExtension(Expr *Init,
6122 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006123
6124/// Update a glvalue expression that is used as the initializer of a reference
6125/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006126/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00006127static bool
6128performReferenceExtension(Expr *Init,
6129 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006130 // Walk past any constructs which we can lifetime-extend across.
6131 Expr *Old;
6132 do {
6133 Old = Init;
6134
Richard Smithdbc82492015-01-10 01:28:13 +00006135 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6136 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
6137 // This is just redundant braces around an initializer. Step over it.
6138 Init = ILE->getInit(0);
6139 }
6140 }
6141
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006142 // Step over any subobject adjustments; we may have a materialized
6143 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006144 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006145
6146 // Per current approach for DR1376, look through casts to reference type
6147 // when performing lifetime extension.
6148 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6149 if (CE->getSubExpr()->isGLValue())
6150 Init = CE->getSubExpr();
6151
Richard Smithb3189a12016-12-05 07:49:14 +00006152 // Per the current approach for DR1299, look through array element access
6153 // when performing lifetime extension.
6154 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6155 Init = ASE->getBase();
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006156 } while (Init != Old);
6157
Richard Smithe6c01442013-06-05 00:46:14 +00006158 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6159 // Update the storage duration of the materialized temporary.
6160 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00006161 ME->setExtendingDecl(ExtendingEntity->getDecl(),
6162 ExtendingEntity->allocateManglingNumber());
6163 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006164 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00006165 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006166
6167 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00006168}
6169
6170/// Update a prvalue expression that is going to be materialized as a
6171/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00006172static void performLifetimeExtension(Expr *Init,
6173 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00006174 // Dig out the expression which constructs the extended temporary.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006175 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smithe6c01442013-06-05 00:46:14 +00006176
Richard Smith736a9472013-06-12 20:42:33 +00006177 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6178 Init = BTE->getSubExpr();
6179
Richard Smithcc1b96d2013-06-12 22:31:48 +00006180 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006181 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00006182 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006183 return;
6184 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006185
Richard Smithe6c01442013-06-05 00:46:14 +00006186 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006187 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006188 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00006189 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006190 return;
6191 }
6192
Richard Smithcc1b96d2013-06-12 22:31:48 +00006193 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006194 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6195
6196 // If we lifetime-extend a braced initializer which is initializing an
6197 // aggregate, and that aggregate contains reference members which are
6198 // bound to temporaries, those temporaries are also lifetime-extended.
6199 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6200 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006201 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006202 else {
6203 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006204 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006205 if (Index >= ILE->getNumInits())
6206 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006207 if (I->isUnnamedBitfield())
6208 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006209 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006210 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006211 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00006212 else if (isa<InitListExpr>(SubInit) ||
6213 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00006214 // This may be either aggregate-initialization of a member or
6215 // initialization of a std::initializer_list object. Either way,
6216 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006217 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006218 ++Index;
6219 }
6220 }
6221 }
6222 }
6223}
6224
Richard Smithcc1b96d2013-06-12 22:31:48 +00006225static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6226 const Expr *Init, bool IsInitializerList,
6227 const ValueDecl *ExtendingDecl) {
6228 // Warn if a field lifetime-extends a temporary.
6229 if (isa<FieldDecl>(ExtendingDecl)) {
6230 if (IsInitializerList) {
6231 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6232 << /*at end of constructor*/true;
6233 return;
6234 }
6235
6236 bool IsSubobjectMember = false;
6237 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6238 Ent = Ent->getParent()) {
6239 if (Ent->getKind() != InitializedEntity::EK_Base) {
6240 IsSubobjectMember = true;
6241 break;
6242 }
6243 }
6244 S.Diag(Init->getExprLoc(),
6245 diag::warn_bind_ref_member_to_temporary)
6246 << ExtendingDecl << Init->getSourceRange()
6247 << IsSubobjectMember << IsInitializerList;
6248 if (IsSubobjectMember)
6249 S.Diag(ExtendingDecl->getLocation(),
6250 diag::note_ref_subobject_of_member_declared_here);
6251 else
6252 S.Diag(ExtendingDecl->getLocation(),
6253 diag::note_ref_or_ptr_member_declared_here)
6254 << /*is pointer*/false;
6255 }
6256}
6257
Richard Smithaaa0ec42013-09-21 21:19:19 +00006258static void DiagnoseNarrowingInInitList(Sema &S,
6259 const ImplicitConversionSequence &ICS,
6260 QualType PreNarrowingType,
6261 QualType EntityType,
6262 const Expr *PostInit);
6263
Richard Trieuac3eca52015-04-29 01:52:17 +00006264/// Provide warnings when std::move is used on construction.
6265static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6266 bool IsReturnStmt) {
6267 if (!InitExpr)
6268 return;
6269
Richard Smith51ec0cf2017-02-21 01:17:38 +00006270 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00006271 return;
6272
Richard Trieuac3eca52015-04-29 01:52:17 +00006273 QualType DestType = InitExpr->getType();
6274 if (!DestType->isRecordType())
6275 return;
6276
6277 unsigned DiagID = 0;
6278 if (IsReturnStmt) {
6279 const CXXConstructExpr *CCE =
6280 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6281 if (!CCE || CCE->getNumArgs() != 1)
6282 return;
6283
6284 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6285 return;
6286
6287 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00006288 }
6289
6290 // Find the std::move call and get the argument.
6291 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6292 if (!CE || CE->getNumArgs() != 1)
6293 return;
6294
6295 const FunctionDecl *MoveFunction = CE->getDirectCallee();
6296 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6297 !MoveFunction->getIdentifier() ||
6298 !MoveFunction->getIdentifier()->isStr("move"))
6299 return;
6300
6301 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6302
6303 if (IsReturnStmt) {
6304 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6305 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6306 return;
6307
6308 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6309 if (!VD || !VD->hasLocalStorage())
6310 return;
6311
Richard Trieu8d4006a2015-07-28 19:06:16 +00006312 QualType SourceType = VD->getType();
6313 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00006314 return;
6315
Richard Trieu8d4006a2015-07-28 19:06:16 +00006316 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00006317 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00006318 }
6319
Davide Italiano7842c3f2015-07-18 01:15:19 +00006320 // If we're returning a function parameter, copy elision
6321 // is not possible.
6322 if (isa<ParmVarDecl>(VD))
6323 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00006324 else
6325 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00006326 } else {
6327 DiagID = diag::warn_pessimizing_move_on_initialization;
6328 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6329 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6330 return;
6331 }
6332
6333 S.Diag(CE->getLocStart(), DiagID);
6334
6335 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6336 // is within a macro.
6337 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6338 if (CallBegin.isMacroID())
6339 return;
6340 SourceLocation RParen = CE->getRParenLoc();
6341 if (RParen.isMacroID())
6342 return;
6343 SourceLocation LParen;
6344 SourceLocation ArgLoc = Arg->getLocStart();
6345
6346 // Special testing for the argument location. Since the fix-it needs the
6347 // location right before the argument, the argument location can be in a
6348 // macro only if it is at the beginning of the macro.
6349 while (ArgLoc.isMacroID() &&
6350 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
6351 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6352 }
6353
6354 if (LParen.isMacroID())
6355 return;
6356
6357 LParen = ArgLoc.getLocWithOffset(-1);
6358
6359 S.Diag(CE->getLocStart(), diag::note_remove_move)
6360 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6361 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6362}
6363
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006364static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6365 // Check to see if we are dereferencing a null pointer. If so, this is
6366 // undefined behavior, so warn about it. This only handles the pattern
6367 // "*null", which is a very syntactic check.
6368 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6369 if (UO->getOpcode() == UO_Deref &&
6370 UO->getSubExpr()->IgnoreParenCasts()->
6371 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6372 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6373 S.PDiag(diag::warn_binding_null_to_reference)
6374 << UO->getSubExpr()->getSourceRange());
6375 }
6376}
6377
Tim Shen4a05bb82016-06-21 20:29:17 +00006378MaterializeTemporaryExpr *
6379Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6380 bool BoundToLvalueReference) {
6381 auto MTE = new (Context)
6382 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6383
6384 // Order an ExprWithCleanups for lifetime marks.
6385 //
6386 // TODO: It'll be good to have a single place to check the access of the
6387 // destructor and generate ExprWithCleanups for various uses. Currently these
6388 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6389 // but there may be a chance to merge them.
6390 Cleanup.setExprNeedsCleanups(false);
6391 return MTE;
6392}
6393
Richard Smith4baaa5a2016-12-03 01:14:32 +00006394ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6395 // In C++98, we don't want to implicitly create an xvalue.
6396 // FIXME: This means that AST consumers need to deal with "prvalues" that
6397 // denote materialized temporaries. Maybe we should add another ValueKind
6398 // for "xvalue pretending to be a prvalue" for C++98 support.
6399 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6400 return E;
6401
6402 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00006403 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6404 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006405 QualType T = E->getType();
6406 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6407 return ExprError();
6408
6409 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6410}
6411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006412ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006413InitializationSequence::Perform(Sema &S,
6414 const InitializedEntity &Entity,
6415 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00006416 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006417 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006418 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006419 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00006420 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006421 }
Nico Weber337d5aa2015-04-17 08:32:38 +00006422 if (!ZeroInitializationFixit.empty()) {
6423 unsigned DiagID = diag::err_default_init_const;
6424 if (Decl *D = Entity.getDecl())
6425 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6426 DiagID = diag::ext_default_init_const;
6427
6428 // The initialization would have succeeded with this fixit. Since the fixit
6429 // is on the error, we need to build a valid AST in this case, so this isn't
6430 // handled in the Failed() branch above.
6431 QualType DestType = Entity.getType();
6432 S.Diag(Kind.getLocation(), DiagID)
6433 << DestType << (bool)DestType->getAs<RecordType>()
6434 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6435 ZeroInitializationFixit);
6436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006437
Sebastian Redld201edf2011-06-05 13:59:11 +00006438 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006439 // If the declaration is a non-dependent, incomplete array type
6440 // that has an initializer, then its type will be completed once
6441 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00006442 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00006443 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006444 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006445 if (const IncompleteArrayType *ArrayT
6446 = S.Context.getAsIncompleteArrayType(DeclType)) {
6447 // FIXME: We don't currently have the ability to accurately
6448 // compute the length of an initializer list without
6449 // performing full type-checking of the initializer list
6450 // (since we have to determine where braces are implicitly
6451 // introduced and such). So, we fall back to making the array
6452 // type a dependently-sized array type with no specified
6453 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006454 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006455 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00006456
Douglas Gregor51e77d52009-12-10 17:56:55 +00006457 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00006458 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006459 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6460 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00006461 if (IncompleteArrayTypeLoc ArrayLoc =
6462 TL.getAs<IncompleteArrayTypeLoc>())
6463 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00006464 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00006465 }
6466
6467 *ResultType
6468 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006469 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006470 ArrayT->getSizeModifier(),
6471 ArrayT->getIndexTypeCVRQualifiers(),
6472 Brackets);
6473 }
6474
6475 }
6476 }
Sebastian Redla9351792012-02-11 23:51:47 +00006477 if (Kind.getKind() == InitializationKind::IK_Direct &&
6478 !Kind.isExplicitCast()) {
6479 // Rebuild the ParenListExpr.
6480 SourceRange ParenRange = Kind.getParenRange();
6481 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006482 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00006483 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00006484 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00006485 Kind.isExplicitCast() ||
6486 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006487 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006488 }
6489
Sebastian Redld201edf2011-06-05 13:59:11 +00006490 // No steps means no initialization.
6491 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006492 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006493
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006494 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006495 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006496 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00006497 // Produce a C++98 compatibility warning if we are initializing a reference
6498 // from an initializer list. For parameters, we produce a better warning
6499 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006500 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00006501 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6502 << Init->getSourceRange();
6503 }
6504
Egor Churaev3bccec52017-04-05 12:47:10 +00006505 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6506 QualType ETy = Entity.getType();
6507 Qualifiers TyQualifiers = ETy.getQualifiers();
6508 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6509 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6510
6511 if (S.getLangOpts().OpenCLVersion >= 200 &&
6512 ETy->isAtomicType() && !HasGlobalAS &&
6513 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6514 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6515 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6516 return ExprError();
6517 }
6518
Richard Smitheb3cad52012-06-04 22:27:30 +00006519 // Diagnose cases where we initialize a pointer to an array temporary, and the
6520 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006521 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00006522 Entity.getType()->isPointerType() &&
6523 InitializedEntityOutlivesFullExpression(Entity)) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00006524 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6525 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6526 Init = MTE->GetTemporaryExpr();
Richard Smitheb3cad52012-06-04 22:27:30 +00006527 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6528 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6529 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6530 << Init->getSourceRange();
6531 }
6532
Douglas Gregor1b303932009-12-22 15:35:07 +00006533 QualType DestType = Entity.getType().getNonReferenceType();
6534 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00006535 // the same as Entity.getDecl()->getType() in cases involving type merging,
6536 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00006537 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00006538 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00006539 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006540
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006541 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00006542 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00006545 // grab the only argument out the Args and place it into the "current"
6546 // initializer.
6547 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006548 case SK_ResolveAddressOfOverloadedFunction:
6549 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006550 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006551 case SK_CastDerivedToBaseLValue:
6552 case SK_BindReference:
6553 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00006554 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006555 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00006556 case SK_UserConversion:
6557 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006558 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006559 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00006560 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00006561 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006562 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00006563 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00006564 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00006565 case SK_UnwrapInitList:
6566 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00006567 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00006568 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00006569 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00006570 case SK_ArrayLoopIndex:
6571 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00006572 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00006573 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00006574 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00006575 case SK_PassByIndirectCopyRestore:
6576 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00006577 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006578 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00006579 case SK_OCLSamplerInit:
Egor Churaev89831422016-12-23 14:55:49 +00006580 case SK_OCLZeroEvent:
6581 case SK_OCLZeroQueue: {
Douglas Gregore1314a62009-12-18 05:02:21 +00006582 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006583 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00006584 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006585 break;
John McCall34376a62010-12-04 03:47:34 +00006586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006587
Douglas Gregore1314a62009-12-18 05:02:21 +00006588 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00006589 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006590 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00006591 case SK_ZeroInitialization:
6592 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594
Richard Smithd6a15082017-01-07 00:48:55 +00006595 // Promote from an unevaluated context to an unevaluated list context in
6596 // C++11 list-initialization; we need to instantiate entities usable in
6597 // constant expressions here in order to perform narrowing checks =(
6598 EnterExpressionEvaluationContext Evaluated(
6599 S, EnterExpressionEvaluationContext::InitList,
6600 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6601
Richard Smith81f5ade2016-12-15 02:28:18 +00006602 // C++ [class.abstract]p2:
6603 // no objects of an abstract class can be created except as subobjects
6604 // of a class derived from it
6605 auto checkAbstractType = [&](QualType T) -> bool {
6606 if (Entity.getKind() == InitializedEntity::EK_Base ||
6607 Entity.getKind() == InitializedEntity::EK_Delegating)
6608 return false;
6609 return S.RequireNonAbstractType(Kind.getLocation(), T,
6610 diag::err_allocation_of_abstract_type);
6611 };
6612
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006613 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006614 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006615 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006616 for (step_iterator Step = step_begin(), StepEnd = step_end();
6617 Step != StepEnd; ++Step) {
6618 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006619 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006620
John Wiegley01296292011-04-08 18:41:53 +00006621 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006623 switch (Step->Kind) {
6624 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006626 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00006627 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00006628 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6629 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006630 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00006631 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00006632 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006633 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006635 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006636 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006637 case SK_CastDerivedToBaseLValue: {
6638 // We have a derived-to-base cast that produces either an rvalue or an
6639 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006640
John McCallcf142162010-08-07 06:22:56 +00006641 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00006642
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006643 // Casts to inaccessible base classes are allowed with C-style casts.
6644 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6645 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00006646 CurInit.get()->getLocStart(),
6647 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00006648 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00006649 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650
John McCall2536c6d2010-08-25 10:28:54 +00006651 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006652 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006653 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006654 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006655 VK_XValue :
6656 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006657 CurInit =
6658 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6659 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006660 break;
6661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006662
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006663 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006664 // Reference binding does not have any corresponding ASTs.
6665
6666 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006667 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006668 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006669
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006670 // Even though we didn't materialize a temporary, the binding may still
6671 // extend the lifetime of a temporary. This happens if we bind a reference
6672 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00006673 if (const InitializedEntity *ExtendingEntity =
6674 getEntityForTemporaryLifetimeExtension(&Entity))
6675 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6676 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6677 /*IsInitializerList=*/false,
6678 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006679
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006680 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006681 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006682
Richard Smithe6c01442013-06-05 00:46:14 +00006683 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00006684 // Make sure the "temporary" is actually an rvalue.
6685 assert(CurInit.get()->isRValue() && "not a temporary");
6686
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006687 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006688 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006689 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006690
Douglas Gregorfe314812011-06-21 17:03:29 +00006691 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00006692 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00006693 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
David Majnemerdaff3702014-05-01 17:50:17 +00006694
6695 // Maybe lifetime-extend the temporary's subobjects to match the
6696 // entity's lifetime.
6697 if (const InitializedEntity *ExtendingEntity =
6698 getEntityForTemporaryLifetimeExtension(&Entity))
6699 if (performReferenceExtension(MTE, ExtendingEntity))
Richard Smithb8c0f552016-12-09 18:49:13 +00006700 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6701 /*IsInitializerList=*/false,
David Majnemerdaff3702014-05-01 17:50:17 +00006702 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006703
Brian Kelley762f9282017-03-29 18:16:38 +00006704 // If we're extending this temporary to automatic storage duration -- we
6705 // need to register its cleanup during the full-expression's cleanups.
6706 if (MTE->getStorageDuration() == SD_Automatic &&
6707 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00006708 S.Cleanup.setExprNeedsCleanups(true);
Richard Smith736a9472013-06-12 20:42:33 +00006709
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006710 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006711 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006713
Richard Smithb8c0f552016-12-09 18:49:13 +00006714 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00006715 if (checkAbstractType(Step->Type))
6716 return ExprError();
6717
Richard Smithb8c0f552016-12-09 18:49:13 +00006718 // If the overall initialization is initializing a temporary, we already
6719 // bound our argument if it was necessary to do so. If not (if we're
6720 // ultimately initializing a non-temporary), our argument needs to be
6721 // bound since it's initializing a function parameter.
6722 // FIXME: This is a mess. Rationalize temporary destruction.
6723 if (!shouldBindAsTemporary(Entity))
6724 CurInit = S.MaybeBindToTemporary(CurInit.get());
6725 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6726 /*IsExtraneousCopy=*/false);
6727 break;
6728
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006729 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006730 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006731 /*IsExtraneousCopy=*/true);
6732 break;
6733
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006734 case SK_UserConversion: {
6735 // We have a user-defined conversion that invokes either a constructor
6736 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006737 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00006738 FunctionDecl *Fn = Step->Function.Function;
6739 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006740 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006741 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006742 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006743 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006744 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006745 SourceLocation Loc = CurInit.get()->getLocStart();
John McCall760af172010-02-01 03:16:54 +00006746
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006747 // Determine the arguments required to actually perform the constructor
6748 // call.
John Wiegley01296292011-04-08 18:41:53 +00006749 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006750 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006751 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006752 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006753 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006754
Richard Smithb24f0672012-02-11 19:22:50 +00006755 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00006756 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6757 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006758 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006759 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006760 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006761 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006762 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006763 CXXConstructExpr::CK_Complete,
6764 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006765 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006766 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006767
Richard Smith5179eb72016-06-28 19:03:57 +00006768 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6769 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006770 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6771 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006772
John McCalle3027922010-08-25 11:45:40 +00006773 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00006774 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006775 } else {
6776 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006777 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006778 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006779 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006780 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6781 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006782
6783 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006784 // derived-to-base conversion? I believe the answer is "no", because
6785 // we don't want to turn off access control here for c-style casts.
Richard Smithb8c0f552016-12-09 18:49:13 +00006786 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
6787 /*Qualifier=*/nullptr,
6788 FoundFn, Conversion);
6789 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006790 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006791
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006792 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006793 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6794 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00006795 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006796 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006797
John McCalle3027922010-08-25 11:45:40 +00006798 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00006799 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006801
Richard Smith81f5ade2016-12-15 02:28:18 +00006802 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
6803 return ExprError();
6804
Richard Smithb8c0f552016-12-09 18:49:13 +00006805 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6806 CastKind, CurInit.get(), nullptr,
6807 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006808
Richard Smithb8c0f552016-12-09 18:49:13 +00006809 if (shouldBindAsTemporary(Entity))
6810 // The overall entity is temporary, so this expression should be
6811 // destroyed at the end of its full-expression.
6812 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6813 else if (CreatedObject && shouldDestroyEntity(Entity)) {
6814 // The object outlasts the full-expression, but we need to prepare for
6815 // a destructor being run on it.
6816 // FIXME: It makes no sense to do this here. This should happen
6817 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00006818 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006819 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006820 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006821 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006822 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006823 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006824 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006825 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6826 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006827 }
6828 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006829 break;
6830 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006831
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006832 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006833 case SK_QualificationConversionXValue:
6834 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006835 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006836 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006837 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006838 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006839 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006840 VK_XValue :
6841 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006842 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006843 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006844 }
6845
Richard Smith77be48a2014-07-31 06:31:19 +00006846 case SK_AtomicConversion: {
6847 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6848 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6849 CK_NonAtomicToAtomic, VK_RValue);
6850 break;
6851 }
6852
Jordan Roseb1312a52013-04-11 00:58:58 +00006853 case SK_LValueToRValue: {
6854 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006855 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6856 CK_LValueToRValue, CurInit.get(),
6857 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006858 break;
6859 }
6860
Richard Smithaaa0ec42013-09-21 21:19:19 +00006861 case SK_ConversionSequence:
6862 case SK_ConversionSequenceNoNarrowing: {
6863 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006864 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6865 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006866 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006867 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006868 ExprResult CurInitExprRes =
6869 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006870 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006871 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006872 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00006873
6874 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
6875
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006876 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006877
6878 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00006879 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00006880 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6881 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00006882
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006883 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006885
Douglas Gregor51e77d52009-12-10 17:56:55 +00006886 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00006887 if (checkAbstractType(Step->Type))
6888 return ExprError();
6889
John Wiegley01296292011-04-08 18:41:53 +00006890 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006891 // If we're not initializing the top-level entity, we need to create an
6892 // InitializeTemporary entity for our target type.
6893 QualType Ty = Step->Type;
6894 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006895 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006896 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6897 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00006898 InitList, Ty, /*VerifyOnly=*/false,
6899 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006900 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006901 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006902
Richard Smithcc1b96d2013-06-12 22:31:48 +00006903 // Hack: We must update *ResultType if available in order to set the
6904 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6905 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6906 if (ResultType &&
6907 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006908 if ((*ResultType)->isRValueReferenceType())
6909 Ty = S.Context.getRValueReferenceType(Ty);
6910 else if ((*ResultType)->isLValueReferenceType())
6911 Ty = S.Context.getLValueReferenceType(Ty,
6912 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6913 *ResultType = Ty;
6914 }
6915
6916 InitListExpr *StructuredInitList =
6917 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006918 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006919 CurInit = shouldBindAsTemporary(InitEntity)
6920 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006921 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006922 break;
6923 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006924
Richard Smith53324112014-07-16 21:33:43 +00006925 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00006926 if (checkAbstractType(Step->Type))
6927 return ExprError();
6928
Sebastian Redl5a41f682012-02-12 16:37:24 +00006929 // When an initializer list is passed for a parameter of type "reference
6930 // to object", we don't get an EK_Temporary entity, but instead an
6931 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006932 // FIXME: This is a hack. What we really should do is create a user
6933 // conversion step for this case, but this makes it considerably more
6934 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006935 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6936 Entity.getType().getNonReferenceType());
6937 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006938 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006939 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006940 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6941 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006942 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006943 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6944 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006945 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006946 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006947 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006948 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006949 InitList->getLBraceLoc(),
6950 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006951 break;
6952 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006953
Sebastian Redl29526f02011-11-27 16:50:07 +00006954 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006955 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006956 break;
6957
6958 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006959 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006960 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6961 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006962 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006963 ILE->setSyntacticForm(Syntactic);
6964 ILE->setType(E->getType());
6965 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006966 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006967 break;
6968 }
6969
Richard Smith53324112014-07-16 21:33:43 +00006970 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006971 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00006972 if (checkAbstractType(Step->Type))
6973 return ExprError();
6974
Sebastian Redl99f66162012-02-19 12:27:56 +00006975 // When an initializer list is passed for a parameter of type "reference
6976 // to object", we don't get an EK_Temporary entity, but instead an
6977 // EK_Parameter entity with reference type.
6978 // FIXME: This is a hack. What we really should do is create a user
6979 // conversion step for this case, but this makes it considerably more
6980 // complicated. For now, this will do.
6981 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6982 Entity.getType().getNonReferenceType());
6983 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006984 bool IsStdInitListInit =
6985 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00006986 Expr *Source = CurInit.get();
Richard Smith53324112014-07-16 21:33:43 +00006987 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00006988 S, UseTemporary ? TempEntity : Entity, Kind,
6989 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00006990 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00006991 /*IsListInitialization*/ IsStdInitListInit,
6992 /*IsStdInitListInitialization*/ IsStdInitListInit,
6993 /*LBraceLoc*/ SourceLocation(),
6994 /*RBraceLoc*/ SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006995 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006998 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006999 step_iterator NextStep = Step;
7000 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007001 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007002 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007003 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007004 // The need for zero-initialization is recorded directly into
7005 // the call to the object's constructor within the next step.
7006 ConstructorInitRequiresZeroInit = true;
7007 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007008 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007009 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007010 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7011 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007013 Kind.getRange().getBegin());
7014
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007015 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007016 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007017 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007018 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007019 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007020 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007021 break;
7022 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007023
7024 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007025 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007026 // Save off the initial CurInit in case we need to emit a diagnostic
7027 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007028 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007029 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007030 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7031 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007032 if (Result.isInvalid())
7033 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007034 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007035
7036 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007037 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007038 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007039 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007040 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007041 == Sema::Compatible)
7042 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007043 if (CurInitExprRes.isInvalid())
7044 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007045 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007046
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007047 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007048 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7049 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007050 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007051 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007052 &Complained)) {
7053 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007054 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007055 } else if (Complained)
7056 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007057 break;
7058 }
Eli Friedman78275202009-12-19 08:11:05 +00007059
7060 case SK_StringInit: {
7061 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007062 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007063 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007064 break;
7065 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007066
7067 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007068 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007069 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007070 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007071 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007072
Richard Smith410306b2016-12-12 02:53:20 +00007073 case SK_ArrayLoopIndex: {
7074 Expr *Cur = CurInit.get();
7075 Expr *BaseExpr = new (S.Context)
7076 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7077 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7078 Expr *IndexExpr =
7079 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7080 CurInit = S.CreateBuiltinArraySubscriptExpr(
7081 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7082 ArrayLoopCommonExprs.push_back(BaseExpr);
7083 break;
7084 }
7085
7086 case SK_ArrayLoopInit: {
7087 assert(!ArrayLoopCommonExprs.empty() &&
7088 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7089 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7090 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7091 CurInit.get());
7092 break;
7093 }
7094
Richard Smith378b8c82016-12-14 03:22:16 +00007095 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007096 // Okay: we checked everything before creating this step. Note that
7097 // this is a GNU extension.
7098 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007099 << Step->Type << CurInit.get()->getType()
7100 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007101 LLVM_FALLTHROUGH;
7102 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007103 // If the destination type is an incomplete array type, update the
7104 // type accordingly.
7105 if (ResultType) {
7106 if (const IncompleteArrayType *IncompleteDest
7107 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7108 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007109 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007110 *ResultType = S.Context.getConstantArrayType(
7111 IncompleteDest->getElementType(),
7112 ConstantSource->getSize(),
7113 ArrayType::Normal, 0);
7114 }
7115 }
7116 }
John McCall31168b02011-06-15 23:02:42 +00007117 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007118
Richard Smithebeed412012-02-15 22:38:09 +00007119 case SK_ParenthesizedArrayInit:
7120 // Okay: we checked everything before creating this step. Note that
7121 // this is a GNU extension.
7122 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7123 << CurInit.get()->getSourceRange();
7124 break;
7125
John McCall31168b02011-06-15 23:02:42 +00007126 case SK_PassByIndirectCopyRestore:
7127 case SK_PassByIndirectRestore:
7128 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007129 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7130 CurInit.get(), Step->Type,
7131 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007132 break;
7133
7134 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007135 CurInit =
7136 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7137 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007138 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007139
7140 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007141 S.Diag(CurInit.get()->getExprLoc(),
7142 diag::warn_cxx98_compat_initializer_list_init)
7143 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007144
Richard Smithcc1b96d2013-06-12 22:31:48 +00007145 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007146 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7147 CurInit.get()->getType(), CurInit.get(),
7148 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007149
7150 // Maybe lifetime-extend the array temporary's subobjects to match the
7151 // entity's lifetime.
7152 if (const InitializedEntity *ExtendingEntity =
7153 getEntityForTemporaryLifetimeExtension(&Entity))
7154 if (performReferenceExtension(MTE, ExtendingEntity))
7155 warnOnLifetimeExtension(S, Entity, CurInit.get(),
7156 /*IsInitializerList=*/true,
7157 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007158
7159 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007160 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007161
7162 // Bind the result, in case the library has given initializer_list a
7163 // non-trivial destructor.
7164 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007165 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007166 break;
7167 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007168
Guy Benyei61054192013-02-07 10:55:47 +00007169 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007170 // Sampler initialzation have 5 cases:
7171 // 1. function argument passing
7172 // 1a. argument is a file-scope variable
7173 // 1b. argument is a function-scope variable
7174 // 1c. argument is one of caller function's parameters
7175 // 2. variable initialization
7176 // 2a. initializing a file-scope variable
7177 // 2b. initializing a function-scope variable
7178 //
7179 // For file-scope variables, since they cannot be initialized by function
7180 // call of __translate_sampler_initializer in LLVM IR, their references
7181 // need to be replaced by a cast from their literal initializers to
7182 // sampler type. Since sampler variables can only be used in function
7183 // calls as arguments, we only need to replace them when handling the
7184 // argument passing.
7185 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007186 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007187 Expr *Init = CurInit.get();
7188 QualType SourceType = Init->getType();
7189 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007190 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00007191 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00007192 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7193 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007194 break;
7195 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7196 auto Var = cast<VarDecl>(DRE->getDecl());
7197 // Case 1b and 1c
7198 // No cast from integer to sampler is needed.
7199 if (!Var->hasGlobalStorage()) {
7200 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7201 CK_LValueToRValue, Init,
7202 /*BasePath=*/nullptr, VK_RValue);
7203 break;
7204 }
7205 // Case 1a
7206 // For function call with a file-scope sampler variable as argument,
7207 // get the integer literal.
7208 // Do not diagnose if the file-scope variable does not have initializer
7209 // since this has already been diagnosed when parsing the variable
7210 // declaration.
7211 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7212 break;
7213 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7214 Var->getInit()))->getSubExpr();
7215 SourceType = Init->getType();
7216 }
7217 } else {
7218 // Case 2
7219 // Check initializer is 32 bit integer constant.
7220 // If the initializer is taken from global variable, do not diagnose since
7221 // this has already been done when parsing the variable declaration.
7222 if (!Init->isConstantInitializer(S.Context, false))
7223 break;
7224
7225 if (!SourceType->isIntegerType() ||
7226 32 != S.Context.getIntWidth(SourceType)) {
7227 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7228 << SourceType;
7229 break;
7230 }
7231
7232 llvm::APSInt Result;
7233 Init->EvaluateAsInt(Result, S.Context);
7234 const uint64_t SamplerValue = Result.getLimitedValue();
7235 // 32-bit value of sampler's initializer is interpreted as
7236 // bit-field with the following structure:
7237 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7238 // |31 6|5 4|3 1| 0|
7239 // This structure corresponds to enum values of sampler properties
7240 // defined in SPIR spec v1.2 and also opencl-c.h
7241 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7242 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7243 if (FilterMode != 1 && FilterMode != 2)
7244 S.Diag(Kind.getLocation(),
7245 diag::warn_sampler_initializer_invalid_bits)
7246 << "Filter Mode";
7247 if (AddressingMode > 4)
7248 S.Diag(Kind.getLocation(),
7249 diag::warn_sampler_initializer_invalid_bits)
7250 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00007251 }
7252
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007253 // Cases 1a, 2a and 2b
7254 // Insert cast from integer to sampler.
7255 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7256 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00007257 break;
7258 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007259 case SK_OCLZeroEvent: {
7260 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007261 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007262
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007263 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007264 CK_ZeroToOCLEvent,
7265 CurInit.get()->getValueKind());
7266 break;
7267 }
Egor Churaev89831422016-12-23 14:55:49 +00007268 case SK_OCLZeroQueue: {
7269 assert(Step->Type->isQueueT() &&
7270 "Event initialization on non queue type.");
7271
7272 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7273 CK_ZeroToOCLQueue,
7274 CurInit.get()->getValueKind());
7275 break;
7276 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007277 }
7278 }
John McCall1f425642010-11-11 03:21:53 +00007279
7280 // Diagnose non-fatal problems with the completed initialization.
7281 if (Entity.getKind() == InitializedEntity::EK_Member &&
7282 cast<FieldDecl>(Entity.getDecl())->isBitField())
7283 S.CheckBitFieldInitialization(Kind.getLocation(),
7284 cast<FieldDecl>(Entity.getDecl()),
7285 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007286
Richard Trieuac3eca52015-04-29 01:52:17 +00007287 // Check for std::move on construction.
7288 if (const Expr *E = CurInit.get()) {
7289 CheckMoveOnConstruction(S, E,
7290 Entity.getKind() == InitializedEntity::EK_Result);
7291 }
7292
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007293 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007294}
7295
Richard Smith593f9932012-12-08 02:01:17 +00007296/// Somewhere within T there is an uninitialized reference subobject.
7297/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00007298static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7299 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00007300 if (T->isReferenceType()) {
7301 S.Diag(Loc, diag::err_reference_without_init)
7302 << T.getNonReferenceType();
7303 return true;
7304 }
7305
7306 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7307 if (!RD || !RD->hasUninitializedReferenceMember())
7308 return false;
7309
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007310 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00007311 if (FI->isUnnamedBitfield())
7312 continue;
7313
7314 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7315 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7316 return true;
7317 }
7318 }
7319
Aaron Ballman574705e2014-03-13 15:41:46 +00007320 for (const auto &BI : RD->bases()) {
7321 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00007322 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7323 return true;
7324 }
7325 }
7326
7327 return false;
7328}
7329
7330
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007331//===----------------------------------------------------------------------===//
7332// Diagnose initialization failures
7333//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00007334
7335/// Emit notes associated with an initialization that failed due to a
7336/// "simple" conversion failure.
7337static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7338 Expr *op) {
7339 QualType destType = entity.getType();
7340 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7341 op->getType()->isObjCObjectPointerType()) {
7342
7343 // Emit a possible note about the conversion failing because the
7344 // operand is a message send with a related result type.
7345 S.EmitRelatedResultTypeNote(op);
7346
7347 // Emit a possible note about a return failing because we're
7348 // expecting a related result type.
7349 if (entity.getKind() == InitializedEntity::EK_Result)
7350 S.EmitRelatedResultTypeNoteForReturn(destType);
7351 }
7352}
7353
Richard Smith0449aaf2013-11-21 23:30:57 +00007354static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7355 InitListExpr *InitList) {
7356 QualType DestType = Entity.getType();
7357
7358 QualType E;
7359 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7360 QualType ArrayType = S.Context.getConstantArrayType(
7361 E.withConst(),
7362 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7363 InitList->getNumInits()),
7364 clang::ArrayType::Normal, 0);
7365 InitializedEntity HiddenArray =
7366 InitializedEntity::InitializeTemporary(ArrayType);
7367 return diagnoseListInit(S, HiddenArray, InitList);
7368 }
7369
Richard Smith8d082d12014-09-04 22:13:39 +00007370 if (DestType->isReferenceType()) {
7371 // A list-initialization failure for a reference means that we tried to
7372 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7373 // inner initialization failed.
7374 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7375 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7376 SourceLocation Loc = InitList->getLocStart();
7377 if (auto *D = Entity.getDecl())
7378 Loc = D->getLocation();
7379 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7380 return;
7381 }
7382
Richard Smith0449aaf2013-11-21 23:30:57 +00007383 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00007384 /*VerifyOnly=*/false,
7385 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00007386 assert(DiagnoseInitList.HadError() &&
7387 "Inconsistent init list check result.");
7388}
7389
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007390bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007391 const InitializedEntity &Entity,
7392 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007393 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007394 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007395 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007396
Douglas Gregor1b303932009-12-22 15:35:07 +00007397 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007398 switch (Failure) {
7399 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007400 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007401 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00007402 // Dig out the reference subobject which is uninitialized and diagnose it.
7403 // If this is value-initialization, this could be nested some way within
7404 // the target type.
7405 assert(Kind.getKind() == InitializationKind::IK_Value ||
7406 DestType->isReferenceType());
7407 bool Diagnosed =
7408 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7409 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7410 (void)Diagnosed;
7411 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007412 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007413 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007414 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00007415 case FK_ParenthesizedListInitForReference:
7416 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7417 << 1 << Entity.getType() << Args[0]->getSourceRange();
7418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007419
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007420 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007421 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007422 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007423 case FK_ArrayNeedsInitListOrStringLiteral:
7424 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7425 break;
7426 case FK_ArrayNeedsInitListOrWideStringLiteral:
7427 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7428 break;
7429 case FK_NarrowStringIntoWideCharArray:
7430 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7431 break;
7432 case FK_WideStringIntoCharArray:
7433 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7434 break;
7435 case FK_IncompatWideStringIntoWideChar:
7436 S.Diag(Kind.getLocation(),
7437 diag::err_array_init_incompat_wide_string_into_wchar);
7438 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007439 case FK_ArrayTypeMismatch:
7440 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00007441 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00007442 (Failure == FK_ArrayTypeMismatch
7443 ? diag::err_array_init_different_type
7444 : diag::err_array_init_non_constant_array))
7445 << DestType.getNonReferenceType()
7446 << Args[0]->getType()
7447 << Args[0]->getSourceRange();
7448 break;
7449
John McCalla59dc2f2012-01-05 00:13:19 +00007450 case FK_VariableLengthArrayHasInitializer:
7451 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7452 << Args[0]->getSourceRange();
7453 break;
7454
John McCall16df1e52010-03-30 21:47:33 +00007455 case FK_AddressOfOverloadFailed: {
7456 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007457 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007458 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00007459 true,
7460 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007461 break;
John McCall16df1e52010-03-30 21:47:33 +00007462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007463
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007464 case FK_AddressOfUnaddressableFunction: {
7465 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7466 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7467 Args[0]->getLocStart());
7468 break;
7469 }
7470
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007471 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00007472 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007473 switch (FailedOverloadResult) {
7474 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00007475 if (Failure == FK_UserConversionOverloadFailed)
7476 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7477 << Args[0]->getType() << DestType
7478 << Args[0]->getSourceRange();
7479 else
7480 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7481 << DestType << Args[0]->getType()
7482 << Args[0]->getSourceRange();
7483
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007484 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007485 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007486
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007487 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00007488 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007489 DestType.getNonReferenceType(),
7490 diag::err_typecheck_nonviable_condition_incomplete,
7491 Args[0]->getType(), Args[0]->getSourceRange()))
7492 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00007493 << (Entity.getKind() == InitializedEntity::EK_Result)
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007494 << Args[0]->getType() << Args[0]->getSourceRange()
7495 << DestType.getNonReferenceType();
7496
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007497 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007498 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007499
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007500 case OR_Deleted: {
7501 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7502 << Args[0]->getType() << DestType.getNonReferenceType()
7503 << Args[0]->getSourceRange();
7504 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007505 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00007506 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
7507 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007508 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00007509 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007510 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007511 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007512 }
7513 break;
7514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007516 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007517 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007518 }
7519 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007520
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007521 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00007522 if (isa<InitListExpr>(Args[0])) {
7523 S.Diag(Kind.getLocation(),
7524 diag::err_lvalue_reference_bind_to_initlist)
7525 << DestType.getNonReferenceType().isVolatileQualified()
7526 << DestType.getNonReferenceType()
7527 << Args[0]->getSourceRange();
7528 break;
7529 }
7530 // Intentional fallthrough
7531
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007532 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007533 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007534 Failure == FK_NonConstLValueReferenceBindingToTemporary
7535 ? diag::err_lvalue_reference_bind_to_temporary
7536 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00007537 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007538 << DestType.getNonReferenceType()
7539 << Args[0]->getType()
7540 << Args[0]->getSourceRange();
7541 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007542
Richard Smithb8c0f552016-12-09 18:49:13 +00007543 case FK_NonConstLValueReferenceBindingToBitfield: {
7544 // We don't necessarily have an unambiguous source bit-field.
7545 FieldDecl *BitField = Args[0]->getSourceBitField();
7546 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7547 << DestType.isVolatileQualified()
7548 << (BitField ? BitField->getDeclName() : DeclarationName())
7549 << (BitField != nullptr)
7550 << Args[0]->getSourceRange();
7551 if (BitField)
7552 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7553 break;
7554 }
7555
7556 case FK_NonConstLValueReferenceBindingToVectorElement:
7557 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7558 << DestType.isVolatileQualified()
7559 << Args[0]->getSourceRange();
7560 break;
7561
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007562 case FK_RValueReferenceBindingToLValue:
7563 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00007564 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007565 << Args[0]->getSourceRange();
7566 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007567
Richard Trieuf956a492015-05-16 01:27:03 +00007568 case FK_ReferenceInitDropsQualifiers: {
7569 QualType SourceType = Args[0]->getType();
7570 QualType NonRefType = DestType.getNonReferenceType();
7571 Qualifiers DroppedQualifiers =
7572 SourceType.getQualifiers() - NonRefType.getQualifiers();
7573
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007574 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00007575 << SourceType
7576 << NonRefType
7577 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007578 << Args[0]->getSourceRange();
7579 break;
Richard Trieuf956a492015-05-16 01:27:03 +00007580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007582 case FK_ReferenceInitFailed:
7583 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7584 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00007585 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007586 << Args[0]->getType()
7587 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00007588 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007590
Douglas Gregorb491ed32011-02-19 21:32:49 +00007591 case FK_ConversionFailed: {
7592 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00007593 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00007594 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007595 << DestType
John McCall086a4642010-11-24 05:12:34 +00007596 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00007597 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007598 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00007599 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7600 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00007601 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00007602 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007603 }
John Wiegley01296292011-04-08 18:41:53 +00007604
7605 case FK_ConversionFromPropertyFailed:
7606 // No-op. This error has already been reported.
7607 break;
7608
Douglas Gregor51e77d52009-12-10 17:56:55 +00007609 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00007610 SourceRange R;
7611
David Majnemerbd385442015-04-10 04:52:06 +00007612 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007613 if (InitList && InitList->getNumInits() >= 1) {
David Majnemerbd385442015-04-10 04:52:06 +00007614 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007615 } else {
7616 assert(Args.size() > 1 && "Expected multiple initializers!");
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007617 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007618 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007619
Alp Tokerb6cc5922014-05-03 03:45:55 +00007620 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00007621 if (Kind.isCStyleOrFunctionalCast())
7622 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7623 << R;
7624 else
7625 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7626 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007627 break;
7628 }
7629
Richard Smith49a6b6e2017-03-24 01:14:25 +00007630 case FK_ParenthesizedListInitForScalar:
7631 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7632 << 0 << Entity.getType() << Args[0]->getSourceRange();
7633 break;
7634
Douglas Gregor51e77d52009-12-10 17:56:55 +00007635 case FK_ReferenceBindingToInitList:
7636 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7637 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7638 break;
7639
7640 case FK_InitListBadDestinationType:
7641 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7642 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7643 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007644
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007645 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007646 case FK_ConstructorOverloadFailed: {
7647 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007648 if (Args.size())
7649 ArgsRange = SourceRange(Args.front()->getLocStart(),
7650 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007651
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007652 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00007653 assert(Args.size() == 1 &&
7654 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007655 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007656 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007657 }
7658
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007659 // FIXME: Using "DestType" for the entity we're printing is probably
7660 // bad.
7661 switch (FailedOverloadResult) {
7662 case OR_Ambiguous:
7663 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7664 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007665 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007666 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007667
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007668 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007669 if (Kind.getKind() == InitializationKind::IK_Default &&
7670 (Entity.getKind() == InitializedEntity::EK_Base ||
7671 Entity.getKind() == InitializedEntity::EK_Member) &&
7672 isa<CXXConstructorDecl>(S.CurContext)) {
7673 // This is implicit default initialization of a member or
7674 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00007675 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007676 // initialize this base/member.
7677 CXXConstructorDecl *Constructor
7678 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00007679 const CXXRecordDecl *InheritedFrom = nullptr;
7680 if (auto Inherited = Constructor->getInheritedConstructor())
7681 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007682 if (Entity.getKind() == InitializedEntity::EK_Base) {
7683 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007684 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007685 << S.Context.getTypeDeclType(Constructor->getParent())
7686 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00007687 << Entity.getType()
7688 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007689
7690 RecordDecl *BaseDecl
7691 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7692 ->getDecl();
7693 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7694 << S.Context.getTagDeclType(BaseDecl);
7695 } else {
7696 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007697 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007698 << S.Context.getTypeDeclType(Constructor->getParent())
7699 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00007700 << Entity.getName()
7701 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00007702 S.Diag(Entity.getDecl()->getLocation(),
7703 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007704
7705 if (const RecordType *Record
7706 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007707 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007708 diag::note_previous_decl)
7709 << S.Context.getTagDeclType(Record->getDecl());
7710 }
7711 break;
7712 }
7713
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007714 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7715 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007716 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007717 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007718
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007719 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007720 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007721 OverloadingResult Ovl
7722 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00007723 if (Ovl != OR_Deleted) {
7724 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7725 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007726 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00007727 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007728 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00007729
7730 // If this is a defaulted or implicitly-declared function, then
7731 // it was implicitly deleted. Make it clear that the deletion was
7732 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00007733 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007734 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00007735 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007736 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00007737 else
7738 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7739 << true << DestType << ArgsRange;
7740
7741 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007742 break;
7743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007744
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007745 case OR_Success:
7746 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007747 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007748 }
David Blaikie60deeee2012-01-17 08:24:58 +00007749 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007750
Douglas Gregor85dabae2009-12-16 01:38:02 +00007751 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007752 if (Entity.getKind() == InitializedEntity::EK_Member &&
7753 isa<CXXConstructorDecl>(S.CurContext)) {
7754 // This is implicit default-initialization of a const member in
7755 // a constructor. Complain that it needs to be explicitly
7756 // initialized.
7757 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7758 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007759 << (Constructor->getInheritedConstructor() ? 2 :
7760 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007761 << S.Context.getTypeDeclType(Constructor->getParent())
7762 << /*const=*/1
7763 << Entity.getName();
7764 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7765 << Entity.getName();
7766 } else {
7767 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00007768 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007769 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00007770 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007771
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007772 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00007773 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007774 diag::err_init_incomplete_type);
7775 break;
7776
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007777 case FK_ListInitializationFailed: {
7778 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00007779 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7780 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007781 break;
7782 }
John McCall4124c492011-10-17 18:40:02 +00007783
7784 case FK_PlaceholderType: {
7785 // FIXME: Already diagnosed!
7786 break;
7787 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00007788
Sebastian Redl048a6d72012-04-01 19:54:59 +00007789 case FK_ExplicitConstructor: {
7790 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7791 << Args[0]->getSourceRange();
7792 OverloadCandidateSet::iterator Best;
7793 OverloadingResult Ovl
7794 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00007795 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007796 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7797 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00007798 S.Diag(CtorDecl->getLocation(),
7799 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007800 break;
7801 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007804 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007805 return true;
7806}
Douglas Gregore1314a62009-12-18 05:02:21 +00007807
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007808void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007809 switch (SequenceKind) {
7810 case FailedSequence: {
7811 OS << "Failed sequence: ";
7812 switch (Failure) {
7813 case FK_TooManyInitsForReference:
7814 OS << "too many initializers for reference";
7815 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007816
Richard Smith49a6b6e2017-03-24 01:14:25 +00007817 case FK_ParenthesizedListInitForReference:
7818 OS << "parenthesized list init for reference";
7819 break;
7820
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007821 case FK_ArrayNeedsInitList:
7822 OS << "array requires initializer list";
7823 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007824
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007825 case FK_AddressOfUnaddressableFunction:
7826 OS << "address of unaddressable function was taken";
7827 break;
7828
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007829 case FK_ArrayNeedsInitListOrStringLiteral:
7830 OS << "array requires initializer list or string literal";
7831 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007832
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007833 case FK_ArrayNeedsInitListOrWideStringLiteral:
7834 OS << "array requires initializer list or wide string literal";
7835 break;
7836
7837 case FK_NarrowStringIntoWideCharArray:
7838 OS << "narrow string into wide char array";
7839 break;
7840
7841 case FK_WideStringIntoCharArray:
7842 OS << "wide string into char array";
7843 break;
7844
7845 case FK_IncompatWideStringIntoWideChar:
7846 OS << "incompatible wide string into wide char array";
7847 break;
7848
Douglas Gregore2f943b2011-02-22 18:29:51 +00007849 case FK_ArrayTypeMismatch:
7850 OS << "array type mismatch";
7851 break;
7852
7853 case FK_NonConstantArrayInit:
7854 OS << "non-constant array initializer";
7855 break;
7856
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007857 case FK_AddressOfOverloadFailed:
7858 OS << "address of overloaded function failed";
7859 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007860
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007861 case FK_ReferenceInitOverloadFailed:
7862 OS << "overload resolution for reference initialization failed";
7863 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007864
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007865 case FK_NonConstLValueReferenceBindingToTemporary:
7866 OS << "non-const lvalue reference bound to temporary";
7867 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007868
Richard Smithb8c0f552016-12-09 18:49:13 +00007869 case FK_NonConstLValueReferenceBindingToBitfield:
7870 OS << "non-const lvalue reference bound to bit-field";
7871 break;
7872
7873 case FK_NonConstLValueReferenceBindingToVectorElement:
7874 OS << "non-const lvalue reference bound to vector element";
7875 break;
7876
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007877 case FK_NonConstLValueReferenceBindingToUnrelated:
7878 OS << "non-const lvalue reference bound to unrelated type";
7879 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007880
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007881 case FK_RValueReferenceBindingToLValue:
7882 OS << "rvalue reference bound to an lvalue";
7883 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007884
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007885 case FK_ReferenceInitDropsQualifiers:
7886 OS << "reference initialization drops qualifiers";
7887 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007888
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007889 case FK_ReferenceInitFailed:
7890 OS << "reference initialization failed";
7891 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007892
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007893 case FK_ConversionFailed:
7894 OS << "conversion failed";
7895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007896
John Wiegley01296292011-04-08 18:41:53 +00007897 case FK_ConversionFromPropertyFailed:
7898 OS << "conversion from property failed";
7899 break;
7900
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007901 case FK_TooManyInitsForScalar:
7902 OS << "too many initializers for scalar";
7903 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007904
Richard Smith49a6b6e2017-03-24 01:14:25 +00007905 case FK_ParenthesizedListInitForScalar:
7906 OS << "parenthesized list init for reference";
7907 break;
7908
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007909 case FK_ReferenceBindingToInitList:
7910 OS << "referencing binding to initializer list";
7911 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007912
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007913 case FK_InitListBadDestinationType:
7914 OS << "initializer list for non-aggregate, non-scalar type";
7915 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007916
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007917 case FK_UserConversionOverloadFailed:
7918 OS << "overloading failed for user-defined conversion";
7919 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007920
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007921 case FK_ConstructorOverloadFailed:
7922 OS << "constructor overloading failed";
7923 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007924
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007925 case FK_DefaultInitOfConst:
7926 OS << "default initialization of a const variable";
7927 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007928
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00007929 case FK_Incomplete:
7930 OS << "initialization of incomplete type";
7931 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007932
7933 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007934 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00007935 break;
7936
John McCalla59dc2f2012-01-05 00:13:19 +00007937 case FK_VariableLengthArrayHasInitializer:
7938 OS << "variable length array has an initializer";
7939 break;
7940
John McCall4124c492011-10-17 18:40:02 +00007941 case FK_PlaceholderType:
7942 OS << "initializer expression isn't contextually valid";
7943 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00007944
7945 case FK_ListConstructorOverloadFailed:
7946 OS << "list constructor overloading failed";
7947 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007948
Sebastian Redl048a6d72012-04-01 19:54:59 +00007949 case FK_ExplicitConstructor:
7950 OS << "list copy initialization chose explicit constructor";
7951 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007952 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007953 OS << '\n';
7954 return;
7955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007956
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007957 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007958 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007959 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007960
Sebastian Redld201edf2011-06-05 13:59:11 +00007961 case NormalSequence:
7962 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007963 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007965
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007966 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7967 if (S != step_begin()) {
7968 OS << " -> ";
7969 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007970
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007971 switch (S->Kind) {
7972 case SK_ResolveAddressOfOverloadedFunction:
7973 OS << "resolve address of overloaded function";
7974 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007975
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007976 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00007977 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007978 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007979
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007980 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00007981 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007982 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007983
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007984 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00007985 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007986 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007988 case SK_BindReference:
7989 OS << "bind reference to lvalue";
7990 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007991
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007992 case SK_BindReferenceToTemporary:
7993 OS << "bind reference to a temporary";
7994 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007995
Richard Smithb8c0f552016-12-09 18:49:13 +00007996 case SK_FinalCopy:
7997 OS << "final copy in class direct-initialization";
7998 break;
7999
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008000 case SK_ExtraneousCopyToTemporary:
8001 OS << "extraneous C++03 copy to temporary";
8002 break;
8003
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008004 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008005 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008006 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008007
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008008 case SK_QualificationConversionRValue:
8009 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008010 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008011
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008012 case SK_QualificationConversionXValue:
8013 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008014 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008015
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008016 case SK_QualificationConversionLValue:
8017 OS << "qualification conversion (lvalue)";
8018 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008019
Richard Smith77be48a2014-07-31 06:31:19 +00008020 case SK_AtomicConversion:
8021 OS << "non-atomic-to-atomic conversion";
8022 break;
8023
Jordan Roseb1312a52013-04-11 00:58:58 +00008024 case SK_LValueToRValue:
8025 OS << "load (lvalue to rvalue)";
8026 break;
8027
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008028 case SK_ConversionSequence:
8029 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008030 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008031 OS << ")";
8032 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008033
Richard Smithaaa0ec42013-09-21 21:19:19 +00008034 case SK_ConversionSequenceNoNarrowing:
8035 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008036 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008037 OS << ")";
8038 break;
8039
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008040 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008041 OS << "list aggregate initialization";
8042 break;
8043
Sebastian Redl29526f02011-11-27 16:50:07 +00008044 case SK_UnwrapInitList:
8045 OS << "unwrap reference initializer list";
8046 break;
8047
8048 case SK_RewrapInitList:
8049 OS << "rewrap reference initializer list";
8050 break;
8051
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008052 case SK_ConstructorInitialization:
8053 OS << "constructor initialization";
8054 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008055
Richard Smith53324112014-07-16 21:33:43 +00008056 case SK_ConstructorInitializationFromList:
8057 OS << "list initialization via constructor";
8058 break;
8059
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008060 case SK_ZeroInitialization:
8061 OS << "zero initialization";
8062 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008063
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008064 case SK_CAssignment:
8065 OS << "C assignment";
8066 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008067
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008068 case SK_StringInit:
8069 OS << "string initialization";
8070 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008071
8072 case SK_ObjCObjectConversion:
8073 OS << "Objective-C object conversion";
8074 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008075
Richard Smith410306b2016-12-12 02:53:20 +00008076 case SK_ArrayLoopIndex:
8077 OS << "indexing for array initialization loop";
8078 break;
8079
8080 case SK_ArrayLoopInit:
8081 OS << "array initialization loop";
8082 break;
8083
Douglas Gregore2f943b2011-02-22 18:29:51 +00008084 case SK_ArrayInit:
8085 OS << "array initialization";
8086 break;
John McCall31168b02011-06-15 23:02:42 +00008087
Richard Smith378b8c82016-12-14 03:22:16 +00008088 case SK_GNUArrayInit:
8089 OS << "array initialization (GNU extension)";
8090 break;
8091
Richard Smithebeed412012-02-15 22:38:09 +00008092 case SK_ParenthesizedArrayInit:
8093 OS << "parenthesized array initialization";
8094 break;
8095
John McCall31168b02011-06-15 23:02:42 +00008096 case SK_PassByIndirectCopyRestore:
8097 OS << "pass by indirect copy and restore";
8098 break;
8099
8100 case SK_PassByIndirectRestore:
8101 OS << "pass by indirect restore";
8102 break;
8103
8104 case SK_ProduceObjCObject:
8105 OS << "Objective-C object retension";
8106 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008107
8108 case SK_StdInitializerList:
8109 OS << "std::initializer_list from initializer list";
8110 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008111
Richard Smithf8adcdc2014-07-17 05:12:35 +00008112 case SK_StdInitializerListConstructorCall:
8113 OS << "list initialization from std::initializer_list";
8114 break;
8115
Guy Benyei61054192013-02-07 10:55:47 +00008116 case SK_OCLSamplerInit:
8117 OS << "OpenCL sampler_t from integer constant";
8118 break;
8119
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008120 case SK_OCLZeroEvent:
8121 OS << "OpenCL event_t from zero";
8122 break;
Egor Churaev89831422016-12-23 14:55:49 +00008123
8124 case SK_OCLZeroQueue:
8125 OS << "OpenCL queue_t from zero";
8126 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008127 }
Richard Smith6b216962013-02-05 05:52:24 +00008128
8129 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008130 }
Richard Smith6b216962013-02-05 05:52:24 +00008131
8132 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008133}
8134
8135void InitializationSequence::dump() const {
8136 dump(llvm::errs());
8137}
8138
Richard Smithaaa0ec42013-09-21 21:19:19 +00008139static void DiagnoseNarrowingInInitList(Sema &S,
8140 const ImplicitConversionSequence &ICS,
8141 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008142 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008143 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008144 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008145 switch (ICS.getKind()) {
8146 case ImplicitConversionSequence::StandardConversion:
8147 SCS = &ICS.Standard;
8148 break;
8149 case ImplicitConversionSequence::UserDefinedConversion:
8150 SCS = &ICS.UserDefined.After;
8151 break;
8152 case ImplicitConversionSequence::AmbiguousConversion:
8153 case ImplicitConversionSequence::EllipsisConversion:
8154 case ImplicitConversionSequence::BadConversion:
8155 return;
8156 }
8157
Richard Smith66e05fe2012-01-18 05:21:49 +00008158 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8159 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00008160 QualType ConstantType;
8161 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8162 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00008163 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00008164 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00008165 // No narrowing occurred.
8166 return;
8167
8168 case NK_Type_Narrowing:
8169 // This was a floating-to-integer conversion, which is always considered a
8170 // narrowing conversion even if the value is a constant and can be
8171 // represented exactly as an integer.
8172 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008173 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8174 ? diag::warn_init_list_type_narrowing
8175 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008176 << PostInit->getSourceRange()
8177 << PreNarrowingType.getLocalUnqualifiedType()
8178 << EntityType.getLocalUnqualifiedType();
8179 break;
8180
8181 case NK_Constant_Narrowing:
8182 // A constant value was narrowed.
8183 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008184 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8185 ? diag::warn_init_list_constant_narrowing
8186 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008187 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00008188 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00008189 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008190 break;
8191
8192 case NK_Variable_Narrowing:
8193 // A variable's value may have been narrowed.
8194 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008195 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8196 ? diag::warn_init_list_variable_narrowing
8197 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008198 << PostInit->getSourceRange()
8199 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00008200 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008201 break;
8202 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008203
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008204 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008205 llvm::raw_svector_ostream OS(StaticCast);
8206 OS << "static_cast<";
8207 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8208 // It's important to use the typedef's name if there is one so that the
8209 // fixit doesn't break code using types like int64_t.
8210 //
8211 // FIXME: This will break if the typedef requires qualification. But
8212 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008213 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008214 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00008215 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008216 else {
8217 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8218 // with a broken cast.
8219 return;
8220 }
8221 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00008222 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008223 << PostInit->getSourceRange()
8224 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8225 << FixItHint::CreateInsertion(
8226 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008227}
8228
Douglas Gregore1314a62009-12-18 05:02:21 +00008229//===----------------------------------------------------------------------===//
8230// Initialization helper functions
8231//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00008232bool
8233Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8234 ExprResult Init) {
8235 if (Init.isInvalid())
8236 return false;
8237
8238 Expr *InitE = Init.get();
8239 assert(InitE && "No initialization expression");
8240
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00008241 InitializationKind Kind
8242 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008243 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00008244 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00008245}
8246
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008247ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00008248Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8249 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008250 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00008251 bool TopLevelOfInitList,
8252 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00008253 if (Init.isInvalid())
8254 return ExprError();
8255
John McCall1f425642010-11-11 03:21:53 +00008256 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00008257 assert(InitE && "No initialization expression?");
8258
8259 if (EqualLoc.isInvalid())
8260 EqualLoc = InitE->getLocStart();
8261
8262 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00008263 EqualLoc,
8264 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00008265 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008266
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008267 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00008268
Richard Smith66e05fe2012-01-18 05:21:49 +00008269 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00008270}
Richard Smith60437622017-02-09 19:17:44 +00008271
8272QualType Sema::DeduceTemplateSpecializationFromInitializer(
8273 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8274 const InitializationKind &Kind, MultiExprArg Inits) {
8275 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8276 TSInfo->getType()->getContainedDeducedType());
8277 assert(DeducedTST && "not a deduced template specialization type");
8278
8279 // We can only perform deduction for class templates.
8280 auto TemplateName = DeducedTST->getTemplateName();
8281 auto *Template =
8282 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8283 if (!Template) {
8284 Diag(Kind.getLocation(),
8285 diag::err_deduced_non_class_template_specialization_type)
8286 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8287 if (auto *TD = TemplateName.getAsTemplateDecl())
8288 Diag(TD->getLocation(), diag::note_template_decl_here);
8289 return QualType();
8290 }
8291
Richard Smith32918772017-02-14 00:25:28 +00008292 // Can't deduce from dependent arguments.
8293 if (Expr::hasAnyTypeDependentArguments(Inits))
8294 return Context.DependentTy;
8295
Richard Smith60437622017-02-09 19:17:44 +00008296 // FIXME: Perform "exact type" matching first, per CWG discussion?
8297 // Or implement this via an implied 'T(T) -> T' deduction guide?
8298
8299 // FIXME: Do we need/want a std::initializer_list<T> special case?
8300
Richard Smith32918772017-02-14 00:25:28 +00008301 // Look up deduction guides, including those synthesized from constructors.
8302 //
Richard Smith60437622017-02-09 19:17:44 +00008303 // C++1z [over.match.class.deduct]p1:
8304 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00008305 // - For each constructor of the class template designated by the
8306 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00008307 // - For each deduction-guide, a function or function template [...]
8308 DeclarationNameInfo NameInfo(
8309 Context.DeclarationNames.getCXXDeductionGuideName(Template),
8310 TSInfo->getTypeLoc().getEndLoc());
8311 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
8312 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00008313
8314 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
8315 // clear on this, but they're not found by name so access does not apply.
8316 Guides.suppressDiagnostics();
8317
8318 // Figure out if this is list-initialization.
8319 InitListExpr *ListInit =
8320 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
8321 ? dyn_cast<InitListExpr>(Inits[0])
8322 : nullptr;
8323
8324 // C++1z [over.match.class.deduct]p1:
8325 // Initialization and overload resolution are performed as described in
8326 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
8327 // (as appropriate for the type of initialization performed) for an object
8328 // of a hypothetical class type, where the selected functions and function
8329 // templates are considered to be the constructors of that class type
8330 //
8331 // Since we know we're initializing a class type of a type unrelated to that
8332 // of the initializer, this reduces to something fairly reasonable.
8333 OverloadCandidateSet Candidates(Kind.getLocation(),
8334 OverloadCandidateSet::CSK_Normal);
8335 OverloadCandidateSet::iterator Best;
8336 auto tryToResolveOverload =
8337 [&](bool OnlyListConstructors) -> OverloadingResult {
8338 Candidates.clear();
Richard Smith32918772017-02-14 00:25:28 +00008339 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
8340 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00008341 if (D->isInvalidDecl())
8342 continue;
8343
Richard Smithbc491202017-02-17 20:05:37 +00008344 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
8345 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
8346 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
8347 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00008348 continue;
8349
8350 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
8351 // For copy-initialization, the candidate functions are all the
8352 // converting constructors (12.3.1) of that class.
8353 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
8354 // The converting constructors of T are candidate functions.
8355 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00008356 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00008357 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00008358 continue;
Richard Smith60437622017-02-09 19:17:44 +00008359
8360 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00008361 // could never be called with one argument are not interesting to
8362 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00008363 if (GD->getMinRequiredArguments() > 1 ||
8364 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00008365 continue;
8366 }
8367
8368 // C++ [over.match.list]p1.1: (first phase list initialization)
8369 // Initially, the candidate functions are the initializer-list
8370 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00008371 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00008372 continue;
8373
8374 // C++ [over.match.list]p1.2: (second phase list initialization)
8375 // the candidate functions are all the constructors of the class T
8376 // C++ [over.match.ctor]p1: (all other cases)
8377 // the candidate functions are all the constructors of the class of
8378 // the object being initialized
8379
8380 // C++ [over.best.ics]p4:
8381 // When [...] the constructor [...] is a candidate by
8382 // - [over.match.copy] (in all cases)
8383 // FIXME: The "second phase of [over.match.list] case can also
8384 // theoretically happen here, but it's not clear whether we can
8385 // ever have a parameter of the right type.
8386 bool SuppressUserConversions = Kind.isCopyInit();
8387
Richard Smith60437622017-02-09 19:17:44 +00008388 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00008389 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
8390 Inits, Candidates,
8391 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00008392 else
Richard Smithbc491202017-02-17 20:05:37 +00008393 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00008394 SuppressUserConversions);
8395 }
8396 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
8397 };
8398
8399 OverloadingResult Result = OR_No_Viable_Function;
8400
8401 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
8402 // try initializer-list constructors.
8403 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00008404 bool TryListConstructors = true;
8405
8406 // Try list constructors unless the list is empty and the class has one or
8407 // more default constructors, in which case those constructors win.
8408 if (!ListInit->getNumInits()) {
8409 for (NamedDecl *D : Guides) {
8410 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
8411 if (FD && FD->getMinRequiredArguments() == 0) {
8412 TryListConstructors = false;
8413 break;
8414 }
8415 }
8416 }
8417
8418 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00008419 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
8420 // Then unwrap the initializer list and try again considering all
8421 // constructors.
8422 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
8423 }
8424
8425 // If list-initialization fails, or if we're doing any other kind of
8426 // initialization, we (eventually) consider constructors.
8427 if (Result == OR_No_Viable_Function)
8428 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
8429
8430 switch (Result) {
8431 case OR_Ambiguous:
8432 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
8433 << TemplateName;
8434 // FIXME: For list-initialization candidates, it'd usually be better to
8435 // list why they were not viable when given the initializer list itself as
8436 // an argument.
8437 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
8438 return QualType();
8439
Richard Smith32918772017-02-14 00:25:28 +00008440 case OR_No_Viable_Function: {
8441 CXXRecordDecl *Primary =
8442 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
8443 bool Complete =
8444 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00008445 Diag(Kind.getLocation(),
8446 Complete ? diag::err_deduced_class_template_ctor_no_viable
8447 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00008448 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00008449 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
8450 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00008451 }
Richard Smith60437622017-02-09 19:17:44 +00008452
8453 case OR_Deleted: {
8454 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
8455 << TemplateName;
8456 NoteDeletedFunction(Best->Function);
8457 return QualType();
8458 }
8459
8460 case OR_Success:
8461 // C++ [over.match.list]p1:
8462 // In copy-list-initialization, if an explicit constructor is chosen, the
8463 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00008464 if (Kind.isCopyInit() && ListInit &&
8465 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00008466 bool IsDeductionGuide = !Best->Function->isImplicit();
8467 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
8468 << TemplateName << IsDeductionGuide;
8469 Diag(Best->Function->getLocation(),
8470 diag::note_explicit_ctor_deduction_guide_here)
8471 << IsDeductionGuide;
8472 return QualType();
8473 }
8474
8475 // Make sure we didn't select an unusable deduction guide, and mark it
8476 // as referenced.
8477 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
8478 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
8479 break;
8480 }
8481
8482 // C++ [dcl.type.class.deduct]p1:
8483 // The placeholder is replaced by the return type of the function selected
8484 // by overload resolution for class template deduction.
8485 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
8486}