blob: cf98805ebd8baa4c21fe73bd14f036aa339e32c5 [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,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000355 InitListExpr *OuterILE, unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000356 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000357 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
358 Expr *InitExpr, FieldDecl *Field,
359 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000360 void CheckEmptyInitializable(const InitializedEntity &Entity,
361 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000362
Douglas Gregor85df8d82009-01-29 00:45:39 +0000363public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000364 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000365 InitListExpr *IL, QualType &T, bool VerifyOnly,
366 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000367 bool HadError() { return hadError; }
368
369 // @brief Retrieves the fully-structured initializer list used for
370 // semantic analysis and code generation.
371 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
372};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000373
Chris Lattner9ececce2009-02-24 22:48:58 +0000374} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000375
Richard Smith454a7cd2014-06-03 08:26:00 +0000376ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
377 SourceLocation Loc,
378 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000379 bool VerifyOnly,
380 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000381 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
382 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000383 MultiExprArg SubInit;
384 Expr *InitExpr;
385 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
386
387 // C++ [dcl.init.aggr]p7:
388 // If there are fewer initializer-clauses in the list than there are
389 // members in the aggregate, then each member not explicitly initialized
390 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000391 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
392 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
393 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000394 // C++1y / DR1070:
395 // shall be initialized [...] from an empty initializer list.
396 //
397 // We apply the resolution of this DR to C++11 but not C++98, since C++98
398 // does not have useful semantics for initialization from an init list.
399 // We treat this as copy-initialization, because aggregate initialization
400 // always performs copy-initialization on its elements.
401 //
402 // Only do this if we're initializing a class type, to avoid filling in
403 // the initializer list where possible.
404 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
405 InitListExpr(SemaRef.Context, Loc, None, Loc);
406 InitExpr->setType(SemaRef.Context.VoidTy);
407 SubInit = InitExpr;
408 Kind = InitializationKind::CreateCopy(Loc, Loc);
409 } else {
410 // C++03:
411 // shall be value-initialized.
412 }
413
414 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000415 // libstdc++4.6 marks the vector default constructor as explicit in
416 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
417 // stlport does so too. Look for std::__debug for libstdc++, and for
418 // std:: for stlport. This is effectively a compiler-side implementation of
419 // LWG2193.
420 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
421 InitializationSequence::FK_ExplicitConstructor) {
422 OverloadCandidateSet::iterator Best;
423 OverloadingResult O =
424 InitSeq.getFailedCandidateSet()
425 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
426 (void)O;
427 assert(O == OR_Success && "Inconsistent overload resolution");
428 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
429 CXXRecordDecl *R = CtorDecl->getParent();
430
431 if (CtorDecl->getMinRequiredArguments() == 0 &&
432 CtorDecl->isExplicit() && R->getDeclName() &&
433 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000434 bool IsInStd = false;
435 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000436 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000437 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
438 IsInStd = true;
439 }
440
441 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
442 .Cases("basic_string", "deque", "forward_list", true)
443 .Cases("list", "map", "multimap", "multiset", true)
444 .Cases("priority_queue", "queue", "set", "stack", true)
445 .Cases("unordered_map", "unordered_set", "vector", true)
446 .Default(false)) {
447 InitSeq.InitializeFrom(
448 SemaRef, Entity,
449 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000450 MultiExprArg(), /*TopLevelOfInitList=*/false,
451 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000452 // Emit a warning for this. System header warnings aren't shown
453 // by default, but people working on system headers should see it.
454 if (!VerifyOnly) {
455 SemaRef.Diag(CtorDecl->getLocation(),
456 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000457 if (Entity.getKind() == InitializedEntity::EK_Member)
458 SemaRef.Diag(Entity.getDecl()->getLocation(),
459 diag::note_used_in_initialization_here);
460 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
461 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000462 }
463 }
464 }
465 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000466 if (!InitSeq) {
467 if (!VerifyOnly) {
468 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
469 if (Entity.getKind() == InitializedEntity::EK_Member)
470 SemaRef.Diag(Entity.getDecl()->getLocation(),
471 diag::note_in_omitted_aggregate_initializer)
472 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000473 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
474 bool IsTrailingArrayNewMember =
475 Entity.getParent() &&
476 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000477 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000478 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
479 << Entity.getElementIndex();
480 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000481 }
482 return ExprError();
483 }
484
485 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
486 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
487}
488
489void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
490 SourceLocation Loc) {
491 assert(VerifyOnly &&
492 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000493 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
494 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000495 hadError = true;
496}
497
Richard Smith872307e2016-03-08 22:17:41 +0000498void InitListChecker::FillInEmptyInitForBase(
499 unsigned Init, const CXXBaseSpecifier &Base,
500 const InitializedEntity &ParentEntity, InitListExpr *ILE,
501 bool &RequiresSecondPass, bool FillWithNoInit) {
502 assert(Init < ILE->getNumInits() && "should have been expanded");
503
504 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
505 SemaRef.Context, &Base, false, &ParentEntity);
506
507 if (!ILE->getInit(Init)) {
508 ExprResult BaseInit =
509 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
510 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
Manman Ren073db022016-03-10 18:53:19 +0000511 /*VerifyOnly*/ false,
512 TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000513 if (BaseInit.isInvalid()) {
514 hadError = true;
515 return;
516 }
517
518 ILE->setInit(Init, BaseInit.getAs<Expr>());
519 } else if (InitListExpr *InnerILE =
520 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
Richard Smithf3b4ca82018-02-07 22:25:16 +0000521 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
522 ILE, Init, FillWithNoInit);
Richard Smith872307e2016-03-08 22:17:41 +0000523 } else if (DesignatedInitUpdateExpr *InnerDIUE =
524 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
525 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000526 RequiresSecondPass, ILE, Init,
527 /*FillWithNoInit =*/true);
Richard Smith872307e2016-03-08 22:17:41 +0000528 }
529}
530
Richard Smith454a7cd2014-06-03 08:26:00 +0000531void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000532 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000534 bool &RequiresSecondPass,
535 bool FillWithNoInit) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000536 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000537 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000538 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000539 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000540
541 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
542 if (!RType->getDecl()->isUnion())
543 assert(Init < NumInits && "This ILE should have been expanded");
544
Douglas Gregor2bb07652009-12-22 00:05:34 +0000545 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000546 if (FillWithNoInit) {
547 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
548 if (Init < NumInits)
549 ILE->setInit(Init, Filler);
550 else
551 ILE->updateInit(SemaRef.Context, Init, Filler);
552 return;
553 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000554 // C++1y [dcl.init.aggr]p7:
555 // If there are fewer initializer-clauses in the list than there are
556 // members in the aggregate, then each member not explicitly initialized
557 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000558 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000559 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
560 if (DIE.isInvalid()) {
561 hadError = true;
562 return;
563 }
Richard Smith852c9db2013-04-20 22:23:05 +0000564 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000565 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000566 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000567 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000568 RequiresSecondPass = true;
569 }
570 return;
571 }
572
Douglas Gregor2bb07652009-12-22 00:05:34 +0000573 if (Field->getType()->isReferenceType()) {
574 // C++ [dcl.init.aggr]p9:
575 // If an incomplete or empty initializer-list leaves a
576 // member of reference type uninitialized, the program is
577 // ill-formed.
578 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
579 << Field->getType()
580 << ILE->getSyntacticForm()->getSourceRange();
581 SemaRef.Diag(Field->getLocation(),
582 diag::note_uninit_reference_member);
583 hadError = true;
584 return;
585 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Richard Smith454a7cd2014-06-03 08:26:00 +0000587 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000588 /*VerifyOnly*/false,
589 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000590 if (MemberInit.isInvalid()) {
591 hadError = true;
592 return;
593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594
Douglas Gregor2bb07652009-12-22 00:05:34 +0000595 if (hadError) {
596 // Do nothing
597 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000598 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000599 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
600 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000601 // extend the initializer list to include the constructor
602 // call and make a note that we'll need to take another pass
603 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000604 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000605 RequiresSecondPass = true;
606 }
607 } else if (InitListExpr *InnerILE
608 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000609 FillInEmptyInitializations(MemberEntity, InnerILE,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000610 RequiresSecondPass, ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000611 else if (DesignatedInitUpdateExpr *InnerDIUE
612 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
613 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000614 RequiresSecondPass, ILE, Init,
615 /*FillWithNoInit =*/true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000616}
617
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000618/// Recursively replaces NULL values within the given initializer list
619/// with expressions that perform value-initialization of the
Richard Smithf3b4ca82018-02-07 22:25:16 +0000620/// appropriate type, and finish off the InitListExpr formation.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000621void
Richard Smith454a7cd2014-06-03 08:26:00 +0000622InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000623 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000624 bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000625 InitListExpr *OuterILE,
626 unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000627 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000628 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000629 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000630
Richard Smithf3b4ca82018-02-07 22:25:16 +0000631 // If this is a nested initializer list, we might have changed its contents
632 // (and therefore some of its properties, such as instantiation-dependence)
633 // while filling it in. Inform the outer initializer list so that its state
634 // can be updated to match.
635 // FIXME: We should fully build the inner initializers before constructing
636 // the outer InitListExpr instead of mutating AST nodes after they have
637 // been used as subexpressions of other nodes.
638 struct UpdateOuterILEWithUpdatedInit {
639 InitListExpr *Outer;
640 unsigned OuterIndex;
641 ~UpdateOuterILEWithUpdatedInit() {
642 if (Outer)
643 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
644 }
645 } UpdateOuterRAII = {OuterILE, OuterIndex};
646
Richard Smith382bc512017-02-23 22:41:47 +0000647 // A transparent ILE is not performing aggregate initialization and should
648 // not be filled in.
649 if (ILE->isTransparent())
650 return;
651
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000652 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000653 const RecordDecl *RDecl = RType->getDecl();
654 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000655 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000656 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000657 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
658 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000659 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000660 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000661 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
662 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000663 break;
664 }
665 }
666 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000667 // The fields beyond ILE->getNumInits() are default initialized, so in
668 // order to leave them uninitialized, the ILE is expanded and the extra
669 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000670 unsigned NumElems = numStructUnionElements(ILE->getType());
671 if (RDecl->hasFlexibleArrayMember())
672 ++NumElems;
673 if (ILE->getNumInits() < NumElems)
674 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000675
Douglas Gregor2bb07652009-12-22 00:05:34 +0000676 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000677
678 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
679 for (auto &Base : CXXRD->bases()) {
680 if (hadError)
681 return;
682
683 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
684 FillWithNoInit);
685 ++Init;
686 }
687 }
688
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000689 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000690 if (Field->isUnnamedBitfield())
691 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692
Douglas Gregor2bb07652009-12-22 00:05:34 +0000693 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000694 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000695
Yunzhong Gaocb779302015-06-10 00:27:52 +0000696 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
697 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000698 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000699 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000700
Douglas Gregor2bb07652009-12-22 00:05:34 +0000701 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000702
Douglas Gregor2bb07652009-12-22 00:05:34 +0000703 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000704 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000705 break;
706 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000707 }
708
709 return;
Mike Stump11289f42009-09-09 15:08:12 +0000710 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000711
712 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000713
Douglas Gregor723796a2009-12-16 06:35:08 +0000714 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000715 unsigned NumInits = ILE->getNumInits();
716 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000717 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000718 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000719 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000720 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000721 // For an array new with an unknown bound, ask for one additional element
722 // in order to populate the array filler.
723 if (Entity.isVariableLengthArrayNew())
724 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000726 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000727 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000728 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000729 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000731 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000732 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000733 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000734
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000735 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000736 if (hadError)
737 return;
738
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000739 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
740 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000741 ElementEntity.setElementIndex(Init);
742
Craig Topperc3ec1492014-05-26 06:22:03 +0000743 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000744 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
745 ILE->setInit(Init, ILE->getArrayFiller());
746 else if (!InitExpr && !ILE->hasArrayFiller()) {
747 Expr *Filler = nullptr;
748
749 if (FillWithNoInit)
750 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
751 else {
752 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
753 ElementEntity,
Manman Ren073db022016-03-10 18:53:19 +0000754 /*VerifyOnly*/false,
755 TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000756 if (ElementInit.isInvalid()) {
757 hadError = true;
758 return;
759 }
760
761 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000762 }
763
764 if (hadError) {
765 // Do nothing
766 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000767 // For arrays, just set the expression used for value-initialization
768 // of the "holes" in the array.
769 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000770 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000771 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000772 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000773 } else {
774 // For arrays, just set the expression used for value-initialization
775 // of the rest of elements and exit.
776 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000777 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000778 return;
779 }
780
Yunzhong Gaocb779302015-06-10 00:27:52 +0000781 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000782 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000783 // extend the initializer list to include the constructor
784 // call and make a note that we'll need to take another pass
785 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000786 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000787 RequiresSecondPass = true;
788 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000789 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000790 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000791 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000792 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000793 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000794 else if (DesignatedInitUpdateExpr *InnerDIUE
795 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
796 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000797 RequiresSecondPass, ILE, Init,
798 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000799 }
800}
801
Douglas Gregor723796a2009-12-16 06:35:08 +0000802InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000803 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000804 bool VerifyOnly,
805 bool TreatUnavailableAsInvalid)
806 : SemaRef(S), VerifyOnly(VerifyOnly),
807 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000808 // FIXME: Check that IL isn't already the semantic form of some other
809 // InitListExpr. If it is, we'd create a broken AST.
810
Steve Narofff8ecff22008-05-01 22:18:59 +0000811 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000812
Richard Smith4e0d2e42013-09-20 20:10:22 +0000813 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000814 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000815 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000816 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000817
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000818 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000819 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000820 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
821 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000822 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000823 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000824 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000825 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000826}
827
828int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000829 // FIXME: use a proper constant
830 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000831 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000832 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000833 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
834 }
835 return maxElements;
836}
837
838int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000839 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000840 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000841 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
842 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000843 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000844 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000845 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000846
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000847 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000848 return std::min(InitializableMembers, 1);
849 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000850}
851
Richard Smith283e2072017-10-03 20:36:00 +0000852/// Determine whether Entity is an entity for which it is idiomatic to elide
853/// the braces in aggregate initialization.
854static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
855 // Recursive initialization of the one and only field within an aggregate
856 // class is considered idiomatic. This case arises in particular for
857 // initialization of std::array, where the C++ standard suggests the idiom of
858 //
859 // std::array<T, N> arr = {1, 2, 3};
860 //
861 // (where std::array is an aggregate struct containing a single array field.
862
863 // FIXME: Should aggregate initialization of a struct with a single
864 // base class and no members also suppress the warning?
865 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
866 return false;
867
868 auto *ParentRD =
869 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
870 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
871 if (CXXRD->getNumBases())
872 return false;
873
874 auto FieldIt = ParentRD->field_begin();
875 assert(FieldIt != ParentRD->field_end() &&
876 "no fields but have initializer for member?");
877 return ++FieldIt == ParentRD->field_end();
878}
879
Richard Smith4e0d2e42013-09-20 20:10:22 +0000880/// Check whether the range of the initializer \p ParentIList from element
881/// \p Index onwards can be used to initialize an object of type \p T. Update
882/// \p Index to indicate how many elements of the list were consumed.
883///
884/// This also fills in \p StructuredList, from element \p StructuredIndex
885/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000886void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000887 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000888 QualType T, unsigned &Index,
889 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000890 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000891 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000892
Steve Narofff8ecff22008-05-01 22:18:59 +0000893 if (T->isArrayType())
894 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000895 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000896 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000897 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000898 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000899 else
David Blaikie83d382b2011-09-23 05:06:16 +0000900 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000901
Eli Friedmane0f832b2008-05-25 13:49:22 +0000902 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000903 if (!VerifyOnly)
904 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
905 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000906 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000907 hadError = true;
908 return;
909 }
910
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000911 // Build a structured initializer list corresponding to this subobject.
912 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000913 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
914 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000915 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000916 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000917 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000918
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000919 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000920 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000921 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000922 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000923 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000924 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000925
Richard Smithde229232013-06-06 11:41:05 +0000926 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000927 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000928
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000929 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000930 // Update the structured sub-object initializer so that it's ending
931 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000932 if (EndIndex < ParentIList->getNumInits() &&
933 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000934 SourceLocation EndLoc
935 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
936 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000939 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000940 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000941 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
942 !isIdiomaticBraceElisionEntity(Entity)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000943 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000944 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000945 << StructuredSubobjectInitList->getSourceRange()
946 << FixItHint::CreateInsertion(
947 StructuredSubobjectInitList->getLocStart(), "{")
948 << FixItHint::CreateInsertion(
949 SemaRef.getLocForEndOfToken(
950 StructuredSubobjectInitList->getLocEnd()),
951 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000952 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000953 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000954}
955
Richard Smith420fa122015-02-12 01:50:05 +0000956/// Warn that \p Entity was of scalar type and was initialized by a
957/// single-element braced initializer list.
958static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
959 SourceRange Braces) {
960 // Don't warn during template instantiation. If the initialization was
961 // non-dependent, we warned during the initial parse; otherwise, the
962 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000963 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000964 return;
965
966 unsigned DiagID = 0;
967
968 switch (Entity.getKind()) {
969 case InitializedEntity::EK_VectorElement:
970 case InitializedEntity::EK_ComplexElement:
971 case InitializedEntity::EK_ArrayElement:
972 case InitializedEntity::EK_Parameter:
973 case InitializedEntity::EK_Parameter_CF_Audited:
974 case InitializedEntity::EK_Result:
975 // Extra braces here are suspicious.
976 DiagID = diag::warn_braces_around_scalar_init;
977 break;
978
979 case InitializedEntity::EK_Member:
980 // Warn on aggregate initialization but not on ctor init list or
981 // default member initializer.
982 if (Entity.getParent())
983 DiagID = diag::warn_braces_around_scalar_init;
984 break;
985
986 case InitializedEntity::EK_Variable:
987 case InitializedEntity::EK_LambdaCapture:
988 // No warning, might be direct-list-initialization.
989 // FIXME: Should we warn for copy-list-initialization in these cases?
990 break;
991
992 case InitializedEntity::EK_New:
993 case InitializedEntity::EK_Temporary:
994 case InitializedEntity::EK_CompoundLiteralInit:
995 // No warning, braces are part of the syntax of the underlying construct.
996 break;
997
998 case InitializedEntity::EK_RelatedResult:
999 // No warning, we already warned when initializing the result.
1000 break;
1001
1002 case InitializedEntity::EK_Exception:
1003 case InitializedEntity::EK_Base:
1004 case InitializedEntity::EK_Delegating:
1005 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001006 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001007 case InitializedEntity::EK_Binding:
Richard Smith420fa122015-02-12 01:50:05 +00001008 llvm_unreachable("unexpected braced scalar init");
1009 }
1010
1011 if (DiagID) {
1012 S.Diag(Braces.getBegin(), DiagID)
1013 << Braces
1014 << FixItHint::CreateRemoval(Braces.getBegin())
1015 << FixItHint::CreateRemoval(Braces.getEnd());
1016 }
1017}
1018
Richard Smith4e0d2e42013-09-20 20:10:22 +00001019/// Check whether the initializer \p IList (that was written with explicit
1020/// braces) can be used to initialize an object of type \p T.
1021///
1022/// This also fills in \p StructuredList with the fully-braced, desugared
1023/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001024void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001025 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001026 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001027 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001028 if (!VerifyOnly) {
1029 SyntacticToSemantic[IList] = StructuredList;
1030 StructuredList->setSyntacticForm(IList);
1031 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001032
1033 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001035 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001036 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001037 QualType ExprTy = T;
1038 if (!ExprTy->isArrayType())
1039 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001040 IList->setType(ExprTy);
1041 StructuredList->setType(ExprTy);
1042 }
Eli Friedman85f54972008-05-25 13:22:35 +00001043 if (hadError)
1044 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001045
Eli Friedman85f54972008-05-25 13:22:35 +00001046 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001047 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001048 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001049 if (SemaRef.getLangOpts().CPlusPlus ||
1050 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001051 IList->getType()->isVectorType())) {
1052 hadError = true;
1053 }
1054 return;
1055 }
1056
Eli Friedmanbd327452009-05-29 20:20:05 +00001057 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001058 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1059 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001060 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001061 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001062 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001063 hadError = true;
1064 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001065 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +00001066 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +00001067 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001068 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001069 // Don't complain for incomplete types, since we'll get an error
1070 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001071 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001072 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001073 CurrentObjectType->isArrayType()? 0 :
1074 CurrentObjectType->isVectorType()? 1 :
1075 CurrentObjectType->isScalarType()? 2 :
1076 CurrentObjectType->isUnionType()? 3 :
1077 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001078
Richard Smith1b98ccc2014-07-19 01:39:17 +00001079 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001080 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001081 DK = diag::err_excess_initializers;
1082 hadError = true;
1083 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001084 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001085 DK = diag::err_excess_initializers;
1086 hadError = true;
1087 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001088
Chris Lattnerb0912a52009-02-24 22:50:46 +00001089 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001090 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001091 }
1092 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001093
Richard Smith420fa122015-02-12 01:50:05 +00001094 if (!VerifyOnly && T->isScalarType() &&
1095 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1096 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +00001097}
1098
Anders Carlsson6cabf312010-01-23 23:23:01 +00001099void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001100 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001101 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001102 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001103 unsigned &Index,
1104 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001105 unsigned &StructuredIndex,
1106 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001107 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1108 // Explicitly braced initializer for complex type can be real+imaginary
1109 // parts.
1110 CheckComplexType(Entity, IList, DeclType, Index,
1111 StructuredList, StructuredIndex);
1112 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001113 CheckScalarType(Entity, IList, DeclType, Index,
1114 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001115 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001116 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001117 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001118 } else if (DeclType->isRecordType()) {
1119 assert(DeclType->isAggregateType() &&
1120 "non-aggregate records should be handed in CheckSubElementType");
1121 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001122 auto Bases =
1123 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1124 CXXRecordDecl::base_class_iterator());
1125 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1126 Bases = CXXRD->bases();
1127 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1128 SubobjectIsDesignatorContext, Index, StructuredList,
1129 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001130 } else if (DeclType->isArrayType()) {
1131 llvm::APSInt Zero(
1132 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1133 false);
1134 CheckArrayType(Entity, IList, DeclType, Zero,
1135 SubobjectIsDesignatorContext, Index,
1136 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001137 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1138 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001139 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001140 if (!VerifyOnly)
1141 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1142 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001143 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001144 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001145 CheckReferenceType(Entity, IList, DeclType, Index,
1146 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001147 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001148 if (!VerifyOnly)
1149 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1150 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001151 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001152 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001153 if (!VerifyOnly)
1154 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1155 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001156 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001157 }
1158}
1159
Anders Carlsson6cabf312010-01-23 23:23:01 +00001160void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001161 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001162 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001163 unsigned &Index,
1164 InitListExpr *StructuredList,
1165 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001166 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001167
1168 if (ElemType->isReferenceType())
1169 return CheckReferenceType(Entity, IList, ElemType, Index,
1170 StructuredList, StructuredIndex);
1171
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001172 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001173 if (SubInitList->getNumInits() == 1 &&
1174 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1175 SIF_None) {
1176 expr = SubInitList->getInit(0);
1177 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001178 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001179 = getStructuredSubobjectInit(IList, Index, ElemType,
1180 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001181 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001182 CheckExplicitInitList(Entity, SubInitList, ElemType,
1183 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001184
1185 if (!hadError && !VerifyOnly) {
1186 bool RequiresSecondPass = false;
1187 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001188 RequiresSecondPass, StructuredList,
1189 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001190 if (RequiresSecondPass && !hadError)
1191 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001192 RequiresSecondPass, StructuredList,
1193 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001194 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001195 ++StructuredIndex;
1196 ++Index;
1197 return;
1198 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001199 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001200 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001201 // This happens during template instantiation when we see an InitListExpr
1202 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001203 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001204 "found implicit initialization for the wrong type");
1205 if (!VerifyOnly)
1206 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1207 ++Index;
1208 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001209 }
1210
Richard Smith3c567fc2015-02-12 01:55:09 +00001211 if (SemaRef.getLangOpts().CPlusPlus) {
1212 // C++ [dcl.init.aggr]p2:
1213 // Each member is copy-initialized from the corresponding
1214 // initializer-clause.
1215
1216 // FIXME: Better EqualLoc?
1217 InitializationKind Kind =
1218 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1219 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1220 /*TopLevelOfInitList*/ true);
1221
1222 // C++14 [dcl.init.aggr]p13:
1223 // If the assignment-expression can initialize a member, the member is
1224 // initialized. Otherwise [...] brace elision is assumed
1225 //
1226 // Brace elision is never performed if the element is not an
1227 // assignment-expression.
1228 if (Seq || isa<InitListExpr>(expr)) {
1229 if (!VerifyOnly) {
1230 ExprResult Result =
1231 Seq.Perform(SemaRef, Entity, Kind, expr);
1232 if (Result.isInvalid())
1233 hadError = true;
1234
1235 UpdateStructuredListElement(StructuredList, StructuredIndex,
1236 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001237 } else if (!Seq)
1238 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001239 ++Index;
1240 return;
1241 }
1242
1243 // Fall through for subaggregate initialization
1244 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1245 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001246 return CheckScalarType(Entity, IList, ElemType, Index,
1247 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001248 } else if (const ArrayType *arrayType =
1249 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001250 // arrayType can be incomplete if we're initializing a flexible
1251 // array member. There's nothing we can do with the completed
1252 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001254 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001255 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001256 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1257 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001258 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001259 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001260 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001261 }
John McCall5decec92011-02-21 07:57:55 +00001262
1263 // Fall through for subaggregate initialization.
1264
John McCall5decec92011-02-21 07:57:55 +00001265 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001266 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001267 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001268
John McCall5decec92011-02-21 07:57:55 +00001269 // C99 6.7.8p13:
1270 //
1271 // The initializer for a structure or union object that has
1272 // automatic storage duration shall be either an initializer
1273 // list as described below, or a single expression that has
1274 // compatible structure or union type. In the latter case, the
1275 // initial value of the object, including unnamed members, is
1276 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001277 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001278 if (SemaRef.CheckSingleAssignmentConstraints(
1279 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001280 if (ExprRes.isInvalid())
1281 hadError = true;
1282 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001283 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001284 if (ExprRes.isInvalid())
1285 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001286 }
1287 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001288 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001289 ++Index;
1290 return;
1291 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001292 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001293 // Fall through for subaggregate initialization
1294 }
1295
1296 // C++ [dcl.init.aggr]p12:
1297 //
1298 // [...] Otherwise, if the member is itself a non-empty
1299 // subaggregate, brace elision is assumed and the initializer is
1300 // considered for the initialization of the first member of
1301 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001302 // OpenCL vector initializer is handled elsewhere.
1303 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1304 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001305 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1306 StructuredIndex);
1307 ++StructuredIndex;
1308 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001309 if (!VerifyOnly) {
1310 // We cannot initialize this element, so let
1311 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001312 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001313 /*TopLevelOfInitList=*/true);
1314 }
John McCall5decec92011-02-21 07:57:55 +00001315 hadError = true;
1316 ++Index;
1317 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001318 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001319}
1320
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001321void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1322 InitListExpr *IList, QualType DeclType,
1323 unsigned &Index,
1324 InitListExpr *StructuredList,
1325 unsigned &StructuredIndex) {
1326 assert(Index == 0 && "Index in explicit init list must be zero");
1327
1328 // As an extension, clang supports complex initializers, which initialize
1329 // a complex number component-wise. When an explicit initializer list for
1330 // a complex number contains two two initializers, this extension kicks in:
1331 // it exepcts the initializer list to contain two elements convertible to
1332 // the element type of the complex type. The first element initializes
1333 // the real part, and the second element intitializes the imaginary part.
1334
1335 if (IList->getNumInits() != 2)
1336 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1337 StructuredIndex);
1338
1339 // This is an extension in C. (The builtin _Complex type does not exist
1340 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001341 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001342 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1343 << IList->getSourceRange();
1344
1345 // Initialize the complex number.
1346 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1347 InitializedEntity ElementEntity =
1348 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1349
1350 for (unsigned i = 0; i < 2; ++i) {
1351 ElementEntity.setElementIndex(Index);
1352 CheckSubElementType(ElementEntity, IList, elementType, Index,
1353 StructuredList, StructuredIndex);
1354 }
1355}
1356
Anders Carlsson6cabf312010-01-23 23:23:01 +00001357void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001358 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001359 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001360 InitListExpr *StructuredList,
1361 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001362 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001363 if (!VerifyOnly)
1364 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001365 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001366 diag::warn_cxx98_compat_empty_scalar_initializer :
1367 diag::err_empty_scalar_initializer)
1368 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001369 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001370 ++Index;
1371 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001372 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001373 }
John McCall643169b2010-11-11 00:46:36 +00001374
1375 Expr *expr = IList->getInit(Index);
1376 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001377 // FIXME: This is invalid, and accepting it causes overload resolution
1378 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001379 if (!VerifyOnly)
1380 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001381 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001382 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001383
1384 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1385 StructuredIndex);
1386 return;
1387 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001388 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001389 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001390 diag::err_designator_for_scalar_init)
1391 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001392 hadError = true;
1393 ++Index;
1394 ++StructuredIndex;
1395 return;
1396 }
1397
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001398 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001399 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001400 hadError = true;
1401 ++Index;
1402 return;
1403 }
1404
John McCall643169b2010-11-11 00:46:36 +00001405 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001406 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001407 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001408
Craig Topperc3ec1492014-05-26 06:22:03 +00001409 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001410
1411 if (Result.isInvalid())
1412 hadError = true; // types weren't compatible.
1413 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001414 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001415
John McCall643169b2010-11-11 00:46:36 +00001416 if (ResultExpr != expr) {
1417 // The type was promoted, update initializer list.
1418 IList->setInit(Index, ResultExpr);
1419 }
1420 }
1421 if (hadError)
1422 ++StructuredIndex;
1423 else
1424 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1425 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001426}
1427
Anders Carlsson6cabf312010-01-23 23:23:01 +00001428void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1429 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001430 unsigned &Index,
1431 InitListExpr *StructuredList,
1432 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001433 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001434 // FIXME: It would be wonderful if we could point at the actual member. In
1435 // general, it would be useful to pass location information down the stack,
1436 // so that we know the location (or decl) of the "current object" being
1437 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001438 if (!VerifyOnly)
1439 SemaRef.Diag(IList->getLocStart(),
1440 diag::err_init_reference_member_uninitialized)
1441 << DeclType
1442 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001443 hadError = true;
1444 ++Index;
1445 ++StructuredIndex;
1446 return;
1447 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001448
1449 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001450 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001451 if (!VerifyOnly)
1452 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1453 << DeclType << IList->getSourceRange();
1454 hadError = true;
1455 ++Index;
1456 ++StructuredIndex;
1457 return;
1458 }
1459
1460 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001461 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001462 hadError = true;
1463 ++Index;
1464 return;
1465 }
1466
1467 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001468 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1469 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001470
1471 if (Result.isInvalid())
1472 hadError = true;
1473
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001474 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001475 IList->setInit(Index, expr);
1476
1477 if (hadError)
1478 ++StructuredIndex;
1479 else
1480 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1481 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001482}
1483
Anders Carlsson6cabf312010-01-23 23:23:01 +00001484void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001485 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001486 unsigned &Index,
1487 InitListExpr *StructuredList,
1488 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001489 const VectorType *VT = DeclType->getAs<VectorType>();
1490 unsigned maxElements = VT->getNumElements();
1491 unsigned numEltsInit = 0;
1492 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001493
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001494 if (Index >= IList->getNumInits()) {
1495 // Make sure the element type can be value-initialized.
1496 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001497 CheckEmptyInitializable(
1498 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1499 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001500 return;
1501 }
1502
David Blaikiebbafb8a2012-03-11 07:00:24 +00001503 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001504 // If the initializing element is a vector, try to copy-initialize
1505 // instead of breaking it apart (which is doomed to failure anyway).
1506 Expr *Init = IList->getInit(Index);
1507 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001508 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001509 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001510 hadError = true;
1511 ++Index;
1512 return;
1513 }
1514
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001515 ExprResult Result =
1516 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1517 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001518
Craig Topperc3ec1492014-05-26 06:22:03 +00001519 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001520 if (Result.isInvalid())
1521 hadError = true; // types weren't compatible.
1522 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001523 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524
John McCall6a16b2f2010-10-30 00:11:39 +00001525 if (ResultExpr != Init) {
1526 // The type was promoted, update initializer list.
1527 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001528 }
1529 }
John McCall6a16b2f2010-10-30 00:11:39 +00001530 if (hadError)
1531 ++StructuredIndex;
1532 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001533 UpdateStructuredListElement(StructuredList, StructuredIndex,
1534 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001535 ++Index;
1536 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
John McCall6a16b2f2010-10-30 00:11:39 +00001539 InitializedEntity ElementEntity =
1540 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
John McCall6a16b2f2010-10-30 00:11:39 +00001542 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1543 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001544 if (Index >= IList->getNumInits()) {
1545 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001546 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001547 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001549
John McCall6a16b2f2010-10-30 00:11:39 +00001550 ElementEntity.setElementIndex(Index);
1551 CheckSubElementType(ElementEntity, IList, elementType, Index,
1552 StructuredList, StructuredIndex);
1553 }
James Molloy9eef2652014-06-20 14:35:13 +00001554
1555 if (VerifyOnly)
1556 return;
1557
1558 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1559 const VectorType *T = Entity.getType()->getAs<VectorType>();
1560 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1561 T->getVectorKind() == VectorType::NeonPolyVector)) {
1562 // The ability to use vector initializer lists is a GNU vector extension
1563 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1564 // endian machines it works fine, however on big endian machines it
1565 // exhibits surprising behaviour:
1566 //
1567 // uint32x2_t x = {42, 64};
1568 // return vget_lane_u32(x, 0); // Will return 64.
1569 //
1570 // Because of this, explicitly call out that it is non-portable.
1571 //
1572 SemaRef.Diag(IList->getLocStart(),
1573 diag::warn_neon_vector_initializer_non_portable);
1574
1575 const char *typeCode;
1576 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1577
1578 if (elementType->isFloatingType())
1579 typeCode = "f";
1580 else if (elementType->isSignedIntegerType())
1581 typeCode = "s";
1582 else if (elementType->isUnsignedIntegerType())
1583 typeCode = "u";
1584 else
1585 llvm_unreachable("Invalid element type!");
1586
1587 SemaRef.Diag(IList->getLocStart(),
1588 SemaRef.Context.getTypeSize(VT) > 64 ?
1589 diag::note_neon_vector_initializer_non_portable_q :
1590 diag::note_neon_vector_initializer_non_portable)
1591 << typeCode << typeSize;
1592 }
1593
John McCall6a16b2f2010-10-30 00:11:39 +00001594 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001595 }
John McCall6a16b2f2010-10-30 00:11:39 +00001596
1597 InitializedEntity ElementEntity =
1598 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599
John McCall6a16b2f2010-10-30 00:11:39 +00001600 // OpenCL initializers allows vectors to be constructed from vectors.
1601 for (unsigned i = 0; i < maxElements; ++i) {
1602 // Don't attempt to go past the end of the init list
1603 if (Index >= IList->getNumInits())
1604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001605
John McCall6a16b2f2010-10-30 00:11:39 +00001606 ElementEntity.setElementIndex(Index);
1607
1608 QualType IType = IList->getInit(Index)->getType();
1609 if (!IType->isVectorType()) {
1610 CheckSubElementType(ElementEntity, IList, elementType, Index,
1611 StructuredList, StructuredIndex);
1612 ++numEltsInit;
1613 } else {
1614 QualType VecType;
1615 const VectorType *IVT = IType->getAs<VectorType>();
1616 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001617
John McCall6a16b2f2010-10-30 00:11:39 +00001618 if (IType->isExtVectorType())
1619 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1620 else
1621 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001622 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001623 CheckSubElementType(ElementEntity, IList, VecType, Index,
1624 StructuredList, StructuredIndex);
1625 numEltsInit += numIElts;
1626 }
1627 }
1628
1629 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001630 if (numEltsInit != maxElements) {
1631 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001632 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001633 diag::err_vector_incorrect_num_initializers)
1634 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1635 hadError = true;
1636 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001637}
1638
Anders Carlsson6cabf312010-01-23 23:23:01 +00001639void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001640 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001641 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001642 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001643 unsigned &Index,
1644 InitListExpr *StructuredList,
1645 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001646 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1647
Steve Narofff8ecff22008-05-01 22:18:59 +00001648 // Check for the special-case of initializing an array with a string.
1649 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001650 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1651 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001652 // We place the string literal directly into the resulting
1653 // initializer list. This is the only place where the structure
1654 // of the structured initializer list doesn't match exactly,
1655 // because doing so would involve allocating one character
1656 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001657 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001658 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1659 UpdateStructuredListElement(StructuredList, StructuredIndex,
1660 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001661 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1662 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001663 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001664 return;
1665 }
1666 }
John McCall66884dd2011-02-21 07:22:22 +00001667 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001668 // Check for VLAs; in standard C it would be possible to check this
1669 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1670 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001671 if (!VerifyOnly)
1672 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1673 diag::err_variable_object_no_init)
1674 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001675 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001676 ++Index;
1677 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001678 return;
1679 }
1680
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001681 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001682 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1683 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001684 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001685 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001686 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001687 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001688 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001689 maxElementsKnown = true;
1690 }
1691
John McCall66884dd2011-02-21 07:22:22 +00001692 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001693 while (Index < IList->getNumInits()) {
1694 Expr *Init = IList->getInit(Index);
1695 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001696 // If we're not the subobject that matches up with the '{' for
1697 // the designator, we shouldn't be handling the
1698 // designator. Return immediately.
1699 if (!SubobjectIsDesignatorContext)
1700 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001701
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001702 // Handle this designated initializer. elementIndex will be
1703 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001704 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001705 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001706 StructuredList, StructuredIndex, true,
1707 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001708 hadError = true;
1709 continue;
1710 }
1711
Douglas Gregor033d1252009-01-23 16:54:12 +00001712 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001713 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001714 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001715 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001716 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001717
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001718 // If the array is of incomplete type, keep track of the number of
1719 // elements in the initializer.
1720 if (!maxElementsKnown && elementIndex > maxElements)
1721 maxElements = elementIndex;
1722
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001723 continue;
1724 }
1725
1726 // If we know the maximum number of elements, and we've already
1727 // hit it, stop consuming elements in the initializer list.
1728 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001729 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001730
Anders Carlsson6cabf312010-01-23 23:23:01 +00001731 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001732 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001733 Entity);
1734 // Check this element.
1735 CheckSubElementType(ElementEntity, IList, elementType, Index,
1736 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001737 ++elementIndex;
1738
1739 // If the array is of incomplete type, keep track of the number of
1740 // elements in the initializer.
1741 if (!maxElementsKnown && elementIndex > maxElements)
1742 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001743 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001744 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001745 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001746 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001747 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001748 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001749 // Sizing an array implicitly to zero is not allowed by ISO C,
1750 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001751 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001752 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001753 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001754
Mike Stump11289f42009-09-09 15:08:12 +00001755 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001756 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001757 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001758 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001759 // If there are any members of the array that get value-initialized, check
1760 // that is possible. That happens if we know the bound and don't have
1761 // enough elements, or if we're performing an array new with an unknown
1762 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001763 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001764 if ((maxElementsKnown && elementIndex < maxElements) ||
1765 Entity.isVariableLengthArrayNew())
Richard Smith454a7cd2014-06-03 08:26:00 +00001766 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1767 SemaRef.Context, 0, Entity),
1768 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001769 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001770}
1771
Eli Friedman3fa64df2011-08-23 22:24:57 +00001772bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1773 Expr *InitExpr,
1774 FieldDecl *Field,
1775 bool TopLevelObject) {
1776 // Handle GNU flexible array initializers.
1777 unsigned FlexArrayDiag;
1778 if (isa<InitListExpr>(InitExpr) &&
1779 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1780 // Empty flexible array init always allowed as an extension
1781 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001782 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001783 // Disallow flexible array init in C++; it is not required for gcc
1784 // compatibility, and it needs work to IRGen correctly in general.
1785 FlexArrayDiag = diag::err_flexible_array_init;
1786 } else if (!TopLevelObject) {
1787 // Disallow flexible array init on non-top-level object
1788 FlexArrayDiag = diag::err_flexible_array_init;
1789 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1790 // Disallow flexible array init on anything which is not a variable.
1791 FlexArrayDiag = diag::err_flexible_array_init;
1792 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1793 // Disallow flexible array init on local variables.
1794 FlexArrayDiag = diag::err_flexible_array_init;
1795 } else {
1796 // Allow other cases.
1797 FlexArrayDiag = diag::ext_flexible_array_init;
1798 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001799
1800 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001801 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001802 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001803 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001804 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1805 << Field;
1806 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001807
1808 return FlexArrayDiag != diag::ext_flexible_array_init;
1809}
1810
Richard Smith872307e2016-03-08 22:17:41 +00001811void InitListChecker::CheckStructUnionTypes(
1812 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1813 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1814 bool SubobjectIsDesignatorContext, unsigned &Index,
1815 InitListExpr *StructuredList, unsigned &StructuredIndex,
1816 bool TopLevelObject) {
1817 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001818
Eli Friedman23a9e312008-05-19 19:16:24 +00001819 // If the record is invalid, some of it's members are invalid. To avoid
1820 // confusion, we forgo checking the intializer for the entire record.
1821 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001822 // Assume it was supposed to consume a single initializer.
1823 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001824 hadError = true;
1825 return;
Mike Stump11289f42009-09-09 15:08:12 +00001826 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001827
1828 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001829 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001830
1831 // If there's a default initializer, use it.
1832 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1833 if (VerifyOnly)
1834 return;
1835 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1836 Field != FieldEnd; ++Field) {
1837 if (Field->hasInClassInitializer()) {
1838 StructuredList->setInitializedFieldInUnion(*Field);
1839 // FIXME: Actually build a CXXDefaultInitExpr?
1840 return;
1841 }
1842 }
1843 }
1844
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001845 // Value-initialize the first member of the union that isn't an unnamed
1846 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001847 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1848 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001849 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001850 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001851 CheckEmptyInitializable(
1852 InitializedEntity::InitializeMember(*Field, &Entity),
1853 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001854 else
David Blaikie40ed2972012-06-06 20:45:41 +00001855 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001856 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001857 }
1858 }
1859 return;
1860 }
1861
Richard Smith872307e2016-03-08 22:17:41 +00001862 bool InitializedSomething = false;
1863
1864 // If we have any base classes, they are initialized prior to the fields.
1865 for (auto &Base : Bases) {
1866 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1867 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1868
1869 // Designated inits always initialize fields, so if we see one, all
1870 // remaining base classes have no explicit initializer.
1871 if (Init && isa<DesignatedInitExpr>(Init))
1872 Init = nullptr;
1873
1874 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1875 SemaRef.Context, &Base, false, &Entity);
1876 if (Init) {
1877 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1878 StructuredList, StructuredIndex);
1879 InitializedSomething = true;
1880 } else if (VerifyOnly) {
1881 CheckEmptyInitializable(BaseEntity, InitLoc);
1882 }
1883 }
1884
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001885 // If structDecl is a forward declaration, this loop won't do
1886 // anything except look at designated initializers; That's okay,
1887 // because an error should get printed out elsewhere. It might be
1888 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001889 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001890 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001891 bool CheckForMissingFields =
1892 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1893
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001894 while (Index < IList->getNumInits()) {
1895 Expr *Init = IList->getInit(Index);
1896
1897 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001898 // If we're not the subobject that matches up with the '{' for
1899 // the designator, we shouldn't be handling the
1900 // designator. Return immediately.
1901 if (!SubobjectIsDesignatorContext)
1902 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001903
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001904 // Handle this designated initializer. Field will be updated to
1905 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001906 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001907 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001908 StructuredList, StructuredIndex,
1909 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001910 hadError = true;
1911
Douglas Gregora9add4e2009-02-12 19:00:39 +00001912 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001913
1914 // Disable check for missing fields when designators are used.
1915 // This matches gcc behaviour.
1916 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001917 continue;
1918 }
1919
1920 if (Field == FieldEnd) {
1921 // We've run out of fields. We're done.
1922 break;
1923 }
1924
Douglas Gregora9add4e2009-02-12 19:00:39 +00001925 // We've already initialized a member of a union. We're done.
1926 if (InitializedSomething && DeclType->isUnionType())
1927 break;
1928
Douglas Gregor91f84212008-12-11 16:49:14 +00001929 // If we've hit the flexible array member at the end, we're done.
1930 if (Field->getType()->isIncompleteArrayType())
1931 break;
1932
Douglas Gregor51695702009-01-29 16:53:55 +00001933 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001934 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001935 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001936 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001937 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001938
Douglas Gregora82064c2011-06-29 21:51:31 +00001939 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001940 bool InvalidUse;
1941 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00001942 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001943 else
David Blaikie40ed2972012-06-06 20:45:41 +00001944 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001945 IList->getInit(Index)->getLocStart());
1946 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001947 ++Index;
1948 ++Field;
1949 hadError = true;
1950 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001951 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001952
Anders Carlsson6cabf312010-01-23 23:23:01 +00001953 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001954 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001955 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1956 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001957 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001958
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001959 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001960 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001961 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001962 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001963
1964 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001965 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001966
John McCalle40b58e2010-03-11 19:32:38 +00001967 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001968 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1969 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1970 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001971 // It is possible we have one or more unnamed bitfields remaining.
1972 // Find first (if any) named field and emit warning.
1973 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1974 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001975 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001976 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001977 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001978 break;
1979 }
1980 }
1981 }
1982
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001983 // Check that any remaining fields can be value-initialized.
1984 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1985 !Field->getType()->isIncompleteArrayType()) {
1986 // FIXME: Should check for holes left by designated initializers too.
1987 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001988 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001989 CheckEmptyInitializable(
1990 InitializedEntity::InitializeMember(*Field, &Entity),
1991 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001992 }
1993 }
1994
Mike Stump11289f42009-09-09 15:08:12 +00001995 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001996 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001997 return;
1998
David Blaikie40ed2972012-06-06 20:45:41 +00001999 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002000 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002001 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002002 ++Index;
2003 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002004 }
2005
Anders Carlsson6cabf312010-01-23 23:23:01 +00002006 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002007 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
Anders Carlsson6cabf312010-01-23 23:23:01 +00002009 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002010 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002011 StructuredList, StructuredIndex);
2012 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002013 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002014 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002015}
Steve Narofff8ecff22008-05-01 22:18:59 +00002016
Douglas Gregord5846a12009-04-15 06:41:24 +00002017/// \brief Expand a field designator that refers to a member of an
2018/// anonymous struct or union into a series of field designators that
2019/// refers to the field within the appropriate subobject.
2020///
Douglas Gregord5846a12009-04-15 06:41:24 +00002021static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002022 DesignatedInitExpr *DIE,
2023 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002024 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002025 typedef DesignatedInitExpr::Designator Designator;
2026
Douglas Gregord5846a12009-04-15 06:41:24 +00002027 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002028 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002029 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2030 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2031 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002032 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002033 DIE->getDesignator(DesigIdx)->getDotLoc(),
2034 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2035 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002036 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2037 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002038 assert(isa<FieldDecl>(*PI));
2039 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002040 }
2041
2042 // Expand the current designator into the set of replacement
2043 // designators, so we have a full subobject path down to where the
2044 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002045 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002046 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002047}
Mike Stump11289f42009-09-09 15:08:12 +00002048
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002049static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2050 DesignatedInitExpr *DIE) {
2051 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2052 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2053 for (unsigned I = 0; I < NumIndexExprs; ++I)
2054 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002055 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2056 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002057 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002058 DIE->usesGNUSyntax(), DIE->getInit());
2059}
2060
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002061namespace {
2062
2063// Callback to only accept typo corrections that are for field members of
2064// the given struct or union.
2065class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2066 public:
2067 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2068 : Record(RD) {}
2069
Craig Toppere14c0f82014-03-12 04:55:44 +00002070 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002071 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2072 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2073 }
2074
2075 private:
2076 RecordDecl *Record;
2077};
2078
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002079} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002080
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002081/// @brief Check the well-formedness of a C99 designated initializer.
2082///
2083/// Determines whether the designated initializer @p DIE, which
2084/// resides at the given @p Index within the initializer list @p
2085/// IList, is well-formed for a current object of type @p DeclType
2086/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002087/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002088/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002089///
2090/// @param IList The initializer list in which this designated
2091/// initializer occurs.
2092///
Douglas Gregora5324162009-04-15 04:56:10 +00002093/// @param DIE The designated initializer expression.
2094///
2095/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002096///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002097/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002098/// into which the designation in @p DIE should refer.
2099///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002100/// @param NextField If non-NULL and the first designator in @p DIE is
2101/// a field, this will be set to the field declaration corresponding
2102/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002103///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002104/// @param NextElementIndex If non-NULL and the first designator in @p
2105/// DIE is an array designator or GNU array-range designator, this
2106/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002107///
2108/// @param Index Index into @p IList where the designated initializer
2109/// @p DIE occurs.
2110///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002111/// @param StructuredList The initializer list expression that
2112/// describes all of the subobject initializers in the order they'll
2113/// actually be initialized.
2114///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002115/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002116bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002117InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002118 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002119 DesignatedInitExpr *DIE,
2120 unsigned DesigIdx,
2121 QualType &CurrentObjectType,
2122 RecordDecl::field_iterator *NextField,
2123 llvm::APSInt *NextElementIndex,
2124 unsigned &Index,
2125 InitListExpr *StructuredList,
2126 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002127 bool FinishSubobjectInit,
2128 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002129 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002130 // Check the actual initialization for the designated object type.
2131 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002132
2133 // Temporarily remove the designator expression from the
2134 // initializer list that the child calls see, so that we don't try
2135 // to re-process the designator.
2136 unsigned OldIndex = Index;
2137 IList->setInit(OldIndex, DIE->getInit());
2138
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002139 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002140 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002141
2142 // Restore the designated initializer expression in the syntactic
2143 // form of the initializer list.
2144 if (IList->getInit(OldIndex) != DIE->getInit())
2145 DIE->setInit(IList->getInit(OldIndex));
2146 IList->setInit(OldIndex, DIE);
2147
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002148 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002149 }
2150
Douglas Gregora5324162009-04-15 04:56:10 +00002151 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002152 bool IsFirstDesignator = (DesigIdx == 0);
2153 if (!VerifyOnly) {
2154 assert((IsFirstDesignator || StructuredList) &&
2155 "Need a non-designated initializer list to start from");
2156
2157 // Determine the structural initializer list that corresponds to the
2158 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002159 if (IsFirstDesignator)
2160 StructuredList = SyntacticToSemantic.lookup(IList);
2161 else {
2162 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2163 StructuredList->getInit(StructuredIndex) : nullptr;
2164 if (!ExistingInit && StructuredList->hasArrayFiller())
2165 ExistingInit = StructuredList->getArrayFiller();
2166
2167 if (!ExistingInit)
2168 StructuredList =
2169 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2170 StructuredList, StructuredIndex,
2171 SourceRange(D->getLocStart(),
2172 DIE->getLocEnd()));
2173 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2174 StructuredList = Result;
2175 else {
2176 if (DesignatedInitUpdateExpr *E =
2177 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2178 StructuredList = E->getUpdater();
2179 else {
2180 DesignatedInitUpdateExpr *DIUE =
2181 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2182 D->getLocStart(), ExistingInit,
2183 DIE->getLocEnd());
2184 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2185 StructuredList = DIUE->getUpdater();
2186 }
2187
2188 // We need to check on source range validity because the previous
2189 // initializer does not have to be an explicit initializer. e.g.,
2190 //
2191 // struct P { int a, b; };
2192 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2193 //
2194 // There is an overwrite taking place because the first braced initializer
2195 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2196 if (ExistingInit->getSourceRange().isValid()) {
2197 // We are creating an initializer list that initializes the
2198 // subobjects of the current object, but there was already an
2199 // initialization that completely initialized the current
2200 // subobject, e.g., by a compound literal:
2201 //
2202 // struct X { int a, b; };
2203 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2204 //
2205 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2206 // designated initializer re-initializes the whole
2207 // subobject [0], overwriting previous initializers.
2208 SemaRef.Diag(D->getLocStart(),
2209 diag::warn_subobject_initializer_overrides)
2210 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2211
2212 SemaRef.Diag(ExistingInit->getLocStart(),
2213 diag::note_previous_initializer)
2214 << /*FIXME:has side effects=*/0
2215 << ExistingInit->getSourceRange();
2216 }
2217 }
2218 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002219 assert(StructuredList && "Expected a structured initializer list");
2220 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002221
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002222 if (D->isFieldDesignator()) {
2223 // C99 6.7.8p7:
2224 //
2225 // If a designator has the form
2226 //
2227 // . identifier
2228 //
2229 // then the current object (defined below) shall have
2230 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002231 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002232 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002233 if (!RT) {
2234 SourceLocation Loc = D->getDotLoc();
2235 if (Loc.isInvalid())
2236 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002237 if (!VerifyOnly)
2238 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002239 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002240 ++Index;
2241 return true;
2242 }
2243
Douglas Gregord5846a12009-04-15 06:41:24 +00002244 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002245 if (!KnownField) {
2246 IdentifierInfo *FieldName = D->getFieldName();
2247 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2248 for (NamedDecl *ND : Lookup) {
2249 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2250 KnownField = FD;
2251 break;
2252 }
2253 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002254 // In verify mode, don't modify the original.
2255 if (VerifyOnly)
2256 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002257 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002258 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002259 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002260 break;
2261 }
2262 }
David Majnemer36ef8982014-08-11 18:33:59 +00002263 if (!KnownField) {
2264 if (VerifyOnly) {
2265 ++Index;
2266 return true; // No typo correction when just trying this out.
2267 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002268
David Majnemer36ef8982014-08-11 18:33:59 +00002269 // Name lookup found something, but it wasn't a field.
2270 if (!Lookup.empty()) {
2271 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2272 << FieldName;
2273 SemaRef.Diag(Lookup.front()->getLocation(),
2274 diag::note_field_designator_found);
2275 ++Index;
2276 return true;
2277 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002278
David Majnemer36ef8982014-08-11 18:33:59 +00002279 // Name lookup didn't find anything.
2280 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002281 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2282 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002283 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002284 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2285 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002286 SemaRef.diagnoseTypo(
2287 Corrected,
2288 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002289 << FieldName << CurrentObjectType);
2290 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002291 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002292 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002293 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002294 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2295 << FieldName << CurrentObjectType;
2296 ++Index;
2297 return true;
2298 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002299 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002300 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002301
David Majnemer58e4ea92014-08-23 01:48:50 +00002302 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002303
2304 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2305 FieldIndex = CXXRD->getNumBases();
2306
David Majnemer58e4ea92014-08-23 01:48:50 +00002307 for (auto *FI : RT->getDecl()->fields()) {
2308 if (FI->isUnnamedBitfield())
2309 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002310 if (declaresSameEntity(KnownField, FI)) {
2311 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002312 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002313 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002314 ++FieldIndex;
2315 }
2316
David Majnemer36ef8982014-08-11 18:33:59 +00002317 RecordDecl::field_iterator Field =
2318 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2319
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002320 // All of the fields of a union are located at the same place in
2321 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002322 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002323 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002324 if (!VerifyOnly) {
2325 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002326 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002327 assert(StructuredList->getNumInits() == 1
2328 && "A union should never have more than one initializer!");
2329
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002330 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002331 if (ExistingInit) {
2332 // We're about to throw away an initializer, emit warning.
2333 SemaRef.Diag(D->getFieldLoc(),
2334 diag::warn_initializer_overrides)
2335 << D->getSourceRange();
2336 SemaRef.Diag(ExistingInit->getLocStart(),
2337 diag::note_previous_initializer)
2338 << /*FIXME:has side effects=*/0
2339 << ExistingInit->getSourceRange();
2340 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002341
2342 // remove existing initializer
2343 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002344 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002345 }
2346
David Blaikie40ed2972012-06-06 20:45:41 +00002347 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002348 }
Douglas Gregor51695702009-01-29 16:53:55 +00002349 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002350
Douglas Gregora82064c2011-06-29 21:51:31 +00002351 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002352 bool InvalidUse;
2353 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002354 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002355 else
David Blaikie40ed2972012-06-06 20:45:41 +00002356 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002357 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002358 ++Index;
2359 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002360 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002361
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002362 if (!VerifyOnly) {
2363 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002364 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002365
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002366 // Make sure that our non-designated initializer list has space
2367 // for a subobject corresponding to this field.
2368 if (FieldIndex >= StructuredList->getNumInits())
2369 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2370 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002371
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002372 // This designator names a flexible array member.
2373 if (Field->getType()->isIncompleteArrayType()) {
2374 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002375 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002376 // We can't designate an object within the flexible array
2377 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002378 if (!VerifyOnly) {
2379 DesignatedInitExpr::Designator *NextD
2380 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002381 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002382 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002383 << SourceRange(NextD->getLocStart(),
2384 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002385 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002386 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002387 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002388 Invalid = true;
2389 }
2390
Chris Lattner001b29c2010-10-10 17:49:49 +00002391 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2392 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002393 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002394 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002395 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002396 diag::err_flexible_array_init_needs_braces)
2397 << DIE->getInit()->getSourceRange();
2398 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002399 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002400 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002401 Invalid = true;
2402 }
2403
Eli Friedman3fa64df2011-08-23 22:24:57 +00002404 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002405 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002406 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002407 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002408
2409 if (Invalid) {
2410 ++Index;
2411 return true;
2412 }
2413
2414 // Initialize the array.
2415 bool prevHadError = hadError;
2416 unsigned newStructuredIndex = FieldIndex;
2417 unsigned OldIndex = Index;
2418 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002419
2420 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002421 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002422 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002423 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002424
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002425 IList->setInit(OldIndex, DIE);
2426 if (hadError && !prevHadError) {
2427 ++Field;
2428 ++FieldIndex;
2429 if (NextField)
2430 *NextField = Field;
2431 StructuredIndex = FieldIndex;
2432 return true;
2433 }
2434 } else {
2435 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002436 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002437 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002438
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002439 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002440 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002441 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002442 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002443 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002444 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002445 return true;
2446 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002447
2448 // Find the position of the next field to be initialized in this
2449 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002450 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002451 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002452
2453 // If this the first designator, our caller will continue checking
2454 // the rest of this struct/class/union subobject.
2455 if (IsFirstDesignator) {
2456 if (NextField)
2457 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002458 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002459 return false;
2460 }
2461
Douglas Gregor17bd0942009-01-28 23:36:17 +00002462 if (!FinishSubobjectInit)
2463 return false;
2464
Douglas Gregord5846a12009-04-15 06:41:24 +00002465 // We've already initialized something in the union; we're done.
2466 if (RT->getDecl()->isUnion())
2467 return hadError;
2468
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002469 // Check the remaining fields within this class/struct/union subobject.
2470 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002471
Richard Smith872307e2016-03-08 22:17:41 +00002472 auto NoBases =
2473 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2474 CXXRecordDecl::base_class_iterator());
2475 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2476 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002477 return hadError && !prevHadError;
2478 }
2479
2480 // C99 6.7.8p6:
2481 //
2482 // If a designator has the form
2483 //
2484 // [ constant-expression ]
2485 //
2486 // then the current object (defined below) shall have array
2487 // type and the expression shall be an integer constant
2488 // expression. If the array is of unknown size, any
2489 // nonnegative value is valid.
2490 //
2491 // Additionally, cope with the GNU extension that permits
2492 // designators of the form
2493 //
2494 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002495 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002496 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002497 if (!VerifyOnly)
2498 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2499 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002500 ++Index;
2501 return true;
2502 }
2503
Craig Topperc3ec1492014-05-26 06:22:03 +00002504 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002505 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2506 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002507 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002508 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002509 DesignatedEndIndex = DesignatedStartIndex;
2510 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002511 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002512
Mike Stump11289f42009-09-09 15:08:12 +00002513 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002514 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002515 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002516 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002517 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002518
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002519 // Codegen can't handle evaluating array range designators that have side
2520 // effects, because we replicate the AST value for each initialized element.
2521 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2522 // elements with something that has a side effect, so codegen can emit an
2523 // "error unsupported" error instead of miscompiling the app.
2524 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002525 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002526 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002527 }
2528
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002529 if (isa<ConstantArrayType>(AT)) {
2530 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002531 DesignatedStartIndex
2532 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002533 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002534 DesignatedEndIndex
2535 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002536 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2537 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002538 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002539 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002540 diag::err_array_designator_too_large)
2541 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2542 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002543 ++Index;
2544 return true;
2545 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002546 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002547 unsigned DesignatedIndexBitWidth =
2548 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2549 DesignatedStartIndex =
2550 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2551 DesignatedEndIndex =
2552 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002553 DesignatedStartIndex.setIsUnsigned(true);
2554 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002555 }
Mike Stump11289f42009-09-09 15:08:12 +00002556
Eli Friedman1f16b742013-06-11 21:48:11 +00002557 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2558 // We're modifying a string literal init; we have to decompose the string
2559 // so we can modify the individual characters.
2560 ASTContext &Context = SemaRef.Context;
2561 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2562
2563 // Compute the character type
2564 QualType CharTy = AT->getElementType();
2565
2566 // Compute the type of the integer literals.
2567 QualType PromotedCharTy = CharTy;
2568 if (CharTy->isPromotableIntegerType())
2569 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2570 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2571
2572 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2573 // Get the length of the string.
2574 uint64_t StrLen = SL->getLength();
2575 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2576 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2577 StructuredList->resizeInits(Context, StrLen);
2578
2579 // Build a literal for each character in the string, and put them into
2580 // the init list.
2581 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2582 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2583 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002584 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002585 if (CharTy != PromotedCharTy)
2586 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002587 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002588 StructuredList->updateInit(Context, i, Init);
2589 }
2590 } else {
2591 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2592 std::string Str;
2593 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2594
2595 // Get the length of the string.
2596 uint64_t StrLen = Str.size();
2597 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2598 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2599 StructuredList->resizeInits(Context, StrLen);
2600
2601 // Build a literal for each character in the string, and put them into
2602 // the init list.
2603 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2604 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2605 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002606 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002607 if (CharTy != PromotedCharTy)
2608 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002609 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002610 StructuredList->updateInit(Context, i, Init);
2611 }
2612 }
2613 }
2614
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002615 // Make sure that our non-designated initializer list has space
2616 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002617 if (!VerifyOnly &&
2618 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002619 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002620 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002621
Douglas Gregor17bd0942009-01-28 23:36:17 +00002622 // Repeatedly perform subobject initializations in the range
2623 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002624
Douglas Gregor17bd0942009-01-28 23:36:17 +00002625 // Move to the next designator
2626 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2627 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002628
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002629 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002630 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002631
Douglas Gregor17bd0942009-01-28 23:36:17 +00002632 while (DesignatedStartIndex <= DesignatedEndIndex) {
2633 // Recurse to check later designated subobjects.
2634 QualType ElementType = AT->getElementType();
2635 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002636
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002637 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002638 if (CheckDesignatedInitializer(
2639 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2640 nullptr, Index, StructuredList, ElementIndex,
2641 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2642 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002643 return true;
2644
2645 // Move to the next index in the array that we'll be initializing.
2646 ++DesignatedStartIndex;
2647 ElementIndex = DesignatedStartIndex.getZExtValue();
2648 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002649
2650 // If this the first designator, our caller will continue checking
2651 // the rest of this array subobject.
2652 if (IsFirstDesignator) {
2653 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002654 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002655 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002656 return false;
2657 }
Mike Stump11289f42009-09-09 15:08:12 +00002658
Douglas Gregor17bd0942009-01-28 23:36:17 +00002659 if (!FinishSubobjectInit)
2660 return false;
2661
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002662 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002663 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002665 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002666 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002667 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002668}
2669
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002670// Get the structured initializer list for a subobject of type
2671// @p CurrentObjectType.
2672InitListExpr *
2673InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2674 QualType CurrentObjectType,
2675 InitListExpr *StructuredList,
2676 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002677 SourceRange InitRange,
2678 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002679 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002680 return nullptr; // No structured list in verification-only mode.
2681 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002682 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002683 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002684 else if (StructuredIndex < StructuredList->getNumInits())
2685 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002686
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002687 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002688 // There might have already been initializers for subobjects of the current
2689 // object, but a subsequent initializer list will overwrite the entirety
2690 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2691 //
2692 // struct P { char x[6]; };
2693 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2694 //
2695 // The first designated initializer is ignored, and l.x is just "f".
2696 if (!IsFullyOverwritten)
2697 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002698
2699 if (ExistingInit) {
2700 // We are creating an initializer list that initializes the
2701 // subobjects of the current object, but there was already an
2702 // initialization that completely initialized the current
2703 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002704 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002705 // struct X { int a, b; };
2706 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002707 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002708 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2709 // designated initializer re-initializes the whole
2710 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002711 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002712 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002713 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002714 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002715 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002716 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002717 << ExistingInit->getSourceRange();
2718 }
2719
Mike Stump11289f42009-09-09 15:08:12 +00002720 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002721 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002722 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002723 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002724
Eli Friedman91f5ae52012-02-23 02:25:10 +00002725 QualType ResultType = CurrentObjectType;
2726 if (!ResultType->isArrayType())
2727 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2728 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002729
Douglas Gregor6d00c992009-03-20 23:58:33 +00002730 // Pre-allocate storage for the structured initializer list.
2731 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002732 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002733 bool GotNumInits = false;
2734 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002735 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002736 GotNumInits = true;
2737 } else if (Index < IList->getNumInits()) {
2738 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002739 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002740 GotNumInits = true;
2741 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002742 }
2743
Mike Stump11289f42009-09-09 15:08:12 +00002744 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002745 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2746 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2747 NumElements = CAType->getSize().getZExtValue();
2748 // Simple heuristic so that we don't allocate a very large
2749 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002750 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002751 NumElements = 0;
2752 }
John McCall9dd450b2009-09-21 23:43:11 +00002753 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002754 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002755 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002756 RecordDecl *RDecl = RType->getDecl();
2757 if (RDecl->isUnion())
2758 NumElements = 1;
2759 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002760 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002761 }
2762
Ted Kremenekac034612010-04-13 23:39:13 +00002763 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002764
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002765 // Link this new initializer list into the structured initializer
2766 // lists.
2767 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002768 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002769 else {
2770 Result->setSyntacticForm(IList);
2771 SyntacticToSemantic[IList] = Result;
2772 }
2773
2774 return Result;
2775}
2776
2777/// Update the initializer at index @p StructuredIndex within the
2778/// structured initializer list to the value @p expr.
2779void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2780 unsigned &StructuredIndex,
2781 Expr *expr) {
2782 // No structured initializer list to update
2783 if (!StructuredList)
2784 return;
2785
Ted Kremenekac034612010-04-13 23:39:13 +00002786 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2787 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002788 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002789 // We need to check on source range validity because the previous
2790 // initializer does not have to be an explicit initializer.
2791 // struct P { int a, b; };
2792 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2793 // There is an overwrite taking place because the first braced initializer
2794 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2795 if (PrevInit->getSourceRange().isValid()) {
2796 SemaRef.Diag(expr->getLocStart(),
2797 diag::warn_initializer_overrides)
2798 << expr->getSourceRange();
2799
2800 SemaRef.Diag(PrevInit->getLocStart(),
2801 diag::note_previous_initializer)
2802 << /*FIXME:has side effects=*/0
2803 << PrevInit->getSourceRange();
2804 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002805 }
Mike Stump11289f42009-09-09 15:08:12 +00002806
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002807 ++StructuredIndex;
2808}
2809
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002810/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002811/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002812/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002813/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002814/// failure. Returns the index expression, possibly with an implicit cast
2815/// added, on success. If everything went okay, Value will receive the
2816/// value of the constant expression.
2817static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002818CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002819 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002820
2821 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002822 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2823 if (Result.isInvalid())
2824 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002825
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002826 if (Value.isSigned() && Value.isNegative())
2827 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002828 << Value.toString(10) << Index->getSourceRange();
2829
Douglas Gregor51650d32009-01-23 21:04:18 +00002830 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002831 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002832}
2833
John McCalldadc5752010-08-24 06:29:42 +00002834ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002835 SourceLocation Loc,
2836 bool GNUSyntax,
2837 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002838 typedef DesignatedInitExpr::Designator ASTDesignator;
2839
2840 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002841 SmallVector<ASTDesignator, 32> Designators;
2842 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002843
2844 // Build designators and check array designator expressions.
2845 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2846 const Designator &D = Desig.getDesignator(Idx);
2847 switch (D.getKind()) {
2848 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002849 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002850 D.getFieldLoc()));
2851 break;
2852
2853 case Designator::ArrayDesignator: {
2854 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2855 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002856 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002857 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002858 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002859 Invalid = true;
2860 else {
2861 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002862 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002863 D.getRBracketLoc()));
2864 InitExpressions.push_back(Index);
2865 }
2866 break;
2867 }
2868
2869 case Designator::ArrayRangeDesignator: {
2870 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2871 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2872 llvm::APSInt StartValue;
2873 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002874 bool StartDependent = StartIndex->isTypeDependent() ||
2875 StartIndex->isValueDependent();
2876 bool EndDependent = EndIndex->isTypeDependent() ||
2877 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002878 if (!StartDependent)
2879 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002880 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002881 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002882 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002883
2884 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002885 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002886 else {
2887 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002888 if (StartDependent || EndDependent) {
2889 // Nothing to compute.
2890 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002891 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002892 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002893 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002894
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002895 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002896 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002897 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002898 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2899 Invalid = true;
2900 } else {
2901 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002902 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002903 D.getEllipsisLoc(),
2904 D.getRBracketLoc()));
2905 InitExpressions.push_back(StartIndex);
2906 InitExpressions.push_back(EndIndex);
2907 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002908 }
2909 break;
2910 }
2911 }
2912 }
2913
2914 if (Invalid || Init.isInvalid())
2915 return ExprError();
2916
2917 // Clear out the expressions within the designation.
2918 Desig.ClearExprs(*this);
2919
2920 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002921 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00002922 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002923 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002924 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002925
David Blaikiebbafb8a2012-03-11 07:00:24 +00002926 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002927 Diag(DIE->getLocStart(), diag::ext_designated_init)
2928 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002930 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002931}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002932
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002933//===----------------------------------------------------------------------===//
2934// Initialization entity
2935//===----------------------------------------------------------------------===//
2936
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002937InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002938 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002940{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002941 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2942 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002943 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002944 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002945 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002946 Type = VT->getElementType();
2947 } else {
2948 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2949 assert(CT && "Unexpected type");
2950 Kind = EK_ComplexElement;
2951 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002952 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002953}
2954
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002955InitializedEntity
2956InitializedEntity::InitializeBase(ASTContext &Context,
2957 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00002958 bool IsInheritedVirtualBase,
2959 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002960 InitializedEntity Result;
2961 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00002962 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002963 Result.Base = reinterpret_cast<uintptr_t>(Base);
2964 if (IsInheritedVirtualBase)
2965 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002966
Douglas Gregor1b303932009-12-22 15:35:07 +00002967 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002968 return Result;
2969}
2970
Douglas Gregor85dabae2009-12-16 01:38:02 +00002971DeclarationName InitializedEntity::getName() const {
2972 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002973 case EK_Parameter:
2974 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002975 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2976 return (D ? D->getDeclName() : DeclarationName());
2977 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002978
2979 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002980 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002981 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002982 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002983
Douglas Gregor19666fb2012-02-15 16:57:26 +00002984 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002985 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002986
Douglas Gregor85dabae2009-12-16 01:38:02 +00002987 case EK_Result:
2988 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002989 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002990 case EK_Temporary:
2991 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002992 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002993 case EK_ArrayElement:
2994 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002995 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002996 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00002997 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002998 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002999 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003000 return DeclarationName();
3001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002
David Blaikie8a40f702012-01-17 06:56:22 +00003003 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003004}
3005
Richard Smith7873de02016-08-11 22:25:46 +00003006ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003007 switch (getKind()) {
3008 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003009 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003010 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003011 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003012
John McCall31168b02011-06-15 23:02:42 +00003013 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003014 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003015 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3016
Douglas Gregora4b592a2009-12-19 03:01:41 +00003017 case EK_Result:
3018 case EK_Exception:
3019 case EK_New:
3020 case EK_Temporary:
3021 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003022 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003023 case EK_ArrayElement:
3024 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003025 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003026 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003027 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003028 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003029 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003030 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003031 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003033
David Blaikie8a40f702012-01-17 06:56:22 +00003034 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003035}
3036
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003037bool InitializedEntity::allowsNRVO() const {
3038 switch (getKind()) {
3039 case EK_Result:
3040 case EK_Exception:
3041 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003042
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003043 case EK_Variable:
3044 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003045 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003046 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003047 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003048 case EK_New:
3049 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003050 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003051 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003052 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003053 case EK_ArrayElement:
3054 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003055 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003056 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003057 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003058 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003059 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003060 break;
3061 }
3062
3063 return false;
3064}
3065
Richard Smithe6c01442013-06-05 00:46:14 +00003066unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003067 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003068 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3069 for (unsigned I = 0; I != Depth; ++I)
3070 OS << "`-";
3071
3072 switch (getKind()) {
3073 case EK_Variable: OS << "Variable"; break;
3074 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003075 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3076 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003077 case EK_Result: OS << "Result"; break;
3078 case EK_Exception: OS << "Exception"; break;
3079 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003080 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003081 case EK_New: OS << "New"; break;
3082 case EK_Temporary: OS << "Temporary"; break;
3083 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003084 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003085 case EK_Base: OS << "Base"; break;
3086 case EK_Delegating: OS << "Delegating"; break;
3087 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3088 case EK_VectorElement: OS << "VectorElement " << Index; break;
3089 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3090 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003091 case EK_LambdaToBlockConversionBlockElement:
3092 OS << "Block (lambda)";
3093 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003094 case EK_LambdaCapture:
3095 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003096 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003097 break;
3098 }
3099
Richard Smith7873de02016-08-11 22:25:46 +00003100 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003101 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003102 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003103 }
3104
3105 OS << " '" << getType().getAsString() << "'\n";
3106
3107 return Depth + 1;
3108}
3109
Yaron Kerencdae9412016-01-29 19:38:18 +00003110LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003111 dumpImpl(llvm::errs());
3112}
3113
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003114//===----------------------------------------------------------------------===//
3115// Initialization sequence
3116//===----------------------------------------------------------------------===//
3117
3118void InitializationSequence::Step::Destroy() {
3119 switch (Kind) {
3120 case SK_ResolveAddressOfOverloadedFunction:
3121 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003122 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003123 case SK_CastDerivedToBaseLValue:
3124 case SK_BindReference:
3125 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003126 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003127 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003128 case SK_UserConversion:
3129 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003130 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003131 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003132 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003133 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003134 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003135 case SK_UnwrapInitList:
3136 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003137 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003138 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003139 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003140 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003141 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003142 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003143 case SK_ArrayLoopIndex:
3144 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003145 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003146 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003147 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003148 case SK_PassByIndirectCopyRestore:
3149 case SK_PassByIndirectRestore:
3150 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003151 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003152 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003153 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003154 case SK_OCLZeroEvent:
Egor Churaev89831422016-12-23 14:55:49 +00003155 case SK_OCLZeroQueue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003156 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003158 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003159 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003160 delete ICS;
3161 }
3162}
3163
Douglas Gregor838fcc32010-03-26 20:14:36 +00003164bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003165 // There can be some lvalue adjustments after the SK_BindReference step.
3166 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3167 if (I->Kind == SK_BindReference)
3168 return true;
3169 if (I->Kind == SK_BindReferenceToTemporary)
3170 return false;
3171 }
3172 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003173}
3174
3175bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003176 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003177 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178
Douglas Gregor838fcc32010-03-26 20:14:36 +00003179 switch (getFailureKind()) {
3180 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003181 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003182 case FK_ArrayNeedsInitList:
3183 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003184 case FK_ArrayNeedsInitListOrWideStringLiteral:
3185 case FK_NarrowStringIntoWideCharArray:
3186 case FK_WideStringIntoCharArray:
3187 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003188 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3189 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003190 case FK_NonConstLValueReferenceBindingToBitfield:
3191 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003192 case FK_NonConstLValueReferenceBindingToUnrelated:
3193 case FK_RValueReferenceBindingToLValue:
3194 case FK_ReferenceInitDropsQualifiers:
3195 case FK_ReferenceInitFailed:
3196 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003197 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003198 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003199 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003200 case FK_ReferenceBindingToInitList:
3201 case FK_InitListBadDestinationType:
3202 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003203 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003204 case FK_ArrayTypeMismatch:
3205 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003206 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003207 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003208 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003209 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003210 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003211 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003212
Douglas Gregor838fcc32010-03-26 20:14:36 +00003213 case FK_ReferenceInitOverloadFailed:
3214 case FK_UserConversionOverloadFailed:
3215 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003216 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003217 return FailedOverloadResult == OR_Ambiguous;
3218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219
David Blaikie8a40f702012-01-17 06:56:22 +00003220 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003221}
3222
Douglas Gregorb33eed02010-04-16 22:09:46 +00003223bool InitializationSequence::isConstructorInitialization() const {
3224 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3225}
3226
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003227void
3228InitializationSequence
3229::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3230 DeclAccessPair Found,
3231 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003232 Step S;
3233 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3234 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003235 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003236 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003237 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 Steps.push_back(S);
3239}
3240
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003242 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003244 switch (VK) {
3245 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3246 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3247 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003248 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003249 S.Type = BaseType;
3250 Steps.push_back(S);
3251}
3252
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003254 bool BindingTemporary) {
3255 Step S;
3256 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3257 S.Type = T;
3258 Steps.push_back(S);
3259}
3260
Richard Smithb8c0f552016-12-09 18:49:13 +00003261void InitializationSequence::AddFinalCopy(QualType T) {
3262 Step S;
3263 S.Kind = SK_FinalCopy;
3264 S.Type = T;
3265 Steps.push_back(S);
3266}
3267
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003268void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3269 Step S;
3270 S.Kind = SK_ExtraneousCopyToTemporary;
3271 S.Type = T;
3272 Steps.push_back(S);
3273}
3274
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003275void
3276InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3277 DeclAccessPair FoundDecl,
3278 QualType T,
3279 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003280 Step S;
3281 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003282 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003283 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003284 S.Function.Function = Function;
3285 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003286 Steps.push_back(S);
3287}
3288
3289void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003290 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003291 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003292 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003293 switch (VK) {
3294 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003295 S.Kind = SK_QualificationConversionRValue;
3296 break;
John McCall2536c6d2010-08-25 10:28:54 +00003297 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003298 S.Kind = SK_QualificationConversionXValue;
3299 break;
John McCall2536c6d2010-08-25 10:28:54 +00003300 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003301 S.Kind = SK_QualificationConversionLValue;
3302 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003303 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003304 S.Type = Ty;
3305 Steps.push_back(S);
3306}
3307
Richard Smith77be48a2014-07-31 06:31:19 +00003308void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3309 Step S;
3310 S.Kind = SK_AtomicConversion;
3311 S.Type = Ty;
3312 Steps.push_back(S);
3313}
3314
Jordan Roseb1312a52013-04-11 00:58:58 +00003315void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3316 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3317
3318 Step S;
3319 S.Kind = SK_LValueToRValue;
3320 S.Type = Ty;
3321 Steps.push_back(S);
3322}
3323
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003324void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003325 const ImplicitConversionSequence &ICS, QualType T,
3326 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003327 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003328 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3329 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003330 S.Type = T;
3331 S.ICS = new ImplicitConversionSequence(ICS);
3332 Steps.push_back(S);
3333}
3334
Douglas Gregor51e77d52009-12-10 17:56:55 +00003335void InitializationSequence::AddListInitializationStep(QualType T) {
3336 Step S;
3337 S.Kind = SK_ListInitialization;
3338 S.Type = T;
3339 Steps.push_back(S);
3340}
3341
Richard Smith55c28882016-05-12 23:45:49 +00003342void InitializationSequence::AddConstructorInitializationStep(
3343 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3344 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003345 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003346 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003347 : SK_ConstructorInitializationFromList
3348 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003349 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003350 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003351 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003352 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003353 Steps.push_back(S);
3354}
3355
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003356void InitializationSequence::AddZeroInitializationStep(QualType T) {
3357 Step S;
3358 S.Kind = SK_ZeroInitialization;
3359 S.Type = T;
3360 Steps.push_back(S);
3361}
3362
Douglas Gregore1314a62009-12-18 05:02:21 +00003363void InitializationSequence::AddCAssignmentStep(QualType T) {
3364 Step S;
3365 S.Kind = SK_CAssignment;
3366 S.Type = T;
3367 Steps.push_back(S);
3368}
3369
Eli Friedman78275202009-12-19 08:11:05 +00003370void InitializationSequence::AddStringInitStep(QualType T) {
3371 Step S;
3372 S.Kind = SK_StringInit;
3373 S.Type = T;
3374 Steps.push_back(S);
3375}
3376
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003377void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3378 Step S;
3379 S.Kind = SK_ObjCObjectConversion;
3380 S.Type = T;
3381 Steps.push_back(S);
3382}
3383
Richard Smith378b8c82016-12-14 03:22:16 +00003384void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003385 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003386 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003387 S.Type = T;
3388 Steps.push_back(S);
3389}
3390
Richard Smith410306b2016-12-12 02:53:20 +00003391void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3392 Step S;
3393 S.Kind = SK_ArrayLoopIndex;
3394 S.Type = EltT;
3395 Steps.insert(Steps.begin(), S);
3396
3397 S.Kind = SK_ArrayLoopInit;
3398 S.Type = T;
3399 Steps.push_back(S);
3400}
3401
Richard Smithebeed412012-02-15 22:38:09 +00003402void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3403 Step S;
3404 S.Kind = SK_ParenthesizedArrayInit;
3405 S.Type = T;
3406 Steps.push_back(S);
3407}
3408
John McCall31168b02011-06-15 23:02:42 +00003409void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3410 bool shouldCopy) {
3411 Step s;
3412 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3413 : SK_PassByIndirectRestore);
3414 s.Type = type;
3415 Steps.push_back(s);
3416}
3417
3418void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3419 Step S;
3420 S.Kind = SK_ProduceObjCObject;
3421 S.Type = T;
3422 Steps.push_back(S);
3423}
3424
Sebastian Redlc1839b12012-01-17 22:49:42 +00003425void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3426 Step S;
3427 S.Kind = SK_StdInitializerList;
3428 S.Type = T;
3429 Steps.push_back(S);
3430}
3431
Guy Benyei61054192013-02-07 10:55:47 +00003432void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3433 Step S;
3434 S.Kind = SK_OCLSamplerInit;
3435 S.Type = T;
3436 Steps.push_back(S);
3437}
3438
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003439void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3440 Step S;
3441 S.Kind = SK_OCLZeroEvent;
3442 S.Type = T;
3443 Steps.push_back(S);
3444}
3445
Egor Churaev89831422016-12-23 14:55:49 +00003446void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3447 Step S;
3448 S.Kind = SK_OCLZeroQueue;
3449 S.Type = T;
3450 Steps.push_back(S);
3451}
3452
Sebastian Redl29526f02011-11-27 16:50:07 +00003453void InitializationSequence::RewrapReferenceInitList(QualType T,
3454 InitListExpr *Syntactic) {
3455 assert(Syntactic->getNumInits() == 1 &&
3456 "Can only rewrap trivial init lists.");
3457 Step S;
3458 S.Kind = SK_UnwrapInitList;
3459 S.Type = Syntactic->getInit(0)->getType();
3460 Steps.insert(Steps.begin(), S);
3461
3462 S.Kind = SK_RewrapInitList;
3463 S.Type = T;
3464 S.WrappingSyntacticList = Syntactic;
3465 Steps.push_back(S);
3466}
3467
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003469 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003470 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003471 this->Failure = Failure;
3472 this->FailedOverloadResult = Result;
3473}
3474
3475//===----------------------------------------------------------------------===//
3476// Attempt initialization
3477//===----------------------------------------------------------------------===//
3478
Nico Weber337d5aa2015-04-17 08:32:38 +00003479/// Tries to add a zero initializer. Returns true if that worked.
3480static bool
3481maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3482 const InitializedEntity &Entity) {
3483 if (Entity.getKind() != InitializedEntity::EK_Variable)
3484 return false;
3485
3486 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3487 if (VD->getInit() || VD->getLocEnd().isMacroID())
3488 return false;
3489
3490 QualType VariableTy = VD->getType().getCanonicalType();
3491 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3492 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3493 if (!Init.empty()) {
3494 Sequence.AddZeroInitializationStep(Entity.getType());
3495 Sequence.SetZeroInitializationFixit(Init, Loc);
3496 return true;
3497 }
3498 return false;
3499}
3500
John McCall31168b02011-06-15 23:02:42 +00003501static void MaybeProduceObjCObject(Sema &S,
3502 InitializationSequence &Sequence,
3503 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003504 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003505
3506 /// When initializing a parameter, produce the value if it's marked
3507 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003508 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003509 if (!Entity.isParameterConsumed())
3510 return;
3511
3512 assert(Entity.getType()->isObjCRetainableType() &&
3513 "consuming an object of unretainable type?");
3514 Sequence.AddProduceObjCObjectStep(Entity.getType());
3515
3516 /// When initializing a return value, if the return type is a
3517 /// retainable type, then returns need to immediately retain the
3518 /// object. If an autorelease is required, it will be done at the
3519 /// last instant.
3520 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3521 if (!Entity.getType()->isObjCRetainableType())
3522 return;
3523
3524 Sequence.AddProduceObjCObjectStep(Entity.getType());
3525 }
3526}
3527
Richard Smithcc1b96d2013-06-12 22:31:48 +00003528static void TryListInitialization(Sema &S,
3529 const InitializedEntity &Entity,
3530 const InitializationKind &Kind,
3531 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003532 InitializationSequence &Sequence,
3533 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003534
Richard Smithd86812d2012-07-05 08:39:21 +00003535/// \brief When initializing from init list via constructor, handle
3536/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003537///
Richard Smithd86812d2012-07-05 08:39:21 +00003538/// \return true if we have handled initialization of an object of type
3539/// std::initializer_list<T>, false otherwise.
3540static bool TryInitializerListConstruction(Sema &S,
3541 InitListExpr *List,
3542 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003543 InitializationSequence &Sequence,
3544 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003545 QualType E;
3546 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003547 return false;
3548
Richard Smithdb0ac552015-12-18 22:40:25 +00003549 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003550 Sequence.setIncompleteTypeFailure(E);
3551 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003552 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003553
3554 // Try initializing a temporary array from the init list.
3555 QualType ArrayType = S.Context.getConstantArrayType(
3556 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3557 List->getNumInits()),
3558 clang::ArrayType::Normal, 0);
3559 InitializedEntity HiddenArray =
3560 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003561 InitializationKind Kind = InitializationKind::CreateDirectList(
3562 List->getExprLoc(), List->getLocStart(), List->getLocEnd());
Manman Ren073db022016-03-10 18:53:19 +00003563 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3564 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003565 if (Sequence)
3566 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003567 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003568}
3569
Richard Smith7c2bcc92016-09-07 02:14:33 +00003570/// Determine if the constructor has the signature of a copy or move
3571/// constructor for the type T of the class in which it was found. That is,
3572/// determine if its first parameter is of type T or reference to (possibly
3573/// cv-qualified) T.
3574static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3575 const ConstructorInfo &Info) {
3576 if (Info.Constructor->getNumParams() == 0)
3577 return false;
3578
3579 QualType ParmT =
3580 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3581 QualType ClassT =
3582 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3583
3584 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3585}
3586
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003587static OverloadingResult
3588ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003589 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003590 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003591 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003592 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003593 OverloadCandidateSet::iterator &Best,
3594 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003595 bool OnlyListConstructors, bool IsListInit,
3596 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003597 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003598
Richard Smith40c78062015-02-21 02:31:57 +00003599 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003600 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003601 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003602 continue;
3603
Richard Smith7c2bcc92016-09-07 02:14:33 +00003604 if (!AllowExplicit && Info.Constructor->isExplicit())
3605 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003606
Richard Smith7c2bcc92016-09-07 02:14:33 +00003607 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3608 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003609
Richard Smith7c2bcc92016-09-07 02:14:33 +00003610 // C++11 [over.best.ics]p4:
3611 // ... and the constructor or user-defined conversion function is a
3612 // candidate by
3613 // - 13.3.1.3, when the argument is the temporary in the second step
3614 // of a class copy-initialization, or
3615 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3616 // - the second phase of 13.3.1.7 when the initializer list has exactly
3617 // one element that is itself an initializer list, and the target is
3618 // the first parameter of a constructor of class X, and the conversion
3619 // is to X or reference to (possibly cv-qualified X),
3620 // user-defined conversion sequences are not considered.
3621 bool SuppressUserConversions =
3622 SecondStepOfCopyInit ||
3623 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3624 hasCopyOrMoveCtorParam(S.Context, Info));
3625
3626 if (Info.ConstructorTmpl)
3627 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3628 /*ExplicitArgs*/ nullptr, Args,
3629 CandidateSet, SuppressUserConversions);
3630 else {
3631 // C++ [over.match.copy]p1:
3632 // - When initializing a temporary to be bound to the first parameter
3633 // of a constructor [for type T] that takes a reference to possibly
3634 // cv-qualified T as its first argument, called with a single
3635 // argument in the context of direct-initialization, explicit
3636 // conversion functions are also considered.
3637 // FIXME: What if a constructor template instantiates to such a signature?
3638 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3639 Args.size() == 1 &&
3640 hasCopyOrMoveCtorParam(S.Context, Info);
3641 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3642 CandidateSet, SuppressUserConversions,
3643 /*PartialOverloading=*/false,
3644 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003645 }
3646 }
3647
Richard Smith67ef14f2017-09-26 18:37:55 +00003648 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3649 //
3650 // When initializing an object of class type T by constructor
3651 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3652 // from a single expression of class type U, conversion functions of
3653 // U that convert to the non-reference type cv T are candidates.
3654 // Explicit conversion functions are only candidates during
3655 // direct-initialization.
3656 //
3657 // Note: SecondStepOfCopyInit is only ever true in this case when
3658 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003659 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003660 !SecondStepOfCopyInit) {
3661 Expr *Initializer = Args[0];
3662 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3663 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3664 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3665 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3666 NamedDecl *D = *I;
3667 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3668 D = D->getUnderlyingDecl();
3669
3670 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3671 CXXConversionDecl *Conv;
3672 if (ConvTemplate)
3673 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3674 else
3675 Conv = cast<CXXConversionDecl>(D);
3676
3677 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3678 if (ConvTemplate)
3679 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3680 ActingDC, Initializer, DestType,
3681 CandidateSet, AllowExplicit,
3682 /*AllowResultConversion*/false);
3683 else
3684 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3685 DestType, CandidateSet, AllowExplicit,
3686 /*AllowResultConversion*/false);
3687 }
3688 }
3689 }
3690 }
3691
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003692 // Perform overload resolution and return the result.
3693 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3694}
3695
Sebastian Redled2e5322011-12-22 14:44:04 +00003696/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3697/// enumerates the constructors of the initialized entity and performs overload
3698/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003699/// \param DestType The destination class type.
3700/// \param DestArrayType The destination type, which is either DestType or
3701/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003702/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003703/// \param IsInitListCopy Is this non-list-initialization resulting from a
3704/// list-initialization from {x} where x is the same
3705/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003706static void TryConstructorInitialization(Sema &S,
3707 const InitializedEntity &Entity,
3708 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003709 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003710 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003711 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003712 bool IsListInit = false,
3713 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003714 assert(((!IsListInit && !IsInitListCopy) ||
3715 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3716 "IsListInit/IsInitListCopy must come with a single initializer list "
3717 "argument.");
3718 InitListExpr *ILE =
3719 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3720 MultiExprArg UnwrappedArgs =
3721 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003722
Sebastian Redled2e5322011-12-22 14:44:04 +00003723 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003724 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003725 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003726 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003727 }
3728
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003729 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003730 // - If the initializer expression is a prvalue and the cv-unqualified
3731 // version of the source type is the same class as the class of the
3732 // destination, the initializer expression is used to initialize the
3733 // destination object.
3734 // Per DR (no number yet), this does not apply when initializing a base
3735 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003736 // ObjC++: Lambda captured by the block in the lambda to block conversion
3737 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003738 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003739 Entity.getKind() != InitializedEntity::EK_Base &&
3740 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003741 Entity.getKind() !=
3742 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003743 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3744 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3745 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003746 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003747 if (ILE)
3748 Sequence.RewrapReferenceInitList(DestType, ILE);
3749 return;
3750 }
3751
Sebastian Redled2e5322011-12-22 14:44:04 +00003752 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3753 assert(DestRecordType && "Constructor initialization requires record type");
3754 CXXRecordDecl *DestRecordDecl
3755 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3756
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003757 // Build the candidate set directly in the initialization sequence
3758 // structure, so that it will persist if we fail.
3759 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3760
3761 // Determine whether we are allowed to call explicit constructors or
3762 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003763 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003764 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003765
Sebastian Redled2e5322011-12-22 14:44:04 +00003766 // - Otherwise, if T is a class type, constructors are considered. The
3767 // applicable constructors are enumerated, and the best one is chosen
3768 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003769 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003770
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003771 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003772 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003773 bool AsInitializerList = false;
3774
Larisse Voufo19d08672015-01-27 18:47:05 +00003775 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003776 // When objects of non-aggregate type T are list-initialized, such that
3777 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3778 // according to the rules in this section, overload resolution selects
3779 // the constructor in two phases:
3780 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003781 // - Initially, the candidate functions are the initializer-list
3782 // constructors of the class T and the argument list consists of the
3783 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003784 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003785 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003786
3787 // If the initializer list has no elements and T has a default constructor,
3788 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003789 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003790 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003791 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003792 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003793 /*OnlyListConstructor=*/true,
3794 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003795 }
3796
3797 // C++11 [over.match.list]p1:
3798 // - If no viable initializer-list constructor is found, overload resolution
3799 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003800 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003801 // elements of the initializer list.
3802 if (Result == OR_No_Viable_Function) {
3803 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003804 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003805 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003806 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003807 /*OnlyListConstructors=*/false,
3808 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003809 }
3810 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003811 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003812 InitializationSequence::FK_ListConstructorOverloadFailed :
3813 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003814 Result);
3815 return;
3816 }
3817
Richard Smith67ef14f2017-09-26 18:37:55 +00003818 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3819
3820 // In C++17, ResolveConstructorOverload can select a conversion function
3821 // instead of a constructor.
3822 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3823 // Add the user-defined conversion step that calls the conversion function.
3824 QualType ConvType = CD->getConversionType();
3825 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3826 "should not have selected this conversion function");
3827 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3828 HadMultipleCandidates);
3829 if (!S.Context.hasSameType(ConvType, DestType))
3830 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3831 if (IsListInit)
3832 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3833 return;
3834 }
3835
Richard Smithd86812d2012-07-05 08:39:21 +00003836 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003837 // If a program calls for the default initialization of an object
3838 // of a const-qualified type T, T shall be a class type with a
3839 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003840 // C++ core issue 253 proposal:
3841 // If the implicit default constructor initializes all subobjects, no
3842 // initializer should be required.
3843 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3844 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003845 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003846 Entity.getType().isConstQualified()) {
3847 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3848 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3849 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3850 return;
3851 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003852 }
3853
Sebastian Redl048a6d72012-04-01 19:54:59 +00003854 // C++11 [over.match.list]p1:
3855 // In copy-list-initialization, if an explicit constructor is chosen, the
3856 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003857 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003858 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3859 return;
3860 }
3861
Sebastian Redled2e5322011-12-22 14:44:04 +00003862 // Add the constructor initialization step. Any cv-qualification conversion is
3863 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00003864 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003865 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003866 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003867}
3868
Sebastian Redl29526f02011-11-27 16:50:07 +00003869static bool
3870ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3871 Expr *Initializer,
3872 QualType &SourceType,
3873 QualType &UnqualifiedSourceType,
3874 QualType UnqualifiedTargetType,
3875 InitializationSequence &Sequence) {
3876 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3877 S.Context.OverloadTy) {
3878 DeclAccessPair Found;
3879 bool HadMultipleCandidates = false;
3880 if (FunctionDecl *Fn
3881 = S.ResolveAddressOfOverloadedFunction(Initializer,
3882 UnqualifiedTargetType,
3883 false, Found,
3884 &HadMultipleCandidates)) {
3885 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3886 HadMultipleCandidates);
3887 SourceType = Fn->getType();
3888 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3889 } else if (!UnqualifiedTargetType->isRecordType()) {
3890 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3891 return true;
3892 }
3893 }
3894 return false;
3895}
3896
3897static void TryReferenceInitializationCore(Sema &S,
3898 const InitializedEntity &Entity,
3899 const InitializationKind &Kind,
3900 Expr *Initializer,
3901 QualType cv1T1, QualType T1,
3902 Qualifiers T1Quals,
3903 QualType cv2T2, QualType T2,
3904 Qualifiers T2Quals,
3905 InitializationSequence &Sequence);
3906
Richard Smithd86812d2012-07-05 08:39:21 +00003907static void TryValueInitialization(Sema &S,
3908 const InitializedEntity &Entity,
3909 const InitializationKind &Kind,
3910 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003911 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003912
Sebastian Redl29526f02011-11-27 16:50:07 +00003913/// \brief Attempt list initialization of a reference.
3914static void TryReferenceListInitialization(Sema &S,
3915 const InitializedEntity &Entity,
3916 const InitializationKind &Kind,
3917 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003918 InitializationSequence &Sequence,
3919 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003920 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003921 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003922 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3923 return;
3924 }
David Majnemer9370dc22015-04-26 07:35:03 +00003925 // Can't reference initialize a compound literal.
3926 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3927 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3928 return;
3929 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003930
3931 QualType DestType = Entity.getType();
3932 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3933 Qualifiers T1Quals;
3934 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3935
3936 // Reference initialization via an initializer list works thus:
3937 // If the initializer list consists of a single element that is
3938 // reference-related to the referenced type, bind directly to that element
3939 // (possibly creating temporaries).
3940 // Otherwise, initialize a temporary with the initializer list and
3941 // bind to that.
3942 if (InitList->getNumInits() == 1) {
3943 Expr *Initializer = InitList->getInit(0);
3944 QualType cv2T2 = Initializer->getType();
3945 Qualifiers T2Quals;
3946 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3947
3948 // If this fails, creating a temporary wouldn't work either.
3949 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3950 T1, Sequence))
3951 return;
3952
3953 SourceLocation DeclLoc = Initializer->getLocStart();
3954 bool dummy1, dummy2, dummy3;
3955 Sema::ReferenceCompareResult RefRelationship
3956 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3957 dummy2, dummy3);
3958 if (RefRelationship >= Sema::Ref_Related) {
3959 // Try to bind the reference here.
3960 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3961 T1Quals, cv2T2, T2, T2Quals, Sequence);
3962 if (Sequence)
3963 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3964 return;
3965 }
Richard Smith03d93932013-01-15 07:58:29 +00003966
3967 // Update the initializer if we've resolved an overloaded function.
3968 if (Sequence.step_begin() != Sequence.step_end())
3969 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003970 }
3971
3972 // Not reference-related. Create a temporary and bind to that.
3973 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3974
Manman Ren073db022016-03-10 18:53:19 +00003975 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3976 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00003977 if (Sequence) {
3978 if (DestType->isRValueReferenceType() ||
3979 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3980 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3981 else
3982 Sequence.SetFailed(
3983 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3984 }
3985}
3986
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003987/// \brief Attempt list initialization (C++0x [dcl.init.list])
3988static void TryListInitialization(Sema &S,
3989 const InitializedEntity &Entity,
3990 const InitializationKind &Kind,
3991 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003992 InitializationSequence &Sequence,
3993 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003994 QualType DestType = Entity.getType();
3995
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003996 // C++ doesn't allow scalar initialization with more than one argument.
3997 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003998 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003999 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4000 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4001 return;
4002 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004003 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004004 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4005 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004006 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004007 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004008
Larisse Voufod2010992015-01-24 23:09:54 +00004009 if (DestType->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004010 !S.isCompleteType(InitList->getLocStart(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004011 Sequence.setIncompleteTypeFailure(DestType);
4012 return;
4013 }
Richard Smithd86812d2012-07-05 08:39:21 +00004014
Larisse Voufo19d08672015-01-27 18:47:05 +00004015 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004016 // - If T is a class type and the initializer list has a single element of
4017 // type cv U, where U is T or a class derived from T, the object is
4018 // initialized from that element (by copy-initialization for
4019 // copy-list-initialization, or by direct-initialization for
4020 // direct-list-initialization).
4021 // - Otherwise, if T is a character array and the initializer list has a
4022 // single element that is an appropriately-typed string literal
4023 // (8.5.2 [dcl.init.string]), initialization is performed as described
4024 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004025 // - Otherwise, if T is an aggregate, [...] (continue below).
4026 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004027 if (DestType->isRecordType()) {
4028 QualType InitType = InitList->getInit(0)->getType();
4029 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004030 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004031 Expr *InitListAsExpr = InitList;
4032 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004033 DestType, Sequence,
4034 /*InitListSyntax*/false,
4035 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004036 return;
4037 }
4038 }
4039 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4040 Expr *SubInit[1] = {InitList->getInit(0)};
4041 if (!isa<VariableArrayType>(DestAT) &&
4042 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4043 InitializationKind SubKind =
4044 Kind.getKind() == InitializationKind::IK_DirectList
4045 ? InitializationKind::CreateDirect(Kind.getLocation(),
4046 InitList->getLBraceLoc(),
4047 InitList->getRBraceLoc())
4048 : Kind;
4049 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004050 /*TopLevelOfInitList*/ true,
4051 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004052
4053 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4054 // the element is not an appropriately-typed string literal, in which
4055 // case we should proceed as in C++11 (below).
4056 if (Sequence) {
4057 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4058 return;
4059 }
4060 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004061 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004062 }
Larisse Voufod2010992015-01-24 23:09:54 +00004063
4064 // C++11 [dcl.init.list]p3:
4065 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004066 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4067 (S.getLangOpts().CPlusPlus11 &&
4068 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004069 if (S.getLangOpts().CPlusPlus11) {
4070 // - Otherwise, if the initializer list has no elements and T is a
4071 // class type with a default constructor, the object is
4072 // value-initialized.
4073 if (InitList->getNumInits() == 0) {
4074 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4075 if (RD->hasDefaultConstructor()) {
4076 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4077 return;
4078 }
4079 }
4080
4081 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4082 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004083 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4084 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004085 return;
4086
4087 // - Otherwise, if T is a class type, constructors are considered.
4088 Expr *InitListAsExpr = InitList;
4089 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004090 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004091 } else
4092 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4093 return;
4094 }
4095
Richard Smith089c3162013-09-21 21:55:46 +00004096 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004097 InitList->getNumInits() == 1) {
4098 Expr *E = InitList->getInit(0);
4099
4100 // - Otherwise, if T is an enumeration with a fixed underlying type,
4101 // the initializer-list has a single element v, and the initialization
4102 // is direct-list-initialization, the object is initialized with the
4103 // value T(v); if a narrowing conversion is required to convert v to
4104 // the underlying type of T, the program is ill-formed.
4105 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004106 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004107 Kind.getKind() == InitializationKind::IK_DirectList &&
4108 ET && ET->getDecl()->isFixed() &&
4109 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4110 (E->getType()->isIntegralOrEnumerationType() ||
4111 E->getType()->isFloatingType())) {
4112 // There are two ways that T(v) can work when T is an enumeration type.
4113 // If there is either an implicit conversion sequence from v to T or
4114 // a conversion function that can convert from v to T, then we use that.
4115 // Otherwise, if v is of integral, enumeration, or floating-point type,
4116 // it is converted to the enumeration type via its underlying type.
4117 // There is no overlap possible between these two cases (except when the
4118 // source value is already of the destination type), and the first
4119 // case is handled by the general case for single-element lists below.
4120 ImplicitConversionSequence ICS;
4121 ICS.setStandard();
4122 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004123 if (!E->isRValue())
4124 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004125 // If E is of a floating-point type, then the conversion is ill-formed
4126 // due to narrowing, but go through the motions in order to produce the
4127 // right diagnostic.
4128 ICS.Standard.Second = E->getType()->isFloatingType()
4129 ? ICK_Floating_Integral
4130 : ICK_Integral_Conversion;
4131 ICS.Standard.setFromType(E->getType());
4132 ICS.Standard.setToType(0, E->getType());
4133 ICS.Standard.setToType(1, DestType);
4134 ICS.Standard.setToType(2, DestType);
4135 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4136 /*TopLevelOfInitList*/true);
4137 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4138 return;
4139 }
4140
Richard Smith089c3162013-09-21 21:55:46 +00004141 // - Otherwise, if the initializer list has a single element of type E
4142 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004143 // initialized from that element (by copy-initialization for
4144 // copy-list-initialization, or by direct-initialization for
4145 // direct-list-initialization); if a narrowing conversion is required
4146 // to convert the element to T, the program is ill-formed.
4147 //
Richard Smith089c3162013-09-21 21:55:46 +00004148 // Per core-24034, this is direct-initialization if we were performing
4149 // direct-list-initialization and copy-initialization otherwise.
4150 // We can't use InitListChecker for this, because it always performs
4151 // copy-initialization. This only matters if we might use an 'explicit'
4152 // conversion operator, so we only need to handle the cases where the source
4153 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004154 if (InitList->getInit(0)->getType()->isRecordType()) {
4155 InitializationKind SubKind =
4156 Kind.getKind() == InitializationKind::IK_DirectList
4157 ? InitializationKind::CreateDirect(Kind.getLocation(),
4158 InitList->getLBraceLoc(),
4159 InitList->getRBraceLoc())
4160 : Kind;
4161 Expr *SubInit[1] = { InitList->getInit(0) };
4162 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4163 /*TopLevelOfInitList*/true,
4164 TreatUnavailableAsInvalid);
4165 if (Sequence)
4166 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4167 return;
4168 }
Richard Smith089c3162013-09-21 21:55:46 +00004169 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004170
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004171 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004172 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004173 if (CheckInitList.HadError()) {
4174 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4175 return;
4176 }
4177
4178 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004179 Sequence.AddListInitializationStep(DestType);
4180}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004181
4182/// \brief Try a reference initialization that involves calling a conversion
4183/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004184static OverloadingResult TryRefInitWithConversionFunction(
4185 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4186 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4187 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004188 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004189 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4190 QualType T1 = cv1T1.getUnqualifiedType();
4191 QualType cv2T2 = Initializer->getType();
4192 QualType T2 = cv2T2.getUnqualifiedType();
4193
4194 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004195 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004196 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004198 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004199 ObjCConversion,
4200 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004201 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004202 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004203 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004204 (void)ObjCLifetimeConversion;
4205
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004206 // Build the candidate set directly in the initialization sequence
4207 // structure, so that it will persist if we fail.
4208 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004209 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004210
4211 // Determine whether we are allowed to call explicit constructors or
4212 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004213 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00004214 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4215
Craig Topperc3ec1492014-05-26 06:22:03 +00004216 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004217 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004218 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004219 // The type we're converting to is a class type. Enumerate its constructors
4220 // to see if there is a suitable conversion.
4221 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004222
Richard Smith40c78062015-02-21 02:31:57 +00004223 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004224 auto Info = getConstructorInfo(D);
4225 if (!Info.Constructor)
4226 continue;
John McCalla0296f72010-03-19 07:35:19 +00004227
Richard Smithc2bebe92016-05-11 20:37:46 +00004228 if (!Info.Constructor->isInvalidDecl() &&
4229 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4230 if (Info.ConstructorTmpl)
4231 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004232 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004233 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004234 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004235 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004236 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004237 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004238 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004241 }
John McCall3696dcb2010-08-17 07:23:57 +00004242 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4243 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244
Craig Topperc3ec1492014-05-26 06:22:03 +00004245 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004246 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004247 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004248 // The type we're converting from is a class type, enumerate its conversion
4249 // functions.
4250 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4251
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004252 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4253 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004254 NamedDecl *D = *I;
4255 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4256 if (isa<UsingShadowDecl>(D))
4257 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004259 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4260 CXXConversionDecl *Conv;
4261 if (ConvTemplate)
4262 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4263 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004264 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004265
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004266 // If the conversion function doesn't return a reference type,
4267 // it can't be considered for this conversion unless we're allowed to
4268 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269 // FIXME: Do we need to make sure that we only consider conversion
4270 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004271 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004272 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4274 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004275 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004276 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004277 DestType, CandidateSet,
4278 /*AllowObjCConversionOnExplicit=*/
4279 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004280 else
John McCalla0296f72010-03-19 07:35:19 +00004281 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004282 Initializer, DestType, CandidateSet,
4283 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004284 }
4285 }
4286 }
John McCall3696dcb2010-08-17 07:23:57 +00004287 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4288 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004289
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004290 SourceLocation DeclLoc = Initializer->getLocStart();
4291
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004293 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004295 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004296 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004297
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004299 // This is the overload that will be used for this initialization step if we
4300 // use this initialization. Mark it as referenced.
4301 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004302
Richard Smithb8c0f552016-12-09 18:49:13 +00004303 // Compute the returned type and value kind of the conversion.
4304 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004305 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004306 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004307 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004308 cv3T3 = T1;
4309
4310 ExprValueKind VK = VK_RValue;
4311 if (cv3T3->isLValueReferenceType())
4312 VK = VK_LValue;
4313 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4314 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4315 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004316
4317 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004318 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004319 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004320 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004321
Richard Smithb8c0f552016-12-09 18:49:13 +00004322 // Determine whether we'll need to perform derived-to-base adjustments or
4323 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004324 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004325 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004326 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004327 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004328 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004329 NewDerivedToBase, NewObjCConversion,
4330 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004331
4332 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004333 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004334 assert(!isa<CXXConstructorDecl>(Function) &&
4335 "should not have conversion after constructor");
4336
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004337 ImplicitConversionSequence ICS;
4338 ICS.setStandard();
4339 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004340 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4341
4342 // Every implicit conversion results in a prvalue, except for a glvalue
4343 // derived-to-base conversion, which we handle below.
4344 cv3T3 = ICS.Standard.getToType(2);
4345 VK = VK_RValue;
4346 }
4347
4348 // If the converted initializer is a prvalue, its type T4 is adjusted to
4349 // type "cv1 T4" and the temporary materialization conversion is applied.
4350 //
4351 // We adjust the cv-qualifications to match the reference regardless of
4352 // whether we have a prvalue so that the AST records the change. In this
4353 // case, T4 is "cv3 T3".
4354 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4355 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4356 Sequence.AddQualificationConversionStep(cv1T4, VK);
4357 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4358 VK = IsLValueRef ? VK_LValue : VK_XValue;
4359
4360 if (NewDerivedToBase)
4361 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004362 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004363 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004364
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004365 return OR_Success;
4366}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Richard Smithc620f552011-10-19 16:55:56 +00004368static void CheckCXX98CompatAccessibleCopy(Sema &S,
4369 const InitializedEntity &Entity,
4370 Expr *CurInitExpr);
4371
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4373static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004374 const InitializedEntity &Entity,
4375 const InitializationKind &Kind,
4376 Expr *Initializer,
4377 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004378 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004379 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004380 Qualifiers T1Quals;
4381 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004382 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004383 Qualifiers T2Quals;
4384 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004385
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004386 // If the initializer is the address of an overloaded function, try
4387 // to resolve the overloaded function. If all goes well, T2 is the
4388 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004389 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4390 T1, Sequence))
4391 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004392
Sebastian Redl29526f02011-11-27 16:50:07 +00004393 // Delegate everything else to a subfunction.
4394 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4395 T1Quals, cv2T2, T2, T2Quals, Sequence);
4396}
4397
Richard Smithb8c0f552016-12-09 18:49:13 +00004398/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004399/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004400/// such a glvalue will always create a temporary.
4401static bool isNonReferenceableGLValue(Expr *E) {
4402 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004403}
4404
Sebastian Redl29526f02011-11-27 16:50:07 +00004405/// \brief Reference initialization without resolving overloaded functions.
4406static void TryReferenceInitializationCore(Sema &S,
4407 const InitializedEntity &Entity,
4408 const InitializationKind &Kind,
4409 Expr *Initializer,
4410 QualType cv1T1, QualType T1,
4411 Qualifiers T1Quals,
4412 QualType cv2T2, QualType T2,
4413 Qualifiers T2Quals,
4414 InitializationSequence &Sequence) {
4415 QualType DestType = Entity.getType();
4416 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004417 // Compute some basic properties of the types and the initializer.
4418 bool isLValueRef = DestType->isLValueReferenceType();
4419 bool isRValueRef = !isLValueRef;
4420 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004421 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004422 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004423 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004424 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004425 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004426 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004427
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004428 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004430 // "cv2 T2" as follows:
4431 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004433 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004434 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004435 // there are no function rvalues in C++, rvalue refs to functions are treated
4436 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004437 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004438 bool T1Function = T1->isFunctionType();
4439 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004440 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004441 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004443 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004445 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004446 if (T1Quals != T2Quals)
4447 // Convert to cv1 T2. This should only add qualifiers unless this is a
4448 // c-style cast. The removal of qualifiers in that case notionally
4449 // happens after the reference binding, but that doesn't matter.
4450 Sequence.AddQualificationConversionStep(
4451 S.Context.getQualifiedType(T2, T1Quals),
4452 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004453 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004454 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004455 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004456 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004457
Richard Smithb8c0f552016-12-09 18:49:13 +00004458 // We only create a temporary here when binding a reference to a
4459 // bit-field or vector element. Those cases are't supposed to be
4460 // handled by this bullet, but the outcome is the same either way.
4461 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004462 return;
4463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
4465 // - has a class type (i.e., T2 is a class type), where T1 is not
4466 // reference-related to T2, and can be implicitly converted to an
4467 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4468 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004469 // applicable conversion functions (13.3.1.6) and choosing the best
4470 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004471 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004472 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004473 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4474 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004475 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004476 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4477 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004478 if (ConvOvlResult == OR_Success)
4479 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004480 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004481 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004482 InitializationSequence::FK_ReferenceInitOverloadFailed,
4483 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004484 }
4485 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004486
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004487 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004488 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004489 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004490 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004491 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4492 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4493 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004494 Sequence.SetOverloadFailure(
4495 InitializationSequence::FK_ReferenceInitOverloadFailed,
4496 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004497 else if (!InitCategory.isLValue())
4498 Sequence.SetFailed(
4499 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4500 else {
4501 InitializationSequence::FailureKind FK;
4502 switch (RefRelationship) {
4503 case Sema::Ref_Compatible:
4504 if (Initializer->refersToBitField())
4505 FK = InitializationSequence::
4506 FK_NonConstLValueReferenceBindingToBitfield;
4507 else if (Initializer->refersToVectorElement())
4508 FK = InitializationSequence::
4509 FK_NonConstLValueReferenceBindingToVectorElement;
4510 else
4511 llvm_unreachable("unexpected kind of compatible initializer");
4512 break;
4513 case Sema::Ref_Related:
4514 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4515 break;
4516 case Sema::Ref_Incompatible:
4517 FK = InitializationSequence::
4518 FK_NonConstLValueReferenceBindingToUnrelated;
4519 break;
4520 }
4521 Sequence.SetFailed(FK);
4522 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004523 return;
4524 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004525
Douglas Gregor92e460e2011-01-20 16:44:54 +00004526 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004527 // - is an
4528 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4529 // [1z] rvalue (but not a bit-field) or
4530 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4531 //
4532 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004533 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004534 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004536 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004537 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004538 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004539 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004540 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004541 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004542 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004543 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4544 // compiler the freedom to perform a copy here or bind to the
4545 // object, while C++0x requires that we bind directly to the
4546 // object. Hence, we always bind to the object without making an
4547 // extra copy. However, in C++03 requires that we check for the
4548 // presence of a suitable copy constructor:
4549 //
4550 // The constructor that would be used to make the copy shall
4551 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004552 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004553 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004554 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004555 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557
Richard Smithb8c0f552016-12-09 18:49:13 +00004558 // C++1z [dcl.init.ref]/5.2.1.2:
4559 // If the converted initializer is a prvalue, its type T4 is adjusted
4560 // to type "cv1 T4" and the temporary materialization conversion is
4561 // applied.
4562 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4563 if (T1Quals != T2Quals)
4564 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4565 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4566 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4567
4568 // In any case, the reference is bound to the resulting glvalue (or to
4569 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004570 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004571 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004572 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004573 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576
4577 // - has a class type (i.e., T2 is a class type), where T1 is not
4578 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004579 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4580 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004581 //
4582 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004583 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004584 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004585 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004586 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4587 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004588 if (ConvOvlResult)
4589 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004590 InitializationSequence::FK_ReferenceInitOverloadFailed,
4591 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004592
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004593 return;
4594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595
Richard Smithce766292016-10-21 23:01:55 +00004596 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004597 isRValueRef && InitCategory.isLValue()) {
4598 Sequence.SetFailed(
4599 InitializationSequence::FK_RValueReferenceBindingToLValue);
4600 return;
4601 }
4602
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004603 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4604 return;
4605 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004606
4607 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004608 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004609 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004610 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004611
John McCallec6f4e92010-06-04 02:29:22 +00004612 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4613
Richard Smith2eabf782013-06-13 00:57:57 +00004614 // FIXME: Why do we use an implicit conversion here rather than trying
4615 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004616 ImplicitConversionSequence ICS
4617 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004618 /*SuppressUserConversions=*/false,
4619 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004620 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004621 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4622 /*AllowObjCWritebackConversion=*/false);
4623
4624 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004625 // FIXME: Use the conversion function set stored in ICS to turn
4626 // this into an overloading ambiguity diagnostic. However, we need
4627 // to keep that set as an OverloadCandidateSet rather than as some
4628 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004629 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4630 Sequence.SetOverloadFailure(
4631 InitializationSequence::FK_ReferenceInitOverloadFailed,
4632 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004633 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4634 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004635 else
4636 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004637 return;
John McCall31168b02011-06-15 23:02:42 +00004638 } else {
4639 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004640 }
4641
4642 // [...] If T1 is reference-related to T2, cv1 must be the
4643 // same cv-qualification as, or greater cv-qualification
4644 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004645 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4646 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004648 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004649 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4650 return;
4651 }
4652
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004654 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004656 InitCategory.isLValue()) {
4657 Sequence.SetFailed(
4658 InitializationSequence::FK_RValueReferenceBindingToLValue);
4659 return;
4660 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004662 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004663}
4664
4665/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004666/// (C++ [dcl.init.string], C99 6.7.8).
4667static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004668 const InitializedEntity &Entity,
4669 const InitializationKind &Kind,
4670 Expr *Initializer,
4671 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004672 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004673}
4674
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004675/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004677 const InitializedEntity &Entity,
4678 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004679 InitializationSequence &Sequence,
4680 InitListExpr *InitList) {
4681 assert((!InitList || InitList->getNumInits() == 0) &&
4682 "Shouldn't use value-init for non-empty init lists");
4683
Richard Smith1bfe0682012-02-14 21:14:13 +00004684 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004685 //
4686 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004687 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004689 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004690 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004692 if (const RecordType *RT = T->getAs<RecordType>()) {
4693 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004694 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004695 // C++98:
4696 // -- if T is a class type (clause 9) with a user-declared constructor
4697 // (12.1), then the default constructor for T is called (and the
4698 // initialization is ill-formed if T has no accessible default
4699 // constructor);
4700 // C++11:
4701 // -- if T is a class type (clause 9) with either no default constructor
4702 // (12.1 [class.ctor]) or a default constructor that is user-provided
4703 // or deleted, then the object is default-initialized;
4704 //
4705 // Note that the C++11 rule is the same as the C++98 rule if there are no
4706 // defaulted or deleted constructors, so we just use it unconditionally.
4707 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4708 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4709 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710
Richard Smith1bfe0682012-02-14 21:14:13 +00004711 // -- if T is a (possibly cv-qualified) non-union class type without a
4712 // user-provided or deleted default constructor, then the object is
4713 // zero-initialized and, if T has a non-trivial default constructor,
4714 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004715 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4716 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004717 if (NeedZeroInitialization)
4718 Sequence.AddZeroInitializationStep(Entity.getType());
4719
Richard Smith593f9932012-12-08 02:01:17 +00004720 // C++03:
4721 // -- if T is a non-union class type without a user-declared constructor,
4722 // then every non-static data member and base class component of T is
4723 // value-initialized;
4724 // [...] A program that calls for [...] value-initialization of an
4725 // entity of reference type is ill-formed.
4726 //
4727 // C++11 doesn't need this handling, because value-initialization does not
4728 // occur recursively there, and the implicit default constructor is
4729 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004730 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004731 ClassDecl->hasUninitializedReferenceMember()) {
4732 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4733 return;
4734 }
4735
Richard Smithd86812d2012-07-05 08:39:21 +00004736 // If this is list-value-initialization, pass the empty init list on when
4737 // building the constructor call. This affects the semantics of a few
4738 // things (such as whether an explicit default constructor can be called).
4739 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004740 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004741 bool InitListSyntax = InitList;
4742
Richard Smith81f5ade2016-12-15 02:28:18 +00004743 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004744 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4745 return TryConstructorInitialization(
4746 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004747 }
4748 }
4749
Douglas Gregor1b303932009-12-22 15:35:07 +00004750 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004751}
4752
Douglas Gregor85dabae2009-12-16 01:38:02 +00004753/// \brief Attempt default initialization (C++ [dcl.init]p6).
4754static void TryDefaultInitialization(Sema &S,
4755 const InitializedEntity &Entity,
4756 const InitializationKind &Kind,
4757 InitializationSequence &Sequence) {
4758 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Douglas Gregor85dabae2009-12-16 01:38:02 +00004760 // C++ [dcl.init]p6:
4761 // To default-initialize an object of type T means:
4762 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004763 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4764
Douglas Gregor85dabae2009-12-16 01:38:02 +00004765 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4766 // constructor for T is called (and the initialization is ill-formed if
4767 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004768 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004769 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4770 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004771 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773
Douglas Gregor85dabae2009-12-16 01:38:02 +00004774 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Douglas Gregor85dabae2009-12-16 01:38:02 +00004776 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004778 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004779 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004780 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4781 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004782 return;
4783 }
4784
4785 // If the destination type has a lifetime property, zero-initialize it.
4786 if (DestType.getQualifiers().hasObjCLifetime()) {
4787 Sequence.AddZeroInitializationStep(Entity.getType());
4788 return;
4789 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004790}
4791
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004792/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4793/// which enumerates all conversion functions and performs overload resolution
4794/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004796 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004797 const InitializationKind &Kind,
4798 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004799 InitializationSequence &Sequence,
4800 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004801 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4802 QualType SourceType = Initializer->getType();
4803 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4804 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805
Douglas Gregor540c3b02009-12-14 17:27:33 +00004806 // Build the candidate set directly in the initialization sequence
4807 // structure, so that it will persist if we fail.
4808 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004809 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004810
Douglas Gregor540c3b02009-12-14 17:27:33 +00004811 // Determine whether we are allowed to call explicit constructors or
4812 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004813 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814
Douglas Gregor540c3b02009-12-14 17:27:33 +00004815 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4816 // The type we're converting to is a class type. Enumerate its constructors
4817 // to see if there is a suitable conversion.
4818 CXXRecordDecl *DestRecordDecl
4819 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Douglas Gregord9848152010-04-26 14:36:57 +00004821 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004822 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004823 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004824 auto Info = getConstructorInfo(D);
4825 if (!Info.Constructor)
4826 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827
Richard Smithc2bebe92016-05-11 20:37:46 +00004828 if (!Info.Constructor->isInvalidDecl() &&
4829 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4830 if (Info.ConstructorTmpl)
4831 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004832 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004833 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004834 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004835 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004836 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004837 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004838 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004840 }
Douglas Gregord9848152010-04-26 14:36:57 +00004841 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004842 }
Eli Friedman78275202009-12-19 08:11:05 +00004843
4844 SourceLocation DeclLoc = Initializer->getLocStart();
4845
Douglas Gregor540c3b02009-12-14 17:27:33 +00004846 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4847 // The type we're converting from is a class type, enumerate its conversion
4848 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004849
Eli Friedman4afe9a32009-12-20 22:12:03 +00004850 // We can only enumerate the conversion functions for a complete type; if
4851 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004852 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004853 CXXRecordDecl *SourceRecordDecl
4854 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004855
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004856 const auto &Conversions =
4857 SourceRecordDecl->getVisibleConversionFunctions();
4858 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004859 NamedDecl *D = *I;
4860 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4861 if (isa<UsingShadowDecl>(D))
4862 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863
Eli Friedman4afe9a32009-12-20 22:12:03 +00004864 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4865 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004866 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004867 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004868 else
John McCallda4458e2010-03-31 01:36:47 +00004869 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004870
Eli Friedman4afe9a32009-12-20 22:12:03 +00004871 if (AllowExplicit || !Conv->isExplicit()) {
4872 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004873 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004874 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004875 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004876 else
John McCalla0296f72010-03-19 07:35:19 +00004877 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004878 Initializer, DestType, CandidateSet,
4879 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004880 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004881 }
4882 }
4883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884
4885 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004886 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004887 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004888 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004889 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004890 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004891 Result);
4892 return;
4893 }
John McCall0d1da222010-01-12 00:44:57 +00004894
Douglas Gregor540c3b02009-12-14 17:27:33 +00004895 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004896 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004897 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004898
Douglas Gregor540c3b02009-12-14 17:27:33 +00004899 if (isa<CXXConstructorDecl>(Function)) {
4900 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004901 // subsumed by the initialization. Per DR5, the created temporary is of the
4902 // cv-unqualified type of the destination.
4903 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4904 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004905 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00004906
4907 // C++14 and before:
4908 // - if the function is a constructor, the call initializes a temporary
4909 // of the cv-unqualified version of the destination type. The [...]
4910 // temporary [...] is then used to direct-initialize, according to the
4911 // rules above, the object that is the destination of the
4912 // copy-initialization.
4913 // Note that this just performs a simple object copy from the temporary.
4914 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004915 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00004916 // - if the function is a constructor, the call is a prvalue of the
4917 // cv-unqualified version of the destination type whose return object
4918 // is initialized by the constructor. The call is used to
4919 // direct-initialize, according to the rules above, the object that
4920 // is the destination of the copy-initialization.
4921 // Therefore we need to do nothing further.
4922 //
4923 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004924 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00004925 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004926 else if (DestType.hasQualifiers())
4927 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004928 return;
4929 }
4930
4931 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004932 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004933 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4934 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935
Richard Smithb8c0f552016-12-09 18:49:13 +00004936 if (ConvType->getAs<RecordType>()) {
4937 // The call is used to direct-initialize [...] the object that is the
4938 // destination of the copy-initialization.
4939 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004940 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00004941 // - If the initializer expression is a prvalue and the cv-unqualified
4942 // version of the source type is the same as the class of the
4943 // destination [... do not make an extra copy]
4944 //
4945 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004946 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00004947 Function->getReturnType()->isReferenceType() ||
4948 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4949 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004950 else if (!S.Context.hasSameType(ConvType, DestType))
4951 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00004952 return;
4953 }
4954
Douglas Gregor5ab11652010-04-17 22:01:05 +00004955 // If the conversion following the call to the conversion function
4956 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004957 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4958 Best->FinalConversion.Third) {
4959 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004960 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004961 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004962 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004963 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004964}
4965
Richard Smithf032001b2013-06-20 02:18:31 +00004966/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4967/// a function with a pointer return type contains a 'return false;' statement.
4968/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4969/// code using that header.
4970///
4971/// Work around this by treating 'return false;' as zero-initializing the result
4972/// if it's used in a pointer-returning function in a system header.
4973static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4974 const InitializedEntity &Entity,
4975 const Expr *Init) {
4976 return S.getLangOpts().CPlusPlus11 &&
4977 Entity.getKind() == InitializedEntity::EK_Result &&
4978 Entity.getType()->isPointerType() &&
4979 isa<CXXBoolLiteralExpr>(Init) &&
4980 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4981 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4982}
4983
John McCall31168b02011-06-15 23:02:42 +00004984/// The non-zero enum values here are indexes into diagnostic alternatives.
4985enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4986
4987/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004988static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004989 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004990 // Skip parens.
4991 e = e->IgnoreParens();
4992
4993 // Skip address-of nodes.
4994 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4995 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004996 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4997 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004998
4999 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005000 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5001 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005002 case CK_Dependent:
5003 case CK_BitCast:
5004 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005005 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005006 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005007
5008 case CK_ArrayToPointerDecay:
5009 return IIK_nonscalar;
5010
5011 case CK_NullToPointer:
5012 return IIK_okay;
5013
5014 default:
5015 break;
5016 }
5017
5018 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005019 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005020 // set isWeakAccess to true, to mean that there will be an implicit
5021 // load which requires a cleanup.
5022 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5023 isWeakAccess = true;
5024
John McCall63f84442011-06-27 23:59:58 +00005025 if (!isAddressOf) return IIK_nonlocal;
5026
John McCall113bee02012-03-10 09:33:50 +00005027 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5028 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005029
5030 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005031
5032 // If we have a conditional operator, check both sides.
5033 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005034 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5035 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005036 return iik;
5037
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005038 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005039
5040 // These are never scalar.
5041 } else if (isa<ArraySubscriptExpr>(e)) {
5042 return IIK_nonscalar;
5043
5044 // Otherwise, it needs to be a null pointer constant.
5045 } else {
5046 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5047 ? IIK_okay : IIK_nonlocal);
5048 }
5049
5050 return IIK_nonlocal;
5051}
5052
5053/// Check whether the given expression is a valid operand for an
5054/// indirect copy/restore.
5055static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5056 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005057 bool isWeakAccess = false;
5058 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5059 // If isWeakAccess to true, there will be an implicit
5060 // load which requires a cleanup.
5061 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005062 S.Cleanup.setExprNeedsCleanups(true);
5063
John McCall31168b02011-06-15 23:02:42 +00005064 if (iik == IIK_okay) return;
5065
5066 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5067 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5068 << src->getSourceRange();
5069}
5070
Douglas Gregore2f943b2011-02-22 18:29:51 +00005071/// \brief Determine whether we have compatible array types for the
5072/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005073static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005074 const ArrayType *Source) {
5075 // If the source and destination array types are equivalent, we're
5076 // done.
5077 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5078 return true;
5079
5080 // Make sure that the element types are the same.
5081 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5082 return false;
5083
5084 // The only mismatch we allow is when the destination is an
5085 // incomplete array type and the source is a constant array type.
5086 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5087}
5088
John McCall31168b02011-06-15 23:02:42 +00005089static bool tryObjCWritebackConversion(Sema &S,
5090 InitializationSequence &Sequence,
5091 const InitializedEntity &Entity,
5092 Expr *Initializer) {
5093 bool ArrayDecay = false;
5094 QualType ArgType = Initializer->getType();
5095 QualType ArgPointee;
5096 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5097 ArrayDecay = true;
5098 ArgPointee = ArgArrayType->getElementType();
5099 ArgType = S.Context.getPointerType(ArgPointee);
5100 }
5101
5102 // Handle write-back conversion.
5103 QualType ConvertedArgType;
5104 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5105 ConvertedArgType))
5106 return false;
5107
5108 // We should copy unless we're passing to an argument explicitly
5109 // marked 'out'.
5110 bool ShouldCopy = true;
5111 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5112 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5113
5114 // Do we need an lvalue conversion?
5115 if (ArrayDecay || Initializer->isGLValue()) {
5116 ImplicitConversionSequence ICS;
5117 ICS.setStandard();
5118 ICS.Standard.setAsIdentityConversion();
5119
5120 QualType ResultType;
5121 if (ArrayDecay) {
5122 ICS.Standard.First = ICK_Array_To_Pointer;
5123 ResultType = S.Context.getPointerType(ArgPointee);
5124 } else {
5125 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5126 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5127 }
5128
5129 Sequence.AddConversionSequenceStep(ICS, ResultType);
5130 }
5131
5132 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5133 return true;
5134}
5135
Guy Benyei61054192013-02-07 10:55:47 +00005136static bool TryOCLSamplerInitialization(Sema &S,
5137 InitializationSequence &Sequence,
5138 QualType DestType,
5139 Expr *Initializer) {
5140 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005141 (!Initializer->isIntegerConstantExpr(S.Context) &&
5142 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005143 return false;
5144
5145 Sequence.AddOCLSamplerInitStep(DestType);
5146 return true;
5147}
5148
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005149//
5150// OpenCL 1.2 spec, s6.12.10
5151//
5152// The event argument can also be used to associate the
5153// async_work_group_copy with a previous async copy allowing
5154// an event to be shared by multiple async copies; otherwise
5155// event should be zero.
5156//
5157static bool TryOCLZeroEventInitialization(Sema &S,
5158 InitializationSequence &Sequence,
5159 QualType DestType,
5160 Expr *Initializer) {
5161 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5162 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5163 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5164 return false;
5165
5166 Sequence.AddOCLZeroEventStep(DestType);
5167 return true;
5168}
5169
Egor Churaev89831422016-12-23 14:55:49 +00005170static bool TryOCLZeroQueueInitialization(Sema &S,
5171 InitializationSequence &Sequence,
5172 QualType DestType,
5173 Expr *Initializer) {
5174 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5175 !DestType->isQueueT() ||
5176 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5177 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5178 return false;
5179
5180 Sequence.AddOCLZeroQueueStep(DestType);
5181 return true;
5182}
5183
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005184InitializationSequence::InitializationSequence(Sema &S,
5185 const InitializedEntity &Entity,
5186 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005187 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005188 bool TopLevelOfInitList,
5189 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005190 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005191 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5192 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005193}
5194
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005195/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5196/// address of that function, this returns true. Otherwise, it returns false.
5197static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5198 auto *DRE = dyn_cast<DeclRefExpr>(E);
5199 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5200 return false;
5201
5202 return !S.checkAddressOfFunctionIsAvailable(
5203 cast<FunctionDecl>(DRE->getDecl()));
5204}
5205
Richard Smith410306b2016-12-12 02:53:20 +00005206/// Determine whether we can perform an elementwise array copy for this kind
5207/// of entity.
5208static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5209 switch (Entity.getKind()) {
5210 case InitializedEntity::EK_LambdaCapture:
5211 // C++ [expr.prim.lambda]p24:
5212 // For array members, the array elements are direct-initialized in
5213 // increasing subscript order.
5214 return true;
5215
5216 case InitializedEntity::EK_Variable:
5217 // C++ [dcl.decomp]p1:
5218 // [...] each element is copy-initialized or direct-initialized from the
5219 // corresponding element of the assignment-expression [...]
5220 return isa<DecompositionDecl>(Entity.getDecl());
5221
5222 case InitializedEntity::EK_Member:
5223 // C++ [class.copy.ctor]p14:
5224 // - if the member is an array, each element is direct-initialized with
5225 // the corresponding subobject of x
5226 return Entity.isImplicitMemberInitializer();
5227
5228 case InitializedEntity::EK_ArrayElement:
5229 // All the above cases are intended to apply recursively, even though none
5230 // of them actually say that.
5231 if (auto *E = Entity.getParent())
5232 return canPerformArrayCopy(*E);
5233 break;
5234
5235 default:
5236 break;
5237 }
5238
5239 return false;
5240}
5241
Richard Smith089c3162013-09-21 21:55:46 +00005242void InitializationSequence::InitializeFrom(Sema &S,
5243 const InitializedEntity &Entity,
5244 const InitializationKind &Kind,
5245 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005246 bool TopLevelOfInitList,
5247 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005248 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005249
John McCall5e77d762013-04-16 07:28:30 +00005250 // Eliminate non-overload placeholder types in the arguments. We
5251 // need to do this before checking whether types are dependent
5252 // because lowering a pseudo-object expression might well give us
5253 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005254 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005255 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5256 // FIXME: should we be doing this here?
5257 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5258 if (result.isInvalid()) {
5259 SetFailed(FK_PlaceholderType);
5260 return;
5261 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005262 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005263 }
5264
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005265 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005266 // The semantics of initializers are as follows. The destination type is
5267 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005268 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005269 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005270 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005271 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005272
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005273 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005274 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005275 SequenceKind = DependentSequence;
5276 return;
5277 }
5278
Sebastian Redld201edf2011-06-05 13:59:11 +00005279 // Almost everything is a normal sequence.
5280 setSequenceKind(NormalSequence);
5281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005282 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005283 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005284 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005285 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005286 if (S.getLangOpts().ObjC1) {
5287 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5288 DestType, Initializer->getType(),
5289 Initializer) ||
5290 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5291 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005292 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005293 if (!isa<InitListExpr>(Initializer))
5294 SourceType = Initializer->getType();
5295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005296
Sebastian Redl0501c632012-02-12 16:37:36 +00005297 // - If the initializer is a (non-parenthesized) braced-init-list, the
5298 // object is list-initialized (8.5.4).
5299 if (Kind.getKind() != InitializationKind::IK_Direct) {
5300 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005301 TryListInitialization(S, Entity, Kind, InitList, *this,
5302 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005303 return;
5304 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005307 // - If the destination type is a reference type, see 8.5.3.
5308 if (DestType->isReferenceType()) {
5309 // C++0x [dcl.init.ref]p1:
5310 // A variable declared to be a T& or T&&, that is, "reference to type T"
5311 // (8.3.2), shall be initialized by an object, or function, of type T or
5312 // by an object that can be converted into a T.
5313 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005314 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005315 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005316 // C++17 [dcl.init.ref]p5:
5317 // A reference [...] is initialized by an expression [...] as follows:
5318 // If the initializer is not an expression, presumably we should reject,
5319 // but the standard fails to actually say so.
5320 else if (isa<InitListExpr>(Args[0]))
5321 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005322 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005323 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005324 return;
5325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005326
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005327 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005328 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005329 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005330 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005331 return;
5332 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005333
Douglas Gregor85dabae2009-12-16 01:38:02 +00005334 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005335 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005336 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005337 return;
5338 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005339
John McCall66884dd2011-02-21 07:22:22 +00005340 // - If the destination type is an array of characters, an array of
5341 // char16_t, an array of char32_t, or an array of wchar_t, and the
5342 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005344 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005345 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005346 if (Initializer && isa<VariableArrayType>(DestAT)) {
5347 SetFailed(FK_VariableLengthArrayHasInitializer);
5348 return;
5349 }
5350
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005351 if (Initializer) {
5352 switch (IsStringInit(Initializer, DestAT, Context)) {
5353 case SIF_None:
5354 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5355 return;
5356 case SIF_NarrowStringIntoWideChar:
5357 SetFailed(FK_NarrowStringIntoWideCharArray);
5358 return;
5359 case SIF_WideStringIntoChar:
5360 SetFailed(FK_WideStringIntoCharArray);
5361 return;
5362 case SIF_IncompatWideStringIntoWideChar:
5363 SetFailed(FK_IncompatWideStringIntoWideChar);
5364 return;
5365 case SIF_Other:
5366 break;
5367 }
John McCall66884dd2011-02-21 07:22:22 +00005368 }
5369
Richard Smith410306b2016-12-12 02:53:20 +00005370 // Some kinds of initialization permit an array to be initialized from
5371 // another array of the same type, and perform elementwise initialization.
5372 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5373 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5374 Entity.getType()) &&
5375 canPerformArrayCopy(Entity)) {
5376 // If source is a prvalue, use it directly.
5377 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005378 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005379 return;
5380 }
5381
5382 // Emit element-at-a-time copy loop.
5383 InitializedEntity Element =
5384 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5385 QualType InitEltT =
5386 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005387 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5388 Initializer->getValueKind(),
5389 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005390 Expr *OVEAsExpr = &OVE;
5391 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5392 TreatUnavailableAsInvalid);
5393 if (!Failed())
5394 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5395 return;
5396 }
5397
Douglas Gregore2f943b2011-02-22 18:29:51 +00005398 // Note: as an GNU C extension, we allow initialization of an
5399 // array from a compound literal that creates an array of the same
5400 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005401 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005402 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5403 Initializer->getType()->isArrayType()) {
5404 const ArrayType *SourceAT
5405 = Context.getAsArrayType(Initializer->getType());
5406 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005407 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005408 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005409 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005410 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005411 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005412 }
Richard Smithebeed412012-02-15 22:38:09 +00005413 }
Richard Smithd86812d2012-07-05 08:39:21 +00005414 // Note: as a GNU C++ extension, we allow list-initialization of a
5415 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005416 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005417 Entity.getKind() == InitializedEntity::EK_Member &&
5418 Initializer && isa<InitListExpr>(Initializer)) {
5419 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005420 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005421 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005422 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005423 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005424 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5425 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005426 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005427 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005428
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005429 return;
5430 }
Eli Friedman78275202009-12-19 08:11:05 +00005431
Larisse Voufod2010992015-01-24 23:09:54 +00005432 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005433 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005434 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005435 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005436
5437 // We're at the end of the line for C: it's either a write-back conversion
5438 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005439 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005440 // If allowed, check whether this is an Objective-C writeback conversion.
5441 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005442 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005443 return;
5444 }
Guy Benyei61054192013-02-07 10:55:47 +00005445
5446 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5447 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005448
5449 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5450 return;
5451
Egor Churaev89831422016-12-23 14:55:49 +00005452 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5453 return;
5454
John McCall31168b02011-06-15 23:02:42 +00005455 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005456 AddCAssignmentStep(DestType);
5457 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005458 return;
5459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
David Blaikiebbafb8a2012-03-11 07:00:24 +00005461 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005462
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005463 // - If the destination type is a (possibly cv-qualified) class type:
5464 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005465 // - If the initialization is direct-initialization, or if it is
5466 // copy-initialization where the cv-unqualified version of the
5467 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005468 // class of the destination, constructors are considered. [...]
5469 if (Kind.getKind() == InitializationKind::IK_Direct ||
5470 (Kind.getKind() == InitializationKind::IK_Copy &&
5471 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005472 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005473 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005474 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005476 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005477 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005478 // used) to a derived class thereof are enumerated as described in
5479 // 13.3.1.4, and the best one is chosen through overload resolution
5480 // (13.3).
5481 else
Richard Smith77be48a2014-07-31 06:31:19 +00005482 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005483 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005484 return;
5485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005486
Richard Smith49a6b6e2017-03-24 01:14:25 +00005487 assert(Args.size() >= 1 && "Zero-argument case handled above");
5488
5489 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005490 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005491 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005492 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005493 } else if (isa<InitListExpr>(Args[0])) {
5494 SetFailed(FK_ParenthesizedListInitForScalar);
5495 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005497
5498 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005499 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005500 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005501 // For a conversion to _Atomic(T) from either T or a class type derived
5502 // from T, initialize the T object then convert to _Atomic type.
5503 bool NeedAtomicConversion = false;
5504 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5505 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005506 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5507 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005508 DestType = Atomic->getValueType();
5509 NeedAtomicConversion = true;
5510 }
5511 }
5512
5513 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005514 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005515 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005516 if (!Failed() && NeedAtomicConversion)
5517 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005518 return;
5519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005520
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005521 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005522 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005523 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005525 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005526
John McCall31168b02011-06-15 23:02:42 +00005527 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005528 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005529 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005530 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005531 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005532 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5533 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005534
5535 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005536 ICS.Standard.Second == ICK_Writeback_Conversion) {
5537 // Objective-C ARC writeback conversion.
5538
5539 // We should copy unless we're passing to an argument explicitly
5540 // marked 'out'.
5541 bool ShouldCopy = true;
5542 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5543 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5544
5545 // If there was an lvalue adjustment, add it as a separate conversion.
5546 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5547 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5548 ImplicitConversionSequence LvalueICS;
5549 LvalueICS.setStandard();
5550 LvalueICS.Standard.setAsIdentityConversion();
5551 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5552 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005553 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005554 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005555
Richard Smith77be48a2014-07-31 06:31:19 +00005556 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005557 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005558 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005559 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5560 AddZeroInitializationStep(Entity.getType());
5561 } else if (Initializer->getType() == Context.OverloadTy &&
5562 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5563 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005564 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005565 else if (Initializer->getType()->isFunctionType() &&
5566 isExprAnUnaddressableFunction(S, Initializer))
5567 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005568 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005569 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005570 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005571 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005572
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005573 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005574 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005575}
5576
5577InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005578 for (auto &S : Steps)
5579 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005580}
5581
5582//===----------------------------------------------------------------------===//
5583// Perform initialization
5584//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005585static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005586getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005587 switch(Entity.getKind()) {
5588 case InitializedEntity::EK_Variable:
5589 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005590 case InitializedEntity::EK_Exception:
5591 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005592 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005593 return Sema::AA_Initializing;
5594
5595 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005597 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5598 return Sema::AA_Sending;
5599
Douglas Gregore1314a62009-12-18 05:02:21 +00005600 return Sema::AA_Passing;
5601
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005602 case InitializedEntity::EK_Parameter_CF_Audited:
5603 if (Entity.getDecl() &&
5604 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5605 return Sema::AA_Sending;
5606
5607 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5608
Douglas Gregore1314a62009-12-18 05:02:21 +00005609 case InitializedEntity::EK_Result:
5610 return Sema::AA_Returning;
5611
Douglas Gregore1314a62009-12-18 05:02:21 +00005612 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005613 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005614 // FIXME: Can we tell apart casting vs. converting?
5615 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616
Douglas Gregore1314a62009-12-18 05:02:21 +00005617 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005618 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005619 case InitializedEntity::EK_ArrayElement:
5620 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005621 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005622 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005623 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005624 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005625 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005626 return Sema::AA_Initializing;
5627 }
5628
David Blaikie8a40f702012-01-17 06:56:22 +00005629 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005630}
5631
Richard Smith27874d62013-01-08 00:08:23 +00005632/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005633/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005634static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005635 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005636 case InitializedEntity::EK_ArrayElement:
5637 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005638 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00005639 case InitializedEntity::EK_New:
5640 case InitializedEntity::EK_Variable:
5641 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005642 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005643 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005644 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005645 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005646 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005647 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005648 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005649 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005650 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005651
Douglas Gregore1314a62009-12-18 05:02:21 +00005652 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005653 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005654 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005655 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005656 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005657 return true;
5658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005659
Douglas Gregore1314a62009-12-18 05:02:21 +00005660 llvm_unreachable("missed an InitializedEntity kind?");
5661}
5662
Douglas Gregor95562572010-04-24 23:45:46 +00005663/// \brief Whether the given entity, when initialized with an object
5664/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005665static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005666 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005667 case InitializedEntity::EK_Result:
5668 case InitializedEntity::EK_New:
5669 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005670 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005671 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005672 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005673 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005674 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005675 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005676 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005677
Richard Smith27874d62013-01-08 00:08:23 +00005678 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005679 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005680 case InitializedEntity::EK_Variable:
5681 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005682 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005683 case InitializedEntity::EK_Temporary:
5684 case InitializedEntity::EK_ArrayElement:
5685 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005686 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005687 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005688 return true;
5689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005690
5691 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005692}
5693
Richard Smithc620f552011-10-19 16:55:56 +00005694/// \brief Get the location at which initialization diagnostics should appear.
5695static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5696 Expr *Initializer) {
5697 switch (Entity.getKind()) {
5698 case InitializedEntity::EK_Result:
5699 return Entity.getReturnLoc();
5700
5701 case InitializedEntity::EK_Exception:
5702 return Entity.getThrowLoc();
5703
5704 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005705 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005706 return Entity.getDecl()->getLocation();
5707
Douglas Gregor19666fb2012-02-15 16:57:26 +00005708 case InitializedEntity::EK_LambdaCapture:
5709 return Entity.getCaptureLoc();
5710
Richard Smithc620f552011-10-19 16:55:56 +00005711 case InitializedEntity::EK_ArrayElement:
5712 case InitializedEntity::EK_Member:
5713 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005714 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005715 case InitializedEntity::EK_Temporary:
5716 case InitializedEntity::EK_New:
5717 case InitializedEntity::EK_Base:
5718 case InitializedEntity::EK_Delegating:
5719 case InitializedEntity::EK_VectorElement:
5720 case InitializedEntity::EK_ComplexElement:
5721 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005722 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005723 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005724 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005725 return Initializer->getLocStart();
5726 }
5727 llvm_unreachable("missed an InitializedEntity kind?");
5728}
5729
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005730/// \brief Make a (potentially elidable) temporary copy of the object
5731/// provided by the given initializer by calling the appropriate copy
5732/// constructor.
5733///
5734/// \param S The Sema object used for type-checking.
5735///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005736/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005737/// the type of the initializer expression or a superclass thereof.
5738///
James Dennett634962f2012-06-14 21:40:34 +00005739/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005740///
5741/// \param CurInit The initializer expression.
5742///
5743/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5744/// is permitted in C++03 (but not C++0x) when binding a reference to
5745/// an rvalue.
5746///
5747/// \returns An expression that copies the initializer expression into
5748/// a temporary object, or an error expression if a copy could not be
5749/// created.
John McCalldadc5752010-08-24 06:29:42 +00005750static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005751 QualType T,
5752 const InitializedEntity &Entity,
5753 ExprResult CurInit,
5754 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005755 if (CurInit.isInvalid())
5756 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005757 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005758 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005759 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005760 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005761 Class = cast<CXXRecordDecl>(Record->getDecl());
5762 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005763 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005764
Richard Smithc620f552011-10-19 16:55:56 +00005765 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005766
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005767 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005768 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005769 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005770
Richard Smith7c2bcc92016-09-07 02:14:33 +00005771 // Perform overload resolution using the class's constructors. Per
5772 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005773 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005774 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005775 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005776
Douglas Gregore1314a62009-12-18 05:02:21 +00005777 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005778 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005779 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005780 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5781 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5782 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005783 case OR_Success:
5784 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005785
Douglas Gregore1314a62009-12-18 05:02:21 +00005786 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005787 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5788 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5789 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005790 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005791 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005792 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005793 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005794 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005795 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005796
Douglas Gregore1314a62009-12-18 05:02:21 +00005797 case OR_Ambiguous:
5798 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005799 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005800 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005801 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005802 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005803
Douglas Gregore1314a62009-12-18 05:02:21 +00005804 case OR_Deleted:
5805 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005806 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005807 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005808 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005809 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005810 }
5811
Richard Smith7c2bcc92016-09-07 02:14:33 +00005812 bool HadMultipleCandidates = CandidateSet.size() > 1;
5813
Douglas Gregor5ab11652010-04-17 22:01:05 +00005814 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005815 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005816 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005817
Richard Smith5179eb72016-06-28 19:03:57 +00005818 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5819 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005820
5821 if (IsExtraneousCopy) {
5822 // If this is a totally extraneous copy for C++03 reference
5823 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005824 // expression. We don't generate an (elided) copy operation here
5825 // because doing so would require us to pass down a flag to avoid
5826 // infinite recursion, where each step adds another extraneous,
5827 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005828
Douglas Gregor30b52772010-04-18 07:57:34 +00005829 // Instantiate the default arguments of any extra parameters in
5830 // the selected copy constructor, as if we were going to create a
5831 // proper call to the copy constructor.
5832 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5833 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5834 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005835 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005836 break;
5837
5838 // Build the default argument expression; we don't actually care
5839 // if this succeeds or not, because this routine will complain
5840 // if there was a problem.
5841 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5842 }
5843
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005844 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005846
Douglas Gregor5ab11652010-04-17 22:01:05 +00005847 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005848 // constructor call (we might have derived-to-base conversions, or
5849 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005850 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005851 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005852
Richard Smith7c2bcc92016-09-07 02:14:33 +00005853 // C++0x [class.copy]p32:
5854 // When certain criteria are met, an implementation is allowed to
5855 // omit the copy/move construction of a class object, even if the
5856 // copy/move constructor and/or destructor for the object have
5857 // side effects. [...]
5858 // - when a temporary class object that has not been bound to a
5859 // reference (12.2) would be copied/moved to a class object
5860 // with the same cv-unqualified type, the copy/move operation
5861 // can be omitted by constructing the temporary object
5862 // directly into the target of the omitted copy/move
5863 //
5864 // Note that the other three bullets are handled elsewhere. Copy
5865 // elision for return statements and throw expressions are handled as part
5866 // of constructor initialization, while copy elision for exception handlers
5867 // is handled by the run-time.
5868 //
5869 // FIXME: If the function parameter is not the same type as the temporary, we
5870 // should still be able to elide the copy, but we don't have a way to
5871 // represent in the AST how much should be elided in this case.
5872 bool Elidable =
5873 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5874 S.Context.hasSameUnqualifiedType(
5875 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5876 CurInitExpr->getType());
5877
Douglas Gregord0ace022010-04-25 00:55:24 +00005878 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00005879 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5880 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005881 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005882 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005883 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005884 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005885 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005886 CXXConstructExpr::CK_Complete,
5887 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005888
Douglas Gregord0ace022010-04-25 00:55:24 +00005889 // If we're supposed to bind temporaries, do so.
5890 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005891 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005892 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005893}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005894
Richard Smithc620f552011-10-19 16:55:56 +00005895/// \brief Check whether elidable copy construction for binding a reference to
5896/// a temporary would have succeeded if we were building in C++98 mode, for
5897/// -Wc++98-compat.
5898static void CheckCXX98CompatAccessibleCopy(Sema &S,
5899 const InitializedEntity &Entity,
5900 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005901 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005902
5903 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5904 if (!Record)
5905 return;
5906
5907 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005908 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005909 return;
5910
5911 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005912 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005913 DeclContext::lookup_result Ctors =
5914 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00005915
5916 // Perform overload resolution.
5917 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005918 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005919 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005920 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5921 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5922 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00005923
5924 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5925 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5926 << CurInitExpr->getSourceRange();
5927
5928 switch (OR) {
5929 case OR_Success:
5930 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00005931 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005932 // FIXME: Check default arguments as far as that's possible.
5933 break;
5934
5935 case OR_No_Viable_Function:
5936 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005937 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005938 break;
5939
5940 case OR_Ambiguous:
5941 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005942 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005943 break;
5944
5945 case OR_Deleted:
5946 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005947 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005948 break;
5949 }
5950}
5951
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005952void InitializationSequence::PrintInitLocationNote(Sema &S,
5953 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005954 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005955 if (Entity.getDecl()->getLocation().isInvalid())
5956 return;
5957
5958 if (Entity.getDecl()->getDeclName())
5959 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5960 << Entity.getDecl()->getDeclName();
5961 else
5962 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5963 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005964 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5965 Entity.getMethodDecl())
5966 S.Diag(Entity.getMethodDecl()->getLocation(),
5967 diag::note_method_return_type_change)
5968 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005969}
5970
Jordan Rose6c0505e2013-05-06 16:48:12 +00005971/// Returns true if the parameters describe a constructor initialization of
5972/// an explicit temporary object, e.g. "Point(x, y)".
5973static bool isExplicitTemporary(const InitializedEntity &Entity,
5974 const InitializationKind &Kind,
5975 unsigned NumArgs) {
5976 switch (Entity.getKind()) {
5977 case InitializedEntity::EK_Temporary:
5978 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005979 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005980 break;
5981 default:
5982 return false;
5983 }
5984
5985 switch (Kind.getKind()) {
5986 case InitializationKind::IK_DirectList:
5987 return true;
5988 // FIXME: Hack to work around cast weirdness.
5989 case InitializationKind::IK_Direct:
5990 case InitializationKind::IK_Value:
5991 return NumArgs != 1;
5992 default:
5993 return false;
5994 }
5995}
5996
Sebastian Redled2e5322011-12-22 14:44:04 +00005997static ExprResult
5998PerformConstructorInitialization(Sema &S,
5999 const InitializedEntity &Entity,
6000 const InitializationKind &Kind,
6001 MultiExprArg Args,
6002 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006003 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006004 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006005 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006006 SourceLocation LBraceLoc,
6007 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006008 unsigned NumArgs = Args.size();
6009 CXXConstructorDecl *Constructor
6010 = cast<CXXConstructorDecl>(Step.Function.Function);
6011 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6012
6013 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006014 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006015 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6016 ? Kind.getEqualLoc()
6017 : Kind.getLocation();
6018
6019 if (Kind.getKind() == InitializationKind::IK_Default) {
6020 // Force even a trivial, implicit default constructor to be
6021 // semantically checked. We do this explicitly because we don't build
6022 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006023 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006024 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006025 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006026 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6027 }
6028
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006029 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006030
Douglas Gregor6073dca2012-02-24 23:56:31 +00006031 // C++ [over.match.copy]p1:
6032 // - When initializing a temporary to be bound to the first parameter
6033 // of a constructor that takes a reference to possibly cv-qualified
6034 // T as its first argument, called with a single argument in the
6035 // context of direct-initialization, explicit conversion functions
6036 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006037 bool AllowExplicitConv =
6038 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6039 hasCopyOrMoveCtorParam(S.Context,
6040 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006041
Sebastian Redled2e5322011-12-22 14:44:04 +00006042 // Determine the arguments required to actually perform the constructor
6043 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006044 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006045 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006046 AllowExplicitConv,
6047 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006048 return ExprError();
6049
6050
Jordan Rose6c0505e2013-05-06 16:48:12 +00006051 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006052 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006053 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6054 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006055
6056 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6057 if (!TSInfo)
6058 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumara14a1f92018-01-17 18:53:51 +00006059 SourceRange ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006060
Richard Smith5179eb72016-06-28 19:03:57 +00006061 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006062 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006063 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006064 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6065 return ExprError();
6066 }
Richard Smith5179eb72016-06-28 19:03:57 +00006067 S.MarkFunctionReferenced(Loc, Constructor);
6068
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006069 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00006070 S.Context, Constructor,
6071 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006072 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6073 IsListInitialization, IsStdInitListInitialization,
6074 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006075 } else {
6076 CXXConstructExpr::ConstructionKind ConstructKind =
6077 CXXConstructExpr::CK_Complete;
6078
6079 if (Entity.getKind() == InitializedEntity::EK_Base) {
6080 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6081 CXXConstructExpr::CK_VirtualBase :
6082 CXXConstructExpr::CK_NonVirtualBase;
6083 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6084 ConstructKind = CXXConstructExpr::CK_Delegating;
6085 }
6086
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006087 // Only get the parenthesis or brace range if it is a list initialization or
6088 // direct construction.
6089 SourceRange ParenOrBraceRange;
6090 if (IsListInitialization)
6091 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6092 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006093 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006094
6095 // If the entity allows NRVO, mark the construction as elidable
6096 // unconditionally.
6097 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006098 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006099 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006100 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006101 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006102 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006103 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006104 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006105 ConstructorInitRequiresZeroInit,
6106 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006107 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006108 else
Richard Smith410306b2016-12-12 02:53:20 +00006109 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006110 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006111 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006112 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006113 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006114 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006115 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006116 ConstructorInitRequiresZeroInit,
6117 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006118 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006119 }
6120 if (CurInit.isInvalid())
6121 return ExprError();
6122
6123 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006124 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006125 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6126 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006127
6128 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006129 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006130
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006131 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006132}
6133
Richard Smitheb3cad52012-06-04 22:27:30 +00006134/// Determine whether the specified InitializedEntity definitely has a lifetime
6135/// longer than the current full-expression. Conservatively returns false if
6136/// it's unclear.
6137static bool
6138InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6139 const InitializedEntity *Top = &Entity;
6140 while (Top->getParent())
6141 Top = Top->getParent();
6142
6143 switch (Top->getKind()) {
6144 case InitializedEntity::EK_Variable:
6145 case InitializedEntity::EK_Result:
6146 case InitializedEntity::EK_Exception:
6147 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00006148 case InitializedEntity::EK_Binding:
Richard Smitheb3cad52012-06-04 22:27:30 +00006149 case InitializedEntity::EK_New:
6150 case InitializedEntity::EK_Base:
6151 case InitializedEntity::EK_Delegating:
6152 return true;
6153
6154 case InitializedEntity::EK_ArrayElement:
6155 case InitializedEntity::EK_VectorElement:
6156 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006157 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smitheb3cad52012-06-04 22:27:30 +00006158 case InitializedEntity::EK_ComplexElement:
6159 // Could not determine what the full initialization is. Assume it might not
6160 // outlive the full-expression.
6161 return false;
6162
6163 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006164 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00006165 case InitializedEntity::EK_Temporary:
6166 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006167 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006168 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00006169 // The entity being initialized might not outlive the full-expression.
6170 return false;
6171 }
6172
6173 llvm_unreachable("unknown entity kind");
6174}
6175
Richard Smithe6c01442013-06-05 00:46:14 +00006176/// Determine the declaration which an initialized entity ultimately refers to,
6177/// for the purpose of lifetime-extending a temporary bound to a reference in
6178/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00006179static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
6180 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00006181 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006182 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006183 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006184 case InitializedEntity::EK_Variable:
6185 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00006186 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006187
6188 case InitializedEntity::EK_Member:
6189 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006190 if (Entity->getParent())
6191 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6192 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006193
6194 // except:
6195 // -- A temporary bound to a reference member in a constructor's
6196 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00006197 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006198
Richard Smith7873de02016-08-11 22:25:46 +00006199 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006200 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6201 // type.
6202 return Entity;
Richard Smith7873de02016-08-11 22:25:46 +00006203
Richard Smithe6c01442013-06-05 00:46:14 +00006204 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006205 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006206 // -- A temporary bound to a reference parameter in a function call
6207 // persists until the completion of the full-expression containing
6208 // the call.
6209 case InitializedEntity::EK_Result:
6210 // -- The lifetime of a temporary bound to the returned value in a
6211 // function return statement is not extended; the temporary is
6212 // destroyed at the end of the full-expression in the return statement.
6213 case InitializedEntity::EK_New:
6214 // -- A temporary bound to a reference in a new-initializer persists
6215 // until the completion of the full-expression containing the
6216 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006217 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006218
6219 case InitializedEntity::EK_Temporary:
6220 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006221 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006222 // We don't yet know the storage duration of the surrounding temporary.
6223 // Assume it's got full-expression duration for now, it will patch up our
6224 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00006225 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006226
6227 case InitializedEntity::EK_ArrayElement:
6228 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006229 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6230 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00006231
6232 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006233 // For subobjects, we look at the complete object.
6234 if (Entity->getParent())
6235 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6236 Entity);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006237 LLVM_FALLTHROUGH;
Richard Smithe6c01442013-06-05 00:46:14 +00006238 case InitializedEntity::EK_Delegating:
6239 // We can reach this case for aggregate initialization in a constructor:
6240 // struct A { int &&r; };
6241 // struct B : A { B() : A{0} {} };
6242 // In this case, use the innermost field decl as the context.
6243 return FallbackDecl;
6244
6245 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006246 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006247 case InitializedEntity::EK_LambdaCapture:
6248 case InitializedEntity::EK_Exception:
6249 case InitializedEntity::EK_VectorElement:
6250 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00006251 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006252 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006253 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006254}
6255
David Majnemerdaff3702014-05-01 17:50:17 +00006256static void performLifetimeExtension(Expr *Init,
6257 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006258
6259/// Update a glvalue expression that is used as the initializer of a reference
6260/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006261/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00006262static bool
6263performReferenceExtension(Expr *Init,
6264 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006265 // Walk past any constructs which we can lifetime-extend across.
6266 Expr *Old;
6267 do {
6268 Old = Init;
6269
Richard Smithdbc82492015-01-10 01:28:13 +00006270 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6271 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
6272 // This is just redundant braces around an initializer. Step over it.
6273 Init = ILE->getInit(0);
6274 }
6275 }
6276
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006277 // Step over any subobject adjustments; we may have a materialized
6278 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006279 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006280
6281 // Per current approach for DR1376, look through casts to reference type
6282 // when performing lifetime extension.
6283 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6284 if (CE->getSubExpr()->isGLValue())
6285 Init = CE->getSubExpr();
6286
Richard Smithb3189a12016-12-05 07:49:14 +00006287 // Per the current approach for DR1299, look through array element access
6288 // when performing lifetime extension.
6289 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6290 Init = ASE->getBase();
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006291 } while (Init != Old);
6292
Richard Smithe6c01442013-06-05 00:46:14 +00006293 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6294 // Update the storage duration of the materialized temporary.
6295 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00006296 ME->setExtendingDecl(ExtendingEntity->getDecl(),
6297 ExtendingEntity->allocateManglingNumber());
6298 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006299 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00006300 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006301
6302 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00006303}
6304
6305/// Update a prvalue expression that is going to be materialized as a
6306/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00006307static void performLifetimeExtension(Expr *Init,
6308 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00006309 // Dig out the expression which constructs the extended temporary.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006310 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smithe6c01442013-06-05 00:46:14 +00006311
Richard Smith736a9472013-06-12 20:42:33 +00006312 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6313 Init = BTE->getSubExpr();
6314
Richard Smithcc1b96d2013-06-12 22:31:48 +00006315 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006316 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00006317 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006318 return;
6319 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006320
Richard Smithe6c01442013-06-05 00:46:14 +00006321 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006322 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006323 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00006324 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006325 return;
6326 }
6327
Richard Smithcc1b96d2013-06-12 22:31:48 +00006328 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006329 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6330
6331 // If we lifetime-extend a braced initializer which is initializing an
6332 // aggregate, and that aggregate contains reference members which are
6333 // bound to temporaries, those temporaries are also lifetime-extended.
6334 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6335 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006336 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006337 else {
6338 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006339 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006340 if (Index >= ILE->getNumInits())
6341 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006342 if (I->isUnnamedBitfield())
6343 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006344 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006345 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006346 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00006347 else if (isa<InitListExpr>(SubInit) ||
6348 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00006349 // This may be either aggregate-initialization of a member or
6350 // initialization of a std::initializer_list object. Either way,
6351 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006352 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006353 ++Index;
6354 }
6355 }
6356 }
6357 }
6358}
6359
Richard Smithcc1b96d2013-06-12 22:31:48 +00006360static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6361 const Expr *Init, bool IsInitializerList,
6362 const ValueDecl *ExtendingDecl) {
6363 // Warn if a field lifetime-extends a temporary.
6364 if (isa<FieldDecl>(ExtendingDecl)) {
6365 if (IsInitializerList) {
6366 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6367 << /*at end of constructor*/true;
6368 return;
6369 }
6370
6371 bool IsSubobjectMember = false;
6372 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6373 Ent = Ent->getParent()) {
6374 if (Ent->getKind() != InitializedEntity::EK_Base) {
6375 IsSubobjectMember = true;
6376 break;
6377 }
6378 }
6379 S.Diag(Init->getExprLoc(),
6380 diag::warn_bind_ref_member_to_temporary)
6381 << ExtendingDecl << Init->getSourceRange()
6382 << IsSubobjectMember << IsInitializerList;
6383 if (IsSubobjectMember)
6384 S.Diag(ExtendingDecl->getLocation(),
6385 diag::note_ref_subobject_of_member_declared_here);
6386 else
6387 S.Diag(ExtendingDecl->getLocation(),
6388 diag::note_ref_or_ptr_member_declared_here)
6389 << /*is pointer*/false;
6390 }
6391}
6392
Richard Smithaaa0ec42013-09-21 21:19:19 +00006393static void DiagnoseNarrowingInInitList(Sema &S,
6394 const ImplicitConversionSequence &ICS,
6395 QualType PreNarrowingType,
6396 QualType EntityType,
6397 const Expr *PostInit);
6398
Richard Trieuac3eca52015-04-29 01:52:17 +00006399/// Provide warnings when std::move is used on construction.
6400static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6401 bool IsReturnStmt) {
6402 if (!InitExpr)
6403 return;
6404
Richard Smith51ec0cf2017-02-21 01:17:38 +00006405 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00006406 return;
6407
Richard Trieuac3eca52015-04-29 01:52:17 +00006408 QualType DestType = InitExpr->getType();
6409 if (!DestType->isRecordType())
6410 return;
6411
6412 unsigned DiagID = 0;
6413 if (IsReturnStmt) {
6414 const CXXConstructExpr *CCE =
6415 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6416 if (!CCE || CCE->getNumArgs() != 1)
6417 return;
6418
6419 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6420 return;
6421
6422 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00006423 }
6424
6425 // Find the std::move call and get the argument.
6426 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6427 if (!CE || CE->getNumArgs() != 1)
6428 return;
6429
6430 const FunctionDecl *MoveFunction = CE->getDirectCallee();
6431 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6432 !MoveFunction->getIdentifier() ||
6433 !MoveFunction->getIdentifier()->isStr("move"))
6434 return;
6435
6436 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6437
6438 if (IsReturnStmt) {
6439 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6440 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6441 return;
6442
6443 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6444 if (!VD || !VD->hasLocalStorage())
6445 return;
6446
Alex Lorenzbbe51d82017-11-07 21:40:11 +00006447 // __block variables are not moved implicitly.
6448 if (VD->hasAttr<BlocksAttr>())
6449 return;
6450
Richard Trieu8d4006a2015-07-28 19:06:16 +00006451 QualType SourceType = VD->getType();
6452 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00006453 return;
6454
Richard Trieu8d4006a2015-07-28 19:06:16 +00006455 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00006456 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00006457 }
6458
Davide Italiano7842c3f2015-07-18 01:15:19 +00006459 // If we're returning a function parameter, copy elision
6460 // is not possible.
6461 if (isa<ParmVarDecl>(VD))
6462 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00006463 else
6464 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00006465 } else {
6466 DiagID = diag::warn_pessimizing_move_on_initialization;
6467 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6468 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6469 return;
6470 }
6471
6472 S.Diag(CE->getLocStart(), DiagID);
6473
6474 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6475 // is within a macro.
6476 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6477 if (CallBegin.isMacroID())
6478 return;
6479 SourceLocation RParen = CE->getRParenLoc();
6480 if (RParen.isMacroID())
6481 return;
6482 SourceLocation LParen;
6483 SourceLocation ArgLoc = Arg->getLocStart();
6484
6485 // Special testing for the argument location. Since the fix-it needs the
6486 // location right before the argument, the argument location can be in a
6487 // macro only if it is at the beginning of the macro.
6488 while (ArgLoc.isMacroID() &&
6489 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
6490 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6491 }
6492
6493 if (LParen.isMacroID())
6494 return;
6495
6496 LParen = ArgLoc.getLocWithOffset(-1);
6497
6498 S.Diag(CE->getLocStart(), diag::note_remove_move)
6499 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6500 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6501}
6502
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006503static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6504 // Check to see if we are dereferencing a null pointer. If so, this is
6505 // undefined behavior, so warn about it. This only handles the pattern
6506 // "*null", which is a very syntactic check.
6507 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6508 if (UO->getOpcode() == UO_Deref &&
6509 UO->getSubExpr()->IgnoreParenCasts()->
6510 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6511 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6512 S.PDiag(diag::warn_binding_null_to_reference)
6513 << UO->getSubExpr()->getSourceRange());
6514 }
6515}
6516
Tim Shen4a05bb82016-06-21 20:29:17 +00006517MaterializeTemporaryExpr *
6518Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6519 bool BoundToLvalueReference) {
6520 auto MTE = new (Context)
6521 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6522
6523 // Order an ExprWithCleanups for lifetime marks.
6524 //
6525 // TODO: It'll be good to have a single place to check the access of the
6526 // destructor and generate ExprWithCleanups for various uses. Currently these
6527 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6528 // but there may be a chance to merge them.
6529 Cleanup.setExprNeedsCleanups(false);
6530 return MTE;
6531}
6532
Richard Smith4baaa5a2016-12-03 01:14:32 +00006533ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6534 // In C++98, we don't want to implicitly create an xvalue.
6535 // FIXME: This means that AST consumers need to deal with "prvalues" that
6536 // denote materialized temporaries. Maybe we should add another ValueKind
6537 // for "xvalue pretending to be a prvalue" for C++98 support.
6538 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6539 return E;
6540
6541 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00006542 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6543 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006544 QualType T = E->getType();
6545 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6546 return ExprError();
6547
6548 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6549}
6550
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006551ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006552InitializationSequence::Perform(Sema &S,
6553 const InitializedEntity &Entity,
6554 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00006555 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006556 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006557 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006558 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00006559 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006560 }
Nico Weber337d5aa2015-04-17 08:32:38 +00006561 if (!ZeroInitializationFixit.empty()) {
6562 unsigned DiagID = diag::err_default_init_const;
6563 if (Decl *D = Entity.getDecl())
6564 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6565 DiagID = diag::ext_default_init_const;
6566
6567 // The initialization would have succeeded with this fixit. Since the fixit
6568 // is on the error, we need to build a valid AST in this case, so this isn't
6569 // handled in the Failed() branch above.
6570 QualType DestType = Entity.getType();
6571 S.Diag(Kind.getLocation(), DiagID)
6572 << DestType << (bool)DestType->getAs<RecordType>()
6573 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6574 ZeroInitializationFixit);
6575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006576
Sebastian Redld201edf2011-06-05 13:59:11 +00006577 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006578 // If the declaration is a non-dependent, incomplete array type
6579 // that has an initializer, then its type will be completed once
6580 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00006581 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00006582 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006583 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006584 if (const IncompleteArrayType *ArrayT
6585 = S.Context.getAsIncompleteArrayType(DeclType)) {
6586 // FIXME: We don't currently have the ability to accurately
6587 // compute the length of an initializer list without
6588 // performing full type-checking of the initializer list
6589 // (since we have to determine where braces are implicitly
6590 // introduced and such). So, we fall back to making the array
6591 // type a dependently-sized array type with no specified
6592 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006593 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006594 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00006595
Douglas Gregor51e77d52009-12-10 17:56:55 +00006596 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00006597 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006598 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6599 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00006600 if (IncompleteArrayTypeLoc ArrayLoc =
6601 TL.getAs<IncompleteArrayTypeLoc>())
6602 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00006603 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00006604 }
6605
6606 *ResultType
6607 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006608 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006609 ArrayT->getSizeModifier(),
6610 ArrayT->getIndexTypeCVRQualifiers(),
6611 Brackets);
6612 }
6613
6614 }
6615 }
Sebastian Redla9351792012-02-11 23:51:47 +00006616 if (Kind.getKind() == InitializationKind::IK_Direct &&
6617 !Kind.isExplicitCast()) {
6618 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00006619 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00006620 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006621 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00006622 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00006623 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00006624 Kind.isExplicitCast() ||
6625 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006626 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006627 }
6628
Sebastian Redld201edf2011-06-05 13:59:11 +00006629 // No steps means no initialization.
6630 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006631 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006632
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006633 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006634 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006635 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00006636 // Produce a C++98 compatibility warning if we are initializing a reference
6637 // from an initializer list. For parameters, we produce a better warning
6638 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006639 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00006640 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6641 << Init->getSourceRange();
6642 }
6643
Egor Churaev3bccec52017-04-05 12:47:10 +00006644 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6645 QualType ETy = Entity.getType();
6646 Qualifiers TyQualifiers = ETy.getQualifiers();
6647 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6648 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6649
6650 if (S.getLangOpts().OpenCLVersion >= 200 &&
6651 ETy->isAtomicType() && !HasGlobalAS &&
6652 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6653 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6654 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6655 return ExprError();
6656 }
6657
Richard Smitheb3cad52012-06-04 22:27:30 +00006658 // Diagnose cases where we initialize a pointer to an array temporary, and the
6659 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006660 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00006661 Entity.getType()->isPointerType() &&
6662 InitializedEntityOutlivesFullExpression(Entity)) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00006663 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6664 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6665 Init = MTE->GetTemporaryExpr();
Richard Smitheb3cad52012-06-04 22:27:30 +00006666 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6667 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6668 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6669 << Init->getSourceRange();
6670 }
6671
Douglas Gregor1b303932009-12-22 15:35:07 +00006672 QualType DestType = Entity.getType().getNonReferenceType();
6673 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00006674 // the same as Entity.getDecl()->getType() in cases involving type merging,
6675 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00006676 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00006677 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00006678 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006679
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006680 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00006681 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006682
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00006684 // grab the only argument out the Args and place it into the "current"
6685 // initializer.
6686 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006687 case SK_ResolveAddressOfOverloadedFunction:
6688 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006689 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006690 case SK_CastDerivedToBaseLValue:
6691 case SK_BindReference:
6692 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00006693 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006694 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00006695 case SK_UserConversion:
6696 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006697 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006698 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00006699 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00006700 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006701 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00006702 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00006703 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00006704 case SK_UnwrapInitList:
6705 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00006706 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00006707 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00006708 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00006709 case SK_ArrayLoopIndex:
6710 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00006711 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00006712 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00006713 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00006714 case SK_PassByIndirectCopyRestore:
6715 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00006716 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006717 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00006718 case SK_OCLSamplerInit:
Egor Churaev89831422016-12-23 14:55:49 +00006719 case SK_OCLZeroEvent:
6720 case SK_OCLZeroQueue: {
Douglas Gregore1314a62009-12-18 05:02:21 +00006721 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006722 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00006723 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006724 break;
John McCall34376a62010-12-04 03:47:34 +00006725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726
Douglas Gregore1314a62009-12-18 05:02:21 +00006727 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00006728 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006729 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00006730 case SK_ZeroInitialization:
6731 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006733
Richard Smithd6a15082017-01-07 00:48:55 +00006734 // Promote from an unevaluated context to an unevaluated list context in
6735 // C++11 list-initialization; we need to instantiate entities usable in
6736 // constant expressions here in order to perform narrowing checks =(
6737 EnterExpressionEvaluationContext Evaluated(
6738 S, EnterExpressionEvaluationContext::InitList,
6739 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6740
Richard Smith81f5ade2016-12-15 02:28:18 +00006741 // C++ [class.abstract]p2:
6742 // no objects of an abstract class can be created except as subobjects
6743 // of a class derived from it
6744 auto checkAbstractType = [&](QualType T) -> bool {
6745 if (Entity.getKind() == InitializedEntity::EK_Base ||
6746 Entity.getKind() == InitializedEntity::EK_Delegating)
6747 return false;
6748 return S.RequireNonAbstractType(Kind.getLocation(), T,
6749 diag::err_allocation_of_abstract_type);
6750 };
6751
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006753 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006754 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006755 for (step_iterator Step = step_begin(), StepEnd = step_end();
6756 Step != StepEnd; ++Step) {
6757 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006758 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006759
John Wiegley01296292011-04-08 18:41:53 +00006760 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006761
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006762 switch (Step->Kind) {
6763 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006764 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006765 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00006766 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00006767 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6768 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006769 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00006770 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00006771 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006772 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006773
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006774 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006775 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006776 case SK_CastDerivedToBaseLValue: {
6777 // We have a derived-to-base cast that produces either an rvalue or an
6778 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006779
John McCallcf142162010-08-07 06:22:56 +00006780 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00006781
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006782 // Casts to inaccessible base classes are allowed with C-style casts.
6783 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6784 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00006785 CurInit.get()->getLocStart(),
6786 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00006787 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00006788 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006789
John McCall2536c6d2010-08-25 10:28:54 +00006790 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006791 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006792 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006793 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006794 VK_XValue :
6795 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006796 CurInit =
6797 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6798 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006799 break;
6800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006801
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006802 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006803 // Reference binding does not have any corresponding ASTs.
6804
6805 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006806 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006807 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006808
George Burgess IVcfd48d92017-04-13 23:47:08 +00006809 // We don't check for e.g. function pointers here, since address
6810 // availability checks should only occur when the function first decays
6811 // into a pointer or reference.
6812 if (CurInit.get()->getType()->isFunctionProtoType()) {
6813 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
6814 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6815 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
6816 DRE->getLocStart()))
6817 return ExprError();
6818 }
6819 }
6820 }
6821
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006822 // Even though we didn't materialize a temporary, the binding may still
6823 // extend the lifetime of a temporary. This happens if we bind a reference
6824 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00006825 if (const InitializedEntity *ExtendingEntity =
6826 getEntityForTemporaryLifetimeExtension(&Entity))
6827 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6828 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6829 /*IsInitializerList=*/false,
6830 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006831
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006832 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006833 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006834
Richard Smithe6c01442013-06-05 00:46:14 +00006835 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00006836 // Make sure the "temporary" is actually an rvalue.
6837 assert(CurInit.get()->isRValue() && "not a temporary");
6838
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006839 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006840 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006841 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006842
Douglas Gregorfe314812011-06-21 17:03:29 +00006843 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00006844 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00006845 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
David Majnemerdaff3702014-05-01 17:50:17 +00006846
6847 // Maybe lifetime-extend the temporary's subobjects to match the
6848 // entity's lifetime.
6849 if (const InitializedEntity *ExtendingEntity =
6850 getEntityForTemporaryLifetimeExtension(&Entity))
6851 if (performReferenceExtension(MTE, ExtendingEntity))
Richard Smithb8c0f552016-12-09 18:49:13 +00006852 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6853 /*IsInitializerList=*/false,
David Majnemerdaff3702014-05-01 17:50:17 +00006854 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006855
Brian Kelley762f9282017-03-29 18:16:38 +00006856 // If we're extending this temporary to automatic storage duration -- we
6857 // need to register its cleanup during the full-expression's cleanups.
6858 if (MTE->getStorageDuration() == SD_Automatic &&
6859 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00006860 S.Cleanup.setExprNeedsCleanups(true);
Richard Smith736a9472013-06-12 20:42:33 +00006861
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006862 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006863 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006865
Richard Smithb8c0f552016-12-09 18:49:13 +00006866 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00006867 if (checkAbstractType(Step->Type))
6868 return ExprError();
6869
Richard Smithb8c0f552016-12-09 18:49:13 +00006870 // If the overall initialization is initializing a temporary, we already
6871 // bound our argument if it was necessary to do so. If not (if we're
6872 // ultimately initializing a non-temporary), our argument needs to be
6873 // bound since it's initializing a function parameter.
6874 // FIXME: This is a mess. Rationalize temporary destruction.
6875 if (!shouldBindAsTemporary(Entity))
6876 CurInit = S.MaybeBindToTemporary(CurInit.get());
6877 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6878 /*IsExtraneousCopy=*/false);
6879 break;
6880
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006881 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006882 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006883 /*IsExtraneousCopy=*/true);
6884 break;
6885
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006886 case SK_UserConversion: {
6887 // We have a user-defined conversion that invokes either a constructor
6888 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006889 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00006890 FunctionDecl *Fn = Step->Function.Function;
6891 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006892 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006893 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006894 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006895 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006896 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006897 SourceLocation Loc = CurInit.get()->getLocStart();
John McCall760af172010-02-01 03:16:54 +00006898
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006899 // Determine the arguments required to actually perform the constructor
6900 // call.
John Wiegley01296292011-04-08 18:41:53 +00006901 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006902 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006903 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006904 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006905 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006906
Richard Smithb24f0672012-02-11 19:22:50 +00006907 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00006908 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6909 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006910 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006911 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006912 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006913 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006914 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006915 CXXConstructExpr::CK_Complete,
6916 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006917 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006918 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006919
Richard Smith5179eb72016-06-28 19:03:57 +00006920 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6921 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006922 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6923 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924
John McCalle3027922010-08-25 11:45:40 +00006925 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00006926 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006927 } else {
6928 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006929 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006930 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006931 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006932 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6933 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006934
6935 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006936 // derived-to-base conversion? I believe the answer is "no", because
6937 // we don't want to turn off access control here for c-style casts.
Richard Smithb8c0f552016-12-09 18:49:13 +00006938 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
6939 /*Qualifier=*/nullptr,
6940 FoundFn, Conversion);
6941 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006942 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006944 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006945 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6946 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00006947 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006948 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949
John McCalle3027922010-08-25 11:45:40 +00006950 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00006951 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006953
Richard Smith81f5ade2016-12-15 02:28:18 +00006954 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
6955 return ExprError();
6956
Richard Smithb8c0f552016-12-09 18:49:13 +00006957 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6958 CastKind, CurInit.get(), nullptr,
6959 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006960
Richard Smithb8c0f552016-12-09 18:49:13 +00006961 if (shouldBindAsTemporary(Entity))
6962 // The overall entity is temporary, so this expression should be
6963 // destroyed at the end of its full-expression.
6964 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6965 else if (CreatedObject && shouldDestroyEntity(Entity)) {
6966 // The object outlasts the full-expression, but we need to prepare for
6967 // a destructor being run on it.
6968 // FIXME: It makes no sense to do this here. This should happen
6969 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00006970 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006971 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006972 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006973 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006974 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006975 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006976 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006977 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6978 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006979 }
6980 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006981 break;
6982 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006983
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006984 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006985 case SK_QualificationConversionXValue:
6986 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006987 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006988 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006989 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006990 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006991 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006992 VK_XValue :
6993 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006994 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006995 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006996 }
6997
Richard Smith77be48a2014-07-31 06:31:19 +00006998 case SK_AtomicConversion: {
6999 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7000 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7001 CK_NonAtomicToAtomic, VK_RValue);
7002 break;
7003 }
7004
Jordan Roseb1312a52013-04-11 00:58:58 +00007005 case SK_LValueToRValue: {
7006 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007007 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7008 CK_LValueToRValue, CurInit.get(),
7009 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00007010 break;
7011 }
7012
Richard Smithaaa0ec42013-09-21 21:19:19 +00007013 case SK_ConversionSequence:
7014 case SK_ConversionSequenceNoNarrowing: {
7015 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007016 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7017 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007018 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007019 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007020 ExprResult CurInitExprRes =
7021 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007022 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007023 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007024 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007025
7026 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7027
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007028 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007029
7030 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007031 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007032 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7033 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007034
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007035 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037
Douglas Gregor51e77d52009-12-10 17:56:55 +00007038 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007039 if (checkAbstractType(Step->Type))
7040 return ExprError();
7041
John Wiegley01296292011-04-08 18:41:53 +00007042 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007043 // If we're not initializing the top-level entity, we need to create an
7044 // InitializeTemporary entity for our target type.
7045 QualType Ty = Step->Type;
7046 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007047 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007048 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7049 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007050 InitList, Ty, /*VerifyOnly=*/false,
7051 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007052 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007053 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007054
Richard Smithcc1b96d2013-06-12 22:31:48 +00007055 // Hack: We must update *ResultType if available in order to set the
7056 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7057 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7058 if (ResultType &&
7059 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007060 if ((*ResultType)->isRValueReferenceType())
7061 Ty = S.Context.getRValueReferenceType(Ty);
7062 else if ((*ResultType)->isLValueReferenceType())
7063 Ty = S.Context.getLValueReferenceType(Ty,
7064 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7065 *ResultType = Ty;
7066 }
7067
7068 InitListExpr *StructuredInitList =
7069 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007070 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007071 CurInit = shouldBindAsTemporary(InitEntity)
7072 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007073 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007074 break;
7075 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007076
Richard Smith53324112014-07-16 21:33:43 +00007077 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007078 if (checkAbstractType(Step->Type))
7079 return ExprError();
7080
Sebastian Redl5a41f682012-02-12 16:37:24 +00007081 // When an initializer list is passed for a parameter of type "reference
7082 // to object", we don't get an EK_Temporary entity, but instead an
7083 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007084 // FIXME: This is a hack. What we really should do is create a user
7085 // conversion step for this case, but this makes it considerably more
7086 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007087 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7088 Entity.getType().getNonReferenceType());
7089 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007090 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007091 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007092 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7093 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007094 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007095 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7096 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007097 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007098 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007099 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007100 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007101 InitList->getLBraceLoc(),
7102 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007103 break;
7104 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007105
Sebastian Redl29526f02011-11-27 16:50:07 +00007106 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007107 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007108 break;
7109
7110 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007111 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007112 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7113 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007114 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007115 ILE->setSyntacticForm(Syntactic);
7116 ILE->setType(E->getType());
7117 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007118 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007119 break;
7120 }
7121
Richard Smith53324112014-07-16 21:33:43 +00007122 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007123 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007124 if (checkAbstractType(Step->Type))
7125 return ExprError();
7126
Sebastian Redl99f66162012-02-19 12:27:56 +00007127 // When an initializer list is passed for a parameter of type "reference
7128 // to object", we don't get an EK_Temporary entity, but instead an
7129 // EK_Parameter entity with reference type.
7130 // FIXME: This is a hack. What we really should do is create a user
7131 // conversion step for this case, but this makes it considerably more
7132 // complicated. For now, this will do.
7133 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7134 Entity.getType().getNonReferenceType());
7135 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00007136 bool IsStdInitListInit =
7137 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00007138 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00007139 SourceRange Range = Kind.hasParenOrBraceRange()
7140 ? Kind.getParenOrBraceRange()
7141 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00007142 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00007143 S, UseTemporary ? TempEntity : Entity, Kind,
7144 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00007145 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00007146 /*IsListInitialization*/ IsStdInitListInit,
7147 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00007148 /*LBraceLoc*/ Range.getBegin(),
7149 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007150 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00007151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007152
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007153 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007154 step_iterator NextStep = Step;
7155 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007156 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007157 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007158 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007159 // The need for zero-initialization is recorded directly into
7160 // the call to the object's constructor within the next step.
7161 ConstructorInitRequiresZeroInit = true;
7162 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007163 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007164 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007165 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7166 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007167 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007168 Kind.getRange().getBegin());
7169
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007170 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007171 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007172 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007173 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007174 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007175 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007176 break;
7177 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007178
7179 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007180 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007181 // Save off the initial CurInit in case we need to emit a diagnostic
7182 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007183 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007184 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007185 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7186 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007187 if (Result.isInvalid())
7188 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007189 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007190
7191 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007192 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007193 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007194 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007195 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007196 == Sema::Compatible)
7197 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007198 if (CurInitExprRes.isInvalid())
7199 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007200 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007201
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007202 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007203 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7204 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007205 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007206 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007207 &Complained)) {
7208 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007209 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007210 } else if (Complained)
7211 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007212 break;
7213 }
Eli Friedman78275202009-12-19 08:11:05 +00007214
7215 case SK_StringInit: {
7216 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007217 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007218 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007219 break;
7220 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007221
7222 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007223 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007224 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007225 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007226 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007227
Richard Smith410306b2016-12-12 02:53:20 +00007228 case SK_ArrayLoopIndex: {
7229 Expr *Cur = CurInit.get();
7230 Expr *BaseExpr = new (S.Context)
7231 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7232 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7233 Expr *IndexExpr =
7234 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7235 CurInit = S.CreateBuiltinArraySubscriptExpr(
7236 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7237 ArrayLoopCommonExprs.push_back(BaseExpr);
7238 break;
7239 }
7240
7241 case SK_ArrayLoopInit: {
7242 assert(!ArrayLoopCommonExprs.empty() &&
7243 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7244 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7245 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7246 CurInit.get());
7247 break;
7248 }
7249
Richard Smith378b8c82016-12-14 03:22:16 +00007250 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007251 // Okay: we checked everything before creating this step. Note that
7252 // this is a GNU extension.
7253 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007254 << Step->Type << CurInit.get()->getType()
7255 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007256 LLVM_FALLTHROUGH;
7257 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007258 // If the destination type is an incomplete array type, update the
7259 // type accordingly.
7260 if (ResultType) {
7261 if (const IncompleteArrayType *IncompleteDest
7262 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7263 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007264 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007265 *ResultType = S.Context.getConstantArrayType(
7266 IncompleteDest->getElementType(),
7267 ConstantSource->getSize(),
7268 ArrayType::Normal, 0);
7269 }
7270 }
7271 }
John McCall31168b02011-06-15 23:02:42 +00007272 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007273
Richard Smithebeed412012-02-15 22:38:09 +00007274 case SK_ParenthesizedArrayInit:
7275 // Okay: we checked everything before creating this step. Note that
7276 // this is a GNU extension.
7277 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7278 << CurInit.get()->getSourceRange();
7279 break;
7280
John McCall31168b02011-06-15 23:02:42 +00007281 case SK_PassByIndirectCopyRestore:
7282 case SK_PassByIndirectRestore:
7283 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007284 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7285 CurInit.get(), Step->Type,
7286 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007287 break;
7288
7289 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007290 CurInit =
7291 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7292 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007293 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007294
7295 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007296 S.Diag(CurInit.get()->getExprLoc(),
7297 diag::warn_cxx98_compat_initializer_list_init)
7298 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007299
Richard Smithcc1b96d2013-06-12 22:31:48 +00007300 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007301 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7302 CurInit.get()->getType(), CurInit.get(),
7303 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007304
7305 // Maybe lifetime-extend the array temporary's subobjects to match the
7306 // entity's lifetime.
7307 if (const InitializedEntity *ExtendingEntity =
7308 getEntityForTemporaryLifetimeExtension(&Entity))
7309 if (performReferenceExtension(MTE, ExtendingEntity))
7310 warnOnLifetimeExtension(S, Entity, CurInit.get(),
7311 /*IsInitializerList=*/true,
7312 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007313
7314 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007315 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007316
7317 // Bind the result, in case the library has given initializer_list a
7318 // non-trivial destructor.
7319 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007320 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007321 break;
7322 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007323
Guy Benyei61054192013-02-07 10:55:47 +00007324 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007325 // Sampler initialzation have 5 cases:
7326 // 1. function argument passing
7327 // 1a. argument is a file-scope variable
7328 // 1b. argument is a function-scope variable
7329 // 1c. argument is one of caller function's parameters
7330 // 2. variable initialization
7331 // 2a. initializing a file-scope variable
7332 // 2b. initializing a function-scope variable
7333 //
7334 // For file-scope variables, since they cannot be initialized by function
7335 // call of __translate_sampler_initializer in LLVM IR, their references
7336 // need to be replaced by a cast from their literal initializers to
7337 // sampler type. Since sampler variables can only be used in function
7338 // calls as arguments, we only need to replace them when handling the
7339 // argument passing.
7340 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007341 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007342 Expr *Init = CurInit.get();
7343 QualType SourceType = Init->getType();
7344 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007345 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00007346 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00007347 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7348 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007349 break;
7350 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7351 auto Var = cast<VarDecl>(DRE->getDecl());
7352 // Case 1b and 1c
7353 // No cast from integer to sampler is needed.
7354 if (!Var->hasGlobalStorage()) {
7355 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7356 CK_LValueToRValue, Init,
7357 /*BasePath=*/nullptr, VK_RValue);
7358 break;
7359 }
7360 // Case 1a
7361 // For function call with a file-scope sampler variable as argument,
7362 // get the integer literal.
7363 // Do not diagnose if the file-scope variable does not have initializer
7364 // since this has already been diagnosed when parsing the variable
7365 // declaration.
7366 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7367 break;
7368 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7369 Var->getInit()))->getSubExpr();
7370 SourceType = Init->getType();
7371 }
7372 } else {
7373 // Case 2
7374 // Check initializer is 32 bit integer constant.
7375 // If the initializer is taken from global variable, do not diagnose since
7376 // this has already been done when parsing the variable declaration.
7377 if (!Init->isConstantInitializer(S.Context, false))
7378 break;
7379
7380 if (!SourceType->isIntegerType() ||
7381 32 != S.Context.getIntWidth(SourceType)) {
7382 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7383 << SourceType;
7384 break;
7385 }
7386
7387 llvm::APSInt Result;
7388 Init->EvaluateAsInt(Result, S.Context);
7389 const uint64_t SamplerValue = Result.getLimitedValue();
7390 // 32-bit value of sampler's initializer is interpreted as
7391 // bit-field with the following structure:
7392 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7393 // |31 6|5 4|3 1| 0|
7394 // This structure corresponds to enum values of sampler properties
7395 // defined in SPIR spec v1.2 and also opencl-c.h
7396 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7397 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7398 if (FilterMode != 1 && FilterMode != 2)
7399 S.Diag(Kind.getLocation(),
7400 diag::warn_sampler_initializer_invalid_bits)
7401 << "Filter Mode";
7402 if (AddressingMode > 4)
7403 S.Diag(Kind.getLocation(),
7404 diag::warn_sampler_initializer_invalid_bits)
7405 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00007406 }
7407
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007408 // Cases 1a, 2a and 2b
7409 // Insert cast from integer to sampler.
7410 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7411 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00007412 break;
7413 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007414 case SK_OCLZeroEvent: {
7415 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007416 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007417
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007418 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007419 CK_ZeroToOCLEvent,
7420 CurInit.get()->getValueKind());
7421 break;
7422 }
Egor Churaev89831422016-12-23 14:55:49 +00007423 case SK_OCLZeroQueue: {
7424 assert(Step->Type->isQueueT() &&
7425 "Event initialization on non queue type.");
7426
7427 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7428 CK_ZeroToOCLQueue,
7429 CurInit.get()->getValueKind());
7430 break;
7431 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007432 }
7433 }
John McCall1f425642010-11-11 03:21:53 +00007434
7435 // Diagnose non-fatal problems with the completed initialization.
7436 if (Entity.getKind() == InitializedEntity::EK_Member &&
7437 cast<FieldDecl>(Entity.getDecl())->isBitField())
7438 S.CheckBitFieldInitialization(Kind.getLocation(),
7439 cast<FieldDecl>(Entity.getDecl()),
7440 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007441
Richard Trieuac3eca52015-04-29 01:52:17 +00007442 // Check for std::move on construction.
7443 if (const Expr *E = CurInit.get()) {
7444 CheckMoveOnConstruction(S, E,
7445 Entity.getKind() == InitializedEntity::EK_Result);
7446 }
7447
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007448 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007449}
7450
Richard Smith593f9932012-12-08 02:01:17 +00007451/// Somewhere within T there is an uninitialized reference subobject.
7452/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00007453static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7454 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00007455 if (T->isReferenceType()) {
7456 S.Diag(Loc, diag::err_reference_without_init)
7457 << T.getNonReferenceType();
7458 return true;
7459 }
7460
7461 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7462 if (!RD || !RD->hasUninitializedReferenceMember())
7463 return false;
7464
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007465 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00007466 if (FI->isUnnamedBitfield())
7467 continue;
7468
7469 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7470 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7471 return true;
7472 }
7473 }
7474
Aaron Ballman574705e2014-03-13 15:41:46 +00007475 for (const auto &BI : RD->bases()) {
7476 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00007477 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7478 return true;
7479 }
7480 }
7481
7482 return false;
7483}
7484
7485
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007486//===----------------------------------------------------------------------===//
7487// Diagnose initialization failures
7488//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00007489
7490/// Emit notes associated with an initialization that failed due to a
7491/// "simple" conversion failure.
7492static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7493 Expr *op) {
7494 QualType destType = entity.getType();
7495 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7496 op->getType()->isObjCObjectPointerType()) {
7497
7498 // Emit a possible note about the conversion failing because the
7499 // operand is a message send with a related result type.
7500 S.EmitRelatedResultTypeNote(op);
7501
7502 // Emit a possible note about a return failing because we're
7503 // expecting a related result type.
7504 if (entity.getKind() == InitializedEntity::EK_Result)
7505 S.EmitRelatedResultTypeNoteForReturn(destType);
7506 }
7507}
7508
Richard Smith0449aaf2013-11-21 23:30:57 +00007509static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7510 InitListExpr *InitList) {
7511 QualType DestType = Entity.getType();
7512
7513 QualType E;
7514 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7515 QualType ArrayType = S.Context.getConstantArrayType(
7516 E.withConst(),
7517 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7518 InitList->getNumInits()),
7519 clang::ArrayType::Normal, 0);
7520 InitializedEntity HiddenArray =
7521 InitializedEntity::InitializeTemporary(ArrayType);
7522 return diagnoseListInit(S, HiddenArray, InitList);
7523 }
7524
Richard Smith8d082d12014-09-04 22:13:39 +00007525 if (DestType->isReferenceType()) {
7526 // A list-initialization failure for a reference means that we tried to
7527 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7528 // inner initialization failed.
7529 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7530 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7531 SourceLocation Loc = InitList->getLocStart();
7532 if (auto *D = Entity.getDecl())
7533 Loc = D->getLocation();
7534 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7535 return;
7536 }
7537
Richard Smith0449aaf2013-11-21 23:30:57 +00007538 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00007539 /*VerifyOnly=*/false,
7540 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00007541 assert(DiagnoseInitList.HadError() &&
7542 "Inconsistent init list check result.");
7543}
7544
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007545bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007546 const InitializedEntity &Entity,
7547 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007548 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007549 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007550 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007551
Douglas Gregor1b303932009-12-22 15:35:07 +00007552 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007553 switch (Failure) {
7554 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007555 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007556 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00007557 // Dig out the reference subobject which is uninitialized and diagnose it.
7558 // If this is value-initialization, this could be nested some way within
7559 // the target type.
7560 assert(Kind.getKind() == InitializationKind::IK_Value ||
7561 DestType->isReferenceType());
7562 bool Diagnosed =
7563 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7564 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7565 (void)Diagnosed;
7566 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007567 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007568 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007569 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00007570 case FK_ParenthesizedListInitForReference:
7571 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7572 << 1 << Entity.getType() << Args[0]->getSourceRange();
7573 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007574
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007575 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007576 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007577 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007578 case FK_ArrayNeedsInitListOrStringLiteral:
7579 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7580 break;
7581 case FK_ArrayNeedsInitListOrWideStringLiteral:
7582 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7583 break;
7584 case FK_NarrowStringIntoWideCharArray:
7585 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7586 break;
7587 case FK_WideStringIntoCharArray:
7588 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7589 break;
7590 case FK_IncompatWideStringIntoWideChar:
7591 S.Diag(Kind.getLocation(),
7592 diag::err_array_init_incompat_wide_string_into_wchar);
7593 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007594 case FK_ArrayTypeMismatch:
7595 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00007596 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00007597 (Failure == FK_ArrayTypeMismatch
7598 ? diag::err_array_init_different_type
7599 : diag::err_array_init_non_constant_array))
7600 << DestType.getNonReferenceType()
7601 << Args[0]->getType()
7602 << Args[0]->getSourceRange();
7603 break;
7604
John McCalla59dc2f2012-01-05 00:13:19 +00007605 case FK_VariableLengthArrayHasInitializer:
7606 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7607 << Args[0]->getSourceRange();
7608 break;
7609
John McCall16df1e52010-03-30 21:47:33 +00007610 case FK_AddressOfOverloadFailed: {
7611 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007612 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007613 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00007614 true,
7615 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007616 break;
John McCall16df1e52010-03-30 21:47:33 +00007617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007618
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007619 case FK_AddressOfUnaddressableFunction: {
7620 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7621 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7622 Args[0]->getLocStart());
7623 break;
7624 }
7625
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007626 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00007627 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007628 switch (FailedOverloadResult) {
7629 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00007630 if (Failure == FK_UserConversionOverloadFailed)
7631 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7632 << Args[0]->getType() << DestType
7633 << Args[0]->getSourceRange();
7634 else
7635 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7636 << DestType << Args[0]->getType()
7637 << Args[0]->getSourceRange();
7638
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007639 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007641
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007642 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00007643 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007644 DestType.getNonReferenceType(),
7645 diag::err_typecheck_nonviable_condition_incomplete,
7646 Args[0]->getType(), Args[0]->getSourceRange()))
7647 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00007648 << (Entity.getKind() == InitializedEntity::EK_Result)
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007649 << Args[0]->getType() << Args[0]->getSourceRange()
7650 << DestType.getNonReferenceType();
7651
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007652 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007654
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007655 case OR_Deleted: {
7656 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7657 << Args[0]->getType() << DestType.getNonReferenceType()
7658 << Args[0]->getSourceRange();
7659 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007660 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00007661 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007662 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00007663 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007664 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007665 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007666 }
7667 break;
7668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007670 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007671 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007672 }
7673 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007674
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007675 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00007676 if (isa<InitListExpr>(Args[0])) {
7677 S.Diag(Kind.getLocation(),
7678 diag::err_lvalue_reference_bind_to_initlist)
7679 << DestType.getNonReferenceType().isVolatileQualified()
7680 << DestType.getNonReferenceType()
7681 << Args[0]->getSourceRange();
7682 break;
7683 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007684 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00007685
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007686 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007687 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007688 Failure == FK_NonConstLValueReferenceBindingToTemporary
7689 ? diag::err_lvalue_reference_bind_to_temporary
7690 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00007691 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007692 << DestType.getNonReferenceType()
7693 << Args[0]->getType()
7694 << Args[0]->getSourceRange();
7695 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007696
Richard Smithb8c0f552016-12-09 18:49:13 +00007697 case FK_NonConstLValueReferenceBindingToBitfield: {
7698 // We don't necessarily have an unambiguous source bit-field.
7699 FieldDecl *BitField = Args[0]->getSourceBitField();
7700 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7701 << DestType.isVolatileQualified()
7702 << (BitField ? BitField->getDeclName() : DeclarationName())
7703 << (BitField != nullptr)
7704 << Args[0]->getSourceRange();
7705 if (BitField)
7706 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7707 break;
7708 }
7709
7710 case FK_NonConstLValueReferenceBindingToVectorElement:
7711 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7712 << DestType.isVolatileQualified()
7713 << Args[0]->getSourceRange();
7714 break;
7715
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007716 case FK_RValueReferenceBindingToLValue:
7717 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00007718 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007719 << Args[0]->getSourceRange();
7720 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007721
Richard Trieuf956a492015-05-16 01:27:03 +00007722 case FK_ReferenceInitDropsQualifiers: {
7723 QualType SourceType = Args[0]->getType();
7724 QualType NonRefType = DestType.getNonReferenceType();
7725 Qualifiers DroppedQualifiers =
7726 SourceType.getQualifiers() - NonRefType.getQualifiers();
7727
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007728 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00007729 << SourceType
7730 << NonRefType
7731 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007732 << Args[0]->getSourceRange();
7733 break;
Richard Trieuf956a492015-05-16 01:27:03 +00007734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007735
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007736 case FK_ReferenceInitFailed:
7737 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7738 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00007739 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007740 << Args[0]->getType()
7741 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00007742 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007743 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007744
Douglas Gregorb491ed32011-02-19 21:32:49 +00007745 case FK_ConversionFailed: {
7746 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00007747 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00007748 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007749 << DestType
John McCall086a4642010-11-24 05:12:34 +00007750 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00007751 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007752 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00007753 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7754 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00007755 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00007756 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007757 }
John Wiegley01296292011-04-08 18:41:53 +00007758
7759 case FK_ConversionFromPropertyFailed:
7760 // No-op. This error has already been reported.
7761 break;
7762
Douglas Gregor51e77d52009-12-10 17:56:55 +00007763 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00007764 SourceRange R;
7765
David Majnemerbd385442015-04-10 04:52:06 +00007766 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007767 if (InitList && InitList->getNumInits() >= 1) {
David Majnemerbd385442015-04-10 04:52:06 +00007768 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007769 } else {
7770 assert(Args.size() > 1 && "Expected multiple initializers!");
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007771 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007772 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007773
Alp Tokerb6cc5922014-05-03 03:45:55 +00007774 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00007775 if (Kind.isCStyleOrFunctionalCast())
7776 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7777 << R;
7778 else
7779 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7780 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007781 break;
7782 }
7783
Richard Smith49a6b6e2017-03-24 01:14:25 +00007784 case FK_ParenthesizedListInitForScalar:
7785 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7786 << 0 << Entity.getType() << Args[0]->getSourceRange();
7787 break;
7788
Douglas Gregor51e77d52009-12-10 17:56:55 +00007789 case FK_ReferenceBindingToInitList:
7790 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7791 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7792 break;
7793
7794 case FK_InitListBadDestinationType:
7795 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7796 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7797 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007798
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007799 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007800 case FK_ConstructorOverloadFailed: {
7801 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007802 if (Args.size())
7803 ArgsRange = SourceRange(Args.front()->getLocStart(),
7804 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007805
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007806 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00007807 assert(Args.size() == 1 &&
7808 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007809 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007810 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007811 }
7812
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007813 // FIXME: Using "DestType" for the entity we're printing is probably
7814 // bad.
7815 switch (FailedOverloadResult) {
7816 case OR_Ambiguous:
7817 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7818 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007819 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007820 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007821
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007822 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007823 if (Kind.getKind() == InitializationKind::IK_Default &&
7824 (Entity.getKind() == InitializedEntity::EK_Base ||
7825 Entity.getKind() == InitializedEntity::EK_Member) &&
7826 isa<CXXConstructorDecl>(S.CurContext)) {
7827 // This is implicit default initialization of a member or
7828 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00007829 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007830 // initialize this base/member.
7831 CXXConstructorDecl *Constructor
7832 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00007833 const CXXRecordDecl *InheritedFrom = nullptr;
7834 if (auto Inherited = Constructor->getInheritedConstructor())
7835 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007836 if (Entity.getKind() == InitializedEntity::EK_Base) {
7837 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007838 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007839 << S.Context.getTypeDeclType(Constructor->getParent())
7840 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00007841 << Entity.getType()
7842 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007843
7844 RecordDecl *BaseDecl
7845 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7846 ->getDecl();
7847 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7848 << S.Context.getTagDeclType(BaseDecl);
7849 } else {
7850 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007851 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007852 << S.Context.getTypeDeclType(Constructor->getParent())
7853 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00007854 << Entity.getName()
7855 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00007856 S.Diag(Entity.getDecl()->getLocation(),
7857 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007858
7859 if (const RecordType *Record
7860 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007861 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007862 diag::note_previous_decl)
7863 << S.Context.getTagDeclType(Record->getDecl());
7864 }
7865 break;
7866 }
7867
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007868 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7869 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007870 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007871 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007872
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007873 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007874 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007875 OverloadingResult Ovl
7876 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00007877 if (Ovl != OR_Deleted) {
7878 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7879 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007880 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00007881 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007882 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00007883
7884 // If this is a defaulted or implicitly-declared function, then
7885 // it was implicitly deleted. Make it clear that the deletion was
7886 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00007887 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007888 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00007889 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007890 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00007891 else
7892 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7893 << true << DestType << ArgsRange;
7894
7895 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007896 break;
7897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007898
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007899 case OR_Success:
7900 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007901 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007902 }
David Blaikie60deeee2012-01-17 08:24:58 +00007903 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007904
Douglas Gregor85dabae2009-12-16 01:38:02 +00007905 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007906 if (Entity.getKind() == InitializedEntity::EK_Member &&
7907 isa<CXXConstructorDecl>(S.CurContext)) {
7908 // This is implicit default-initialization of a const member in
7909 // a constructor. Complain that it needs to be explicitly
7910 // initialized.
7911 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7912 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007913 << (Constructor->getInheritedConstructor() ? 2 :
7914 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007915 << S.Context.getTypeDeclType(Constructor->getParent())
7916 << /*const=*/1
7917 << Entity.getName();
7918 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7919 << Entity.getName();
7920 } else {
7921 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00007922 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007923 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00007924 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007925
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007926 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00007927 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007928 diag::err_init_incomplete_type);
7929 break;
7930
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007931 case FK_ListInitializationFailed: {
7932 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00007933 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7934 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007935 break;
7936 }
John McCall4124c492011-10-17 18:40:02 +00007937
7938 case FK_PlaceholderType: {
7939 // FIXME: Already diagnosed!
7940 break;
7941 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00007942
Sebastian Redl048a6d72012-04-01 19:54:59 +00007943 case FK_ExplicitConstructor: {
7944 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7945 << Args[0]->getSourceRange();
7946 OverloadCandidateSet::iterator Best;
7947 OverloadingResult Ovl
7948 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00007949 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007950 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7951 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00007952 S.Diag(CtorDecl->getLocation(),
7953 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007954 break;
7955 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007957
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007958 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007959 return true;
7960}
Douglas Gregore1314a62009-12-18 05:02:21 +00007961
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007962void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007963 switch (SequenceKind) {
7964 case FailedSequence: {
7965 OS << "Failed sequence: ";
7966 switch (Failure) {
7967 case FK_TooManyInitsForReference:
7968 OS << "too many initializers for reference";
7969 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007970
Richard Smith49a6b6e2017-03-24 01:14:25 +00007971 case FK_ParenthesizedListInitForReference:
7972 OS << "parenthesized list init for reference";
7973 break;
7974
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007975 case FK_ArrayNeedsInitList:
7976 OS << "array requires initializer list";
7977 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007978
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007979 case FK_AddressOfUnaddressableFunction:
7980 OS << "address of unaddressable function was taken";
7981 break;
7982
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007983 case FK_ArrayNeedsInitListOrStringLiteral:
7984 OS << "array requires initializer list or string literal";
7985 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007986
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007987 case FK_ArrayNeedsInitListOrWideStringLiteral:
7988 OS << "array requires initializer list or wide string literal";
7989 break;
7990
7991 case FK_NarrowStringIntoWideCharArray:
7992 OS << "narrow string into wide char array";
7993 break;
7994
7995 case FK_WideStringIntoCharArray:
7996 OS << "wide string into char array";
7997 break;
7998
7999 case FK_IncompatWideStringIntoWideChar:
8000 OS << "incompatible wide string into wide char array";
8001 break;
8002
Douglas Gregore2f943b2011-02-22 18:29:51 +00008003 case FK_ArrayTypeMismatch:
8004 OS << "array type mismatch";
8005 break;
8006
8007 case FK_NonConstantArrayInit:
8008 OS << "non-constant array initializer";
8009 break;
8010
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008011 case FK_AddressOfOverloadFailed:
8012 OS << "address of overloaded function failed";
8013 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008014
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008015 case FK_ReferenceInitOverloadFailed:
8016 OS << "overload resolution for reference initialization failed";
8017 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008018
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008019 case FK_NonConstLValueReferenceBindingToTemporary:
8020 OS << "non-const lvalue reference bound to temporary";
8021 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008022
Richard Smithb8c0f552016-12-09 18:49:13 +00008023 case FK_NonConstLValueReferenceBindingToBitfield:
8024 OS << "non-const lvalue reference bound to bit-field";
8025 break;
8026
8027 case FK_NonConstLValueReferenceBindingToVectorElement:
8028 OS << "non-const lvalue reference bound to vector element";
8029 break;
8030
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008031 case FK_NonConstLValueReferenceBindingToUnrelated:
8032 OS << "non-const lvalue reference bound to unrelated type";
8033 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008034
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008035 case FK_RValueReferenceBindingToLValue:
8036 OS << "rvalue reference bound to an lvalue";
8037 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008038
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008039 case FK_ReferenceInitDropsQualifiers:
8040 OS << "reference initialization drops qualifiers";
8041 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008042
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008043 case FK_ReferenceInitFailed:
8044 OS << "reference initialization failed";
8045 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008046
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008047 case FK_ConversionFailed:
8048 OS << "conversion failed";
8049 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008050
John Wiegley01296292011-04-08 18:41:53 +00008051 case FK_ConversionFromPropertyFailed:
8052 OS << "conversion from property failed";
8053 break;
8054
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008055 case FK_TooManyInitsForScalar:
8056 OS << "too many initializers for scalar";
8057 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008058
Richard Smith49a6b6e2017-03-24 01:14:25 +00008059 case FK_ParenthesizedListInitForScalar:
8060 OS << "parenthesized list init for reference";
8061 break;
8062
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008063 case FK_ReferenceBindingToInitList:
8064 OS << "referencing binding to initializer list";
8065 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008067 case FK_InitListBadDestinationType:
8068 OS << "initializer list for non-aggregate, non-scalar type";
8069 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008070
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008071 case FK_UserConversionOverloadFailed:
8072 OS << "overloading failed for user-defined conversion";
8073 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008074
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008075 case FK_ConstructorOverloadFailed:
8076 OS << "constructor overloading failed";
8077 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008078
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008079 case FK_DefaultInitOfConst:
8080 OS << "default initialization of a const variable";
8081 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008082
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00008083 case FK_Incomplete:
8084 OS << "initialization of incomplete type";
8085 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008086
8087 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008088 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00008089 break;
8090
John McCalla59dc2f2012-01-05 00:13:19 +00008091 case FK_VariableLengthArrayHasInitializer:
8092 OS << "variable length array has an initializer";
8093 break;
8094
John McCall4124c492011-10-17 18:40:02 +00008095 case FK_PlaceholderType:
8096 OS << "initializer expression isn't contextually valid";
8097 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00008098
8099 case FK_ListConstructorOverloadFailed:
8100 OS << "list constructor overloading failed";
8101 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008102
Sebastian Redl048a6d72012-04-01 19:54:59 +00008103 case FK_ExplicitConstructor:
8104 OS << "list copy initialization chose explicit constructor";
8105 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008106 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008107 OS << '\n';
8108 return;
8109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008110
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008111 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00008112 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008113 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008114
Sebastian Redld201edf2011-06-05 13:59:11 +00008115 case NormalSequence:
8116 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008117 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008120 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8121 if (S != step_begin()) {
8122 OS << " -> ";
8123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008124
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008125 switch (S->Kind) {
8126 case SK_ResolveAddressOfOverloadedFunction:
8127 OS << "resolve address of overloaded function";
8128 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008129
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008130 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008131 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008132 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008133
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008134 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008135 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008136 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008137
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008138 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008139 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008140 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008141
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008142 case SK_BindReference:
8143 OS << "bind reference to lvalue";
8144 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008145
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008146 case SK_BindReferenceToTemporary:
8147 OS << "bind reference to a temporary";
8148 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008149
Richard Smithb8c0f552016-12-09 18:49:13 +00008150 case SK_FinalCopy:
8151 OS << "final copy in class direct-initialization";
8152 break;
8153
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008154 case SK_ExtraneousCopyToTemporary:
8155 OS << "extraneous C++03 copy to temporary";
8156 break;
8157
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008158 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008159 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008160 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008161
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008162 case SK_QualificationConversionRValue:
8163 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008164 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008165
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008166 case SK_QualificationConversionXValue:
8167 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008168 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008169
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008170 case SK_QualificationConversionLValue:
8171 OS << "qualification conversion (lvalue)";
8172 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008173
Richard Smith77be48a2014-07-31 06:31:19 +00008174 case SK_AtomicConversion:
8175 OS << "non-atomic-to-atomic conversion";
8176 break;
8177
Jordan Roseb1312a52013-04-11 00:58:58 +00008178 case SK_LValueToRValue:
8179 OS << "load (lvalue to rvalue)";
8180 break;
8181
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008182 case SK_ConversionSequence:
8183 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008184 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008185 OS << ")";
8186 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008187
Richard Smithaaa0ec42013-09-21 21:19:19 +00008188 case SK_ConversionSequenceNoNarrowing:
8189 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008190 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008191 OS << ")";
8192 break;
8193
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008194 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008195 OS << "list aggregate initialization";
8196 break;
8197
Sebastian Redl29526f02011-11-27 16:50:07 +00008198 case SK_UnwrapInitList:
8199 OS << "unwrap reference initializer list";
8200 break;
8201
8202 case SK_RewrapInitList:
8203 OS << "rewrap reference initializer list";
8204 break;
8205
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008206 case SK_ConstructorInitialization:
8207 OS << "constructor initialization";
8208 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008209
Richard Smith53324112014-07-16 21:33:43 +00008210 case SK_ConstructorInitializationFromList:
8211 OS << "list initialization via constructor";
8212 break;
8213
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008214 case SK_ZeroInitialization:
8215 OS << "zero initialization";
8216 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008217
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008218 case SK_CAssignment:
8219 OS << "C assignment";
8220 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008221
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008222 case SK_StringInit:
8223 OS << "string initialization";
8224 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008225
8226 case SK_ObjCObjectConversion:
8227 OS << "Objective-C object conversion";
8228 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008229
Richard Smith410306b2016-12-12 02:53:20 +00008230 case SK_ArrayLoopIndex:
8231 OS << "indexing for array initialization loop";
8232 break;
8233
8234 case SK_ArrayLoopInit:
8235 OS << "array initialization loop";
8236 break;
8237
Douglas Gregore2f943b2011-02-22 18:29:51 +00008238 case SK_ArrayInit:
8239 OS << "array initialization";
8240 break;
John McCall31168b02011-06-15 23:02:42 +00008241
Richard Smith378b8c82016-12-14 03:22:16 +00008242 case SK_GNUArrayInit:
8243 OS << "array initialization (GNU extension)";
8244 break;
8245
Richard Smithebeed412012-02-15 22:38:09 +00008246 case SK_ParenthesizedArrayInit:
8247 OS << "parenthesized array initialization";
8248 break;
8249
John McCall31168b02011-06-15 23:02:42 +00008250 case SK_PassByIndirectCopyRestore:
8251 OS << "pass by indirect copy and restore";
8252 break;
8253
8254 case SK_PassByIndirectRestore:
8255 OS << "pass by indirect restore";
8256 break;
8257
8258 case SK_ProduceObjCObject:
8259 OS << "Objective-C object retension";
8260 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008261
8262 case SK_StdInitializerList:
8263 OS << "std::initializer_list from initializer list";
8264 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008265
Richard Smithf8adcdc2014-07-17 05:12:35 +00008266 case SK_StdInitializerListConstructorCall:
8267 OS << "list initialization from std::initializer_list";
8268 break;
8269
Guy Benyei61054192013-02-07 10:55:47 +00008270 case SK_OCLSamplerInit:
8271 OS << "OpenCL sampler_t from integer constant";
8272 break;
8273
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008274 case SK_OCLZeroEvent:
8275 OS << "OpenCL event_t from zero";
8276 break;
Egor Churaev89831422016-12-23 14:55:49 +00008277
8278 case SK_OCLZeroQueue:
8279 OS << "OpenCL queue_t from zero";
8280 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008281 }
Richard Smith6b216962013-02-05 05:52:24 +00008282
8283 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008284 }
Richard Smith6b216962013-02-05 05:52:24 +00008285
8286 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008287}
8288
8289void InitializationSequence::dump() const {
8290 dump(llvm::errs());
8291}
8292
Richard Smithaaa0ec42013-09-21 21:19:19 +00008293static void DiagnoseNarrowingInInitList(Sema &S,
8294 const ImplicitConversionSequence &ICS,
8295 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008296 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008297 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008298 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008299 switch (ICS.getKind()) {
8300 case ImplicitConversionSequence::StandardConversion:
8301 SCS = &ICS.Standard;
8302 break;
8303 case ImplicitConversionSequence::UserDefinedConversion:
8304 SCS = &ICS.UserDefined.After;
8305 break;
8306 case ImplicitConversionSequence::AmbiguousConversion:
8307 case ImplicitConversionSequence::EllipsisConversion:
8308 case ImplicitConversionSequence::BadConversion:
8309 return;
8310 }
8311
Richard Smith66e05fe2012-01-18 05:21:49 +00008312 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8313 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00008314 QualType ConstantType;
8315 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8316 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00008317 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00008318 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00008319 // No narrowing occurred.
8320 return;
8321
8322 case NK_Type_Narrowing:
8323 // This was a floating-to-integer conversion, which is always considered a
8324 // narrowing conversion even if the value is a constant and can be
8325 // represented exactly as an integer.
8326 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008327 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8328 ? diag::warn_init_list_type_narrowing
8329 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008330 << PostInit->getSourceRange()
8331 << PreNarrowingType.getLocalUnqualifiedType()
8332 << EntityType.getLocalUnqualifiedType();
8333 break;
8334
8335 case NK_Constant_Narrowing:
8336 // A constant value was narrowed.
8337 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008338 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8339 ? diag::warn_init_list_constant_narrowing
8340 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008341 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00008342 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00008343 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008344 break;
8345
8346 case NK_Variable_Narrowing:
8347 // A variable's value may have been narrowed.
8348 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008349 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8350 ? diag::warn_init_list_variable_narrowing
8351 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008352 << PostInit->getSourceRange()
8353 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00008354 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008355 break;
8356 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008357
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008358 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008359 llvm::raw_svector_ostream OS(StaticCast);
8360 OS << "static_cast<";
8361 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8362 // It's important to use the typedef's name if there is one so that the
8363 // fixit doesn't break code using types like int64_t.
8364 //
8365 // FIXME: This will break if the typedef requires qualification. But
8366 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008367 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008368 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00008369 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008370 else {
8371 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8372 // with a broken cast.
8373 return;
8374 }
8375 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00008376 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008377 << PostInit->getSourceRange()
8378 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8379 << FixItHint::CreateInsertion(
8380 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008381}
8382
Douglas Gregore1314a62009-12-18 05:02:21 +00008383//===----------------------------------------------------------------------===//
8384// Initialization helper functions
8385//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00008386bool
8387Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8388 ExprResult Init) {
8389 if (Init.isInvalid())
8390 return false;
8391
8392 Expr *InitE = Init.get();
8393 assert(InitE && "No initialization expression");
8394
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00008395 InitializationKind Kind
8396 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008397 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00008398 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00008399}
8400
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008401ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00008402Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8403 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008404 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00008405 bool TopLevelOfInitList,
8406 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00008407 if (Init.isInvalid())
8408 return ExprError();
8409
John McCall1f425642010-11-11 03:21:53 +00008410 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00008411 assert(InitE && "No initialization expression?");
8412
8413 if (EqualLoc.isInvalid())
8414 EqualLoc = InitE->getLocStart();
8415
8416 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00008417 EqualLoc,
8418 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00008419 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008420
Alex Lorenzde69ff92017-05-16 10:23:58 +00008421 // Prevent infinite recursion when performing parameter copy-initialization.
8422 const bool ShouldTrackCopy =
8423 Entity.isParameterKind() && Seq.isConstructorInitialization();
8424 if (ShouldTrackCopy) {
8425 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
8426 CurrentParameterCopyTypes.end()) {
8427 Seq.SetOverloadFailure(
8428 InitializationSequence::FK_ConstructorOverloadFailed,
8429 OR_No_Viable_Function);
8430
8431 // Try to give a meaningful diagnostic note for the problematic
8432 // constructor.
8433 const auto LastStep = Seq.step_end() - 1;
8434 assert(LastStep->Kind ==
8435 InitializationSequence::SK_ConstructorInitialization);
8436 const FunctionDecl *Function = LastStep->Function.Function;
8437 auto Candidate =
8438 llvm::find_if(Seq.getFailedCandidateSet(),
8439 [Function](const OverloadCandidate &Candidate) -> bool {
8440 return Candidate.Viable &&
8441 Candidate.Function == Function &&
8442 Candidate.Conversions.size() > 0;
8443 });
8444 if (Candidate != Seq.getFailedCandidateSet().end() &&
8445 Function->getNumParams() > 0) {
8446 Candidate->Viable = false;
8447 Candidate->FailureKind = ovl_fail_bad_conversion;
8448 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
8449 InitE,
8450 Function->getParamDecl(0)->getType());
8451 }
8452 }
8453 CurrentParameterCopyTypes.push_back(Entity.getType());
8454 }
8455
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008456 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00008457
Alex Lorenzde69ff92017-05-16 10:23:58 +00008458 if (ShouldTrackCopy)
8459 CurrentParameterCopyTypes.pop_back();
8460
Richard Smith66e05fe2012-01-18 05:21:49 +00008461 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00008462}
Richard Smith60437622017-02-09 19:17:44 +00008463
Richard Smith1363e8f2017-09-07 07:22:36 +00008464/// Determine whether RD is, or is derived from, a specialization of CTD.
8465static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
8466 ClassTemplateDecl *CTD) {
8467 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
8468 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
8469 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
8470 };
8471 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
8472}
8473
Richard Smith60437622017-02-09 19:17:44 +00008474QualType Sema::DeduceTemplateSpecializationFromInitializer(
8475 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8476 const InitializationKind &Kind, MultiExprArg Inits) {
8477 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8478 TSInfo->getType()->getContainedDeducedType());
8479 assert(DeducedTST && "not a deduced template specialization type");
8480
8481 // We can only perform deduction for class templates.
8482 auto TemplateName = DeducedTST->getTemplateName();
8483 auto *Template =
8484 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8485 if (!Template) {
8486 Diag(Kind.getLocation(),
8487 diag::err_deduced_non_class_template_specialization_type)
8488 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8489 if (auto *TD = TemplateName.getAsTemplateDecl())
8490 Diag(TD->getLocation(), diag::note_template_decl_here);
8491 return QualType();
8492 }
8493
Richard Smith32918772017-02-14 00:25:28 +00008494 // Can't deduce from dependent arguments.
8495 if (Expr::hasAnyTypeDependentArguments(Inits))
8496 return Context.DependentTy;
8497
Richard Smith60437622017-02-09 19:17:44 +00008498 // FIXME: Perform "exact type" matching first, per CWG discussion?
8499 // Or implement this via an implied 'T(T) -> T' deduction guide?
8500
8501 // FIXME: Do we need/want a std::initializer_list<T> special case?
8502
Richard Smith32918772017-02-14 00:25:28 +00008503 // Look up deduction guides, including those synthesized from constructors.
8504 //
Richard Smith60437622017-02-09 19:17:44 +00008505 // C++1z [over.match.class.deduct]p1:
8506 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00008507 // - For each constructor of the class template designated by the
8508 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00008509 // - For each deduction-guide, a function or function template [...]
8510 DeclarationNameInfo NameInfo(
8511 Context.DeclarationNames.getCXXDeductionGuideName(Template),
8512 TSInfo->getTypeLoc().getEndLoc());
8513 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
8514 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00008515
8516 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
8517 // clear on this, but they're not found by name so access does not apply.
8518 Guides.suppressDiagnostics();
8519
8520 // Figure out if this is list-initialization.
8521 InitListExpr *ListInit =
8522 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
8523 ? dyn_cast<InitListExpr>(Inits[0])
8524 : nullptr;
8525
8526 // C++1z [over.match.class.deduct]p1:
8527 // Initialization and overload resolution are performed as described in
8528 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
8529 // (as appropriate for the type of initialization performed) for an object
8530 // of a hypothetical class type, where the selected functions and function
8531 // templates are considered to be the constructors of that class type
8532 //
8533 // Since we know we're initializing a class type of a type unrelated to that
8534 // of the initializer, this reduces to something fairly reasonable.
8535 OverloadCandidateSet Candidates(Kind.getLocation(),
8536 OverloadCandidateSet::CSK_Normal);
8537 OverloadCandidateSet::iterator Best;
8538 auto tryToResolveOverload =
8539 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00008540 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Richard Smith32918772017-02-14 00:25:28 +00008541 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
8542 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00008543 if (D->isInvalidDecl())
8544 continue;
8545
Richard Smithbc491202017-02-17 20:05:37 +00008546 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
8547 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
8548 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
8549 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00008550 continue;
8551
8552 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
8553 // For copy-initialization, the candidate functions are all the
8554 // converting constructors (12.3.1) of that class.
8555 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
8556 // The converting constructors of T are candidate functions.
8557 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00008558 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00008559 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00008560 continue;
Richard Smith60437622017-02-09 19:17:44 +00008561
8562 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00008563 // could never be called with one argument are not interesting to
8564 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00008565 if (GD->getMinRequiredArguments() > 1 ||
8566 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00008567 continue;
8568 }
8569
8570 // C++ [over.match.list]p1.1: (first phase list initialization)
8571 // Initially, the candidate functions are the initializer-list
8572 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00008573 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00008574 continue;
8575
8576 // C++ [over.match.list]p1.2: (second phase list initialization)
8577 // the candidate functions are all the constructors of the class T
8578 // C++ [over.match.ctor]p1: (all other cases)
8579 // the candidate functions are all the constructors of the class of
8580 // the object being initialized
8581
8582 // C++ [over.best.ics]p4:
8583 // When [...] the constructor [...] is a candidate by
8584 // - [over.match.copy] (in all cases)
8585 // FIXME: The "second phase of [over.match.list] case can also
8586 // theoretically happen here, but it's not clear whether we can
8587 // ever have a parameter of the right type.
8588 bool SuppressUserConversions = Kind.isCopyInit();
8589
Richard Smith60437622017-02-09 19:17:44 +00008590 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00008591 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
8592 Inits, Candidates,
8593 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00008594 else
Richard Smithbc491202017-02-17 20:05:37 +00008595 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00008596 SuppressUserConversions);
8597 }
8598 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
8599 };
8600
8601 OverloadingResult Result = OR_No_Viable_Function;
8602
8603 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
8604 // try initializer-list constructors.
8605 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00008606 bool TryListConstructors = true;
8607
8608 // Try list constructors unless the list is empty and the class has one or
8609 // more default constructors, in which case those constructors win.
8610 if (!ListInit->getNumInits()) {
8611 for (NamedDecl *D : Guides) {
8612 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
8613 if (FD && FD->getMinRequiredArguments() == 0) {
8614 TryListConstructors = false;
8615 break;
8616 }
8617 }
Richard Smith1363e8f2017-09-07 07:22:36 +00008618 } else if (ListInit->getNumInits() == 1) {
8619 // C++ [over.match.class.deduct]:
8620 // As an exception, the first phase in [over.match.list] (considering
8621 // initializer-list constructors) is omitted if the initializer list
8622 // consists of a single expression of type cv U, where U is a
8623 // specialization of C or a class derived from a specialization of C.
8624 Expr *E = ListInit->getInit(0);
8625 auto *RD = E->getType()->getAsCXXRecordDecl();
8626 if (!isa<InitListExpr>(E) && RD &&
8627 isOrIsDerivedFromSpecializationOf(RD, Template))
8628 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00008629 }
8630
8631 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00008632 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
8633 // Then unwrap the initializer list and try again considering all
8634 // constructors.
8635 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
8636 }
8637
8638 // If list-initialization fails, or if we're doing any other kind of
8639 // initialization, we (eventually) consider constructors.
8640 if (Result == OR_No_Viable_Function)
8641 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
8642
8643 switch (Result) {
8644 case OR_Ambiguous:
8645 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
8646 << TemplateName;
8647 // FIXME: For list-initialization candidates, it'd usually be better to
8648 // list why they were not viable when given the initializer list itself as
8649 // an argument.
8650 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
8651 return QualType();
8652
Richard Smith32918772017-02-14 00:25:28 +00008653 case OR_No_Viable_Function: {
8654 CXXRecordDecl *Primary =
8655 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
8656 bool Complete =
8657 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00008658 Diag(Kind.getLocation(),
8659 Complete ? diag::err_deduced_class_template_ctor_no_viable
8660 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00008661 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00008662 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
8663 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00008664 }
Richard Smith60437622017-02-09 19:17:44 +00008665
8666 case OR_Deleted: {
8667 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
8668 << TemplateName;
8669 NoteDeletedFunction(Best->Function);
8670 return QualType();
8671 }
8672
8673 case OR_Success:
8674 // C++ [over.match.list]p1:
8675 // In copy-list-initialization, if an explicit constructor is chosen, the
8676 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00008677 if (Kind.isCopyInit() && ListInit &&
8678 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00008679 bool IsDeductionGuide = !Best->Function->isImplicit();
8680 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
8681 << TemplateName << IsDeductionGuide;
8682 Diag(Best->Function->getLocation(),
8683 diag::note_explicit_ctor_deduction_guide_here)
8684 << IsDeductionGuide;
8685 return QualType();
8686 }
8687
8688 // Make sure we didn't select an unusable deduction guide, and mark it
8689 // as referenced.
8690 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
8691 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
8692 break;
8693 }
8694
8695 // C++ [dcl.type.class.deduct]p1:
8696 // The placeholder is replaced by the return type of the function selected
8697 // by overload resolution for class template deduction.
8698 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
8699}