blob: 341e7120fe869c29f7d65b75f090cdb37b65c456 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Steve Narofff8ecff22008-05-01 22:18:59 +000014#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000016#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000017#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000018#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000019#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Designator.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000028
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000035/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38 if (Context.typesAreCompatible(Context.getWideCharType(), T))
39 return true;
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
43 }
44 return false;
45}
46
47enum StringInitFailureKind {
48 SIF_None,
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
52 SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000061 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000062 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000063
Chris Lattnera9196812009-02-26 23:26:43 +000064 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000069 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000070
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000073 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000074 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000075
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000076 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000078
79 switch (SL->getKind()) {
80 case StringLiteral::Ascii:
81 case StringLiteral::UTF8:
82 // char array can be initialized with a narrow string.
83 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000084 if (ElemTy->isCharType())
85 return SIF_None;
86 if (IsWideCharCompatible(ElemTy, Context))
87 return SIF_NarrowStringIntoWideChar;
88 return SIF_Other;
89 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90 // "An array with element type compatible with a qualified or unqualified
91 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92 // string literal with the corresponding encoding prefix (L, u, or U,
93 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +000094 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000095 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96 return SIF_None;
97 if (ElemTy->isCharType())
98 return SIF_WideStringIntoChar;
99 if (IsWideCharCompatible(ElemTy, Context))
100 return SIF_IncompatWideStringIntoWideChar;
101 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000102 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000103 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104 return SIF_None;
105 if (ElemTy->isCharType())
106 return SIF_WideStringIntoChar;
107 if (IsWideCharCompatible(ElemTy, Context))
108 return SIF_IncompatWideStringIntoWideChar;
109 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000110 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000111 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112 return SIF_None;
113 if (ElemTy->isCharType())
114 return SIF_WideStringIntoChar;
115 if (IsWideCharCompatible(ElemTy, Context))
116 return SIF_IncompatWideStringIntoWideChar;
117 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregorfb65e592011-07-27 05:40:30 +0000120 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000121}
122
Hans Wennborg950f3182013-05-16 09:22:40 +0000123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000125 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000129}
130
Richard Smith430c23b2013-05-05 16:40:13 +0000131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000134 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000135 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000136 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137 break;
138 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139 E = PE->getSubExpr();
140 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141 E = UO->getSubExpr();
142 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143 E = GSE->getResultExpr();
144 else
145 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000146 }
Richard Smith430c23b2013-05-05 16:40:13 +0000147}
148
John McCall5decec92011-02-21 07:57:55 +0000149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000151 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000152 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000153 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000154 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner0cb78032009-02-24 22:27:37 +0000156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000158 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000159 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000160 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000164 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000165 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Eli Friedman893abe42009-05-29 18:22:49 +0000168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Eli Friedman554eba92011-04-11 00:23:45 +0000170 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000171 // the size may be smaller or larger than the string we are initializing.
172 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000173 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000175 // For Pascal strings it's OK to strip off the terminating null character,
176 // so the example below is valid:
177 //
178 // unsigned char a[2] = "\pa";
179 if (SL->isPascal())
180 StrLength--;
181 }
182
Eli Friedman554eba92011-04-11 00:23:45 +0000183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000185 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000186 diag::err_initializer_string_for_char_array_too_long)
187 << Str->getSourceRange();
188 } else {
189 // C99 6.7.8p14.
190 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 S.Diag(Str->getLocStart(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000192 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000193 << Str->getSourceRange();
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Eli Friedman893abe42009-05-29 18:22:49 +0000196 // Set the type to the actual size that we are initializing. If we have
197 // something like:
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000201}
202
Chris Lattner0cb78032009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000207namespace {
208
Douglas Gregorcde232f2009-01-29 01:05:33 +0000209/// @brief Semantic checking for initializer lists.
210///
211/// The InitListChecker class contains a set of routines that each
212/// handle the initialization of a certain kind of entity, e.g.,
213/// arrays, vectors, struct/union types, scalars, etc. The
214/// InitListChecker itself performs a recursive walk of the subobject
215/// structure of the type to be initialized, while stepping through
216/// the initializer list one element at a time. The IList and Index
217/// parameters to each of the Check* routines contain the active
218/// (syntactic) initializer list and the index into that initializer
219/// list that represents the current initializer. Each routine is
220/// responsible for moving that Index forward as it consumes elements.
221///
222/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000223/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000224/// initializer list and the index into that initializer list where we
225/// are copying initializers as we map them over to the semantic
226/// list. Once we have completed our recursive walk of the subobject
227/// structure, we will have constructed a full semantic initializer
228/// list.
229///
230/// C99 designators cause changes in the initializer list traversal,
231/// because they make the initialization "jump" into a specific
232/// subobject and then continue the initialization from that
233/// point. CheckDesignatedInitializer() recursively steps into the
234/// designated subobject and manages backing out the recursion to
235/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000237 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000238 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000239 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000240 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000241 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000243
Anders Carlsson6cabf312010-01-23 23:23:01 +0000244 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000245 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000246 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000247 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000248 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000249 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000250 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000251 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000252 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000253 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000254 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000255 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000256 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000257 unsigned &StructuredIndex,
258 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000259 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000260 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000261 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000262 InitListExpr *StructuredList,
263 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000264 void CheckComplexType(const InitializedEntity &Entity,
265 InitListExpr *IList, QualType DeclType,
266 unsigned &Index,
267 InitListExpr *StructuredList,
268 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000269 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000270 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000271 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000272 InitListExpr *StructuredList,
273 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000274 void CheckReferenceType(const InitializedEntity &Entity,
275 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000276 unsigned &Index,
277 InitListExpr *StructuredList,
278 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000279 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000280 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000283 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000284 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000285 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000286 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000287 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000288 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000289 unsigned &StructuredIndex,
290 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000291 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000292 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000293 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000294 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000295 InitListExpr *StructuredList,
296 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000297 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000298 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000299 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000300 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000301 RecordDecl::field_iterator *NextField,
302 llvm::APSInt *NextElementIndex,
303 unsigned &Index,
304 InitListExpr *StructuredList,
305 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000306 bool FinishSubobjectInit,
307 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000308 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
309 QualType CurrentObjectType,
310 InitListExpr *StructuredList,
311 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000312 SourceRange InitRange,
313 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000314 void UpdateStructuredListElement(InitListExpr *StructuredList,
315 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000316 Expr *expr);
317 int numArrayElements(QualType DeclType);
318 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000319
Richard Smith454a7cd2014-06-03 08:26:00 +0000320 static ExprResult PerformEmptyInit(Sema &SemaRef,
321 SourceLocation Loc,
322 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000323 bool VerifyOnly,
324 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000325
326 // Explanation on the "FillWithNoInit" mode:
327 //
328 // Assume we have the following definitions (Case#1):
329 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
330 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
331 //
332 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
333 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
334 //
335 // But if we have (Case#2):
336 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
337 //
338 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
339 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
340 //
341 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
342 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
343 // initializers but with special "NoInitExpr" place holders, which tells the
344 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000345 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
346 const InitializedEntity &ParentEntity,
347 InitListExpr *ILE, bool &RequiresSecondPass,
348 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000349 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000351 InitListExpr *ILE, bool &RequiresSecondPass,
352 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000353 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000354 InitListExpr *ILE, bool &RequiresSecondPass,
355 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000356 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
357 Expr *InitExpr, FieldDecl *Field,
358 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000359 void CheckEmptyInitializable(const InitializedEntity &Entity,
360 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000361
Douglas Gregor85df8d82009-01-29 00:45:39 +0000362public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000363 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000364 InitListExpr *IL, QualType &T, bool VerifyOnly,
365 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000366 bool HadError() { return hadError; }
367
368 // @brief Retrieves the fully-structured initializer list used for
369 // semantic analysis and code generation.
370 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
371};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000372
Chris Lattner9ececce2009-02-24 22:48:58 +0000373} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000374
Richard Smith454a7cd2014-06-03 08:26:00 +0000375ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
376 SourceLocation Loc,
377 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000378 bool VerifyOnly,
379 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000380 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
381 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000382 MultiExprArg SubInit;
383 Expr *InitExpr;
384 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
385
386 // C++ [dcl.init.aggr]p7:
387 // If there are fewer initializer-clauses in the list than there are
388 // members in the aggregate, then each member not explicitly initialized
389 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000390 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
391 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
392 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000393 // C++1y / DR1070:
394 // shall be initialized [...] from an empty initializer list.
395 //
396 // We apply the resolution of this DR to C++11 but not C++98, since C++98
397 // does not have useful semantics for initialization from an init list.
398 // We treat this as copy-initialization, because aggregate initialization
399 // always performs copy-initialization on its elements.
400 //
401 // Only do this if we're initializing a class type, to avoid filling in
402 // the initializer list where possible.
403 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
404 InitListExpr(SemaRef.Context, Loc, None, Loc);
405 InitExpr->setType(SemaRef.Context.VoidTy);
406 SubInit = InitExpr;
407 Kind = InitializationKind::CreateCopy(Loc, Loc);
408 } else {
409 // C++03:
410 // shall be value-initialized.
411 }
412
413 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000414 // libstdc++4.6 marks the vector default constructor as explicit in
415 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
416 // stlport does so too. Look for std::__debug for libstdc++, and for
417 // std:: for stlport. This is effectively a compiler-side implementation of
418 // LWG2193.
419 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
420 InitializationSequence::FK_ExplicitConstructor) {
421 OverloadCandidateSet::iterator Best;
422 OverloadingResult O =
423 InitSeq.getFailedCandidateSet()
424 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
425 (void)O;
426 assert(O == OR_Success && "Inconsistent overload resolution");
427 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
428 CXXRecordDecl *R = CtorDecl->getParent();
429
430 if (CtorDecl->getMinRequiredArguments() == 0 &&
431 CtorDecl->isExplicit() && R->getDeclName() &&
432 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000433 bool IsInStd = false;
434 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000435 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000436 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
437 IsInStd = true;
438 }
439
440 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
441 .Cases("basic_string", "deque", "forward_list", true)
442 .Cases("list", "map", "multimap", "multiset", true)
443 .Cases("priority_queue", "queue", "set", "stack", true)
444 .Cases("unordered_map", "unordered_set", "vector", true)
445 .Default(false)) {
446 InitSeq.InitializeFrom(
447 SemaRef, Entity,
448 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000449 MultiExprArg(), /*TopLevelOfInitList=*/false,
450 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000451 // Emit a warning for this. System header warnings aren't shown
452 // by default, but people working on system headers should see it.
453 if (!VerifyOnly) {
454 SemaRef.Diag(CtorDecl->getLocation(),
455 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000456 if (Entity.getKind() == InitializedEntity::EK_Member)
457 SemaRef.Diag(Entity.getDecl()->getLocation(),
458 diag::note_used_in_initialization_here);
459 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
460 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000461 }
462 }
463 }
464 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000465 if (!InitSeq) {
466 if (!VerifyOnly) {
467 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
468 if (Entity.getKind() == InitializedEntity::EK_Member)
469 SemaRef.Diag(Entity.getDecl()->getLocation(),
470 diag::note_in_omitted_aggregate_initializer)
471 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000472 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
473 bool IsTrailingArrayNewMember =
474 Entity.getParent() &&
475 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000476 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000477 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
478 << Entity.getElementIndex();
479 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000480 }
481 return ExprError();
482 }
483
484 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
485 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
486}
487
488void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
489 SourceLocation Loc) {
490 assert(VerifyOnly &&
491 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000492 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
493 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000494 hadError = true;
495}
496
Richard Smith872307e2016-03-08 22:17:41 +0000497void InitListChecker::FillInEmptyInitForBase(
498 unsigned Init, const CXXBaseSpecifier &Base,
499 const InitializedEntity &ParentEntity, InitListExpr *ILE,
500 bool &RequiresSecondPass, bool FillWithNoInit) {
501 assert(Init < ILE->getNumInits() && "should have been expanded");
502
503 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
504 SemaRef.Context, &Base, false, &ParentEntity);
505
506 if (!ILE->getInit(Init)) {
507 ExprResult BaseInit =
508 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
509 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
Manman Ren073db022016-03-10 18:53:19 +0000510 /*VerifyOnly*/ false,
511 TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000512 if (BaseInit.isInvalid()) {
513 hadError = true;
514 return;
515 }
516
517 ILE->setInit(Init, BaseInit.getAs<Expr>());
518 } else if (InitListExpr *InnerILE =
519 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
520 FillInEmptyInitializations(BaseEntity, InnerILE,
521 RequiresSecondPass, FillWithNoInit);
522 } else if (DesignatedInitUpdateExpr *InnerDIUE =
523 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
524 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
525 RequiresSecondPass, /*FillWithNoInit =*/true);
526 }
527}
528
Richard Smith454a7cd2014-06-03 08:26:00 +0000529void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000530 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000532 bool &RequiresSecondPass,
533 bool FillWithNoInit) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000534 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000535 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000537 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000538
539 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
540 if (!RType->getDecl()->isUnion())
541 assert(Init < NumInits && "This ILE should have been expanded");
542
Douglas Gregor2bb07652009-12-22 00:05:34 +0000543 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000544 if (FillWithNoInit) {
545 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
546 if (Init < NumInits)
547 ILE->setInit(Init, Filler);
548 else
549 ILE->updateInit(SemaRef.Context, Init, Filler);
550 return;
551 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000552 // C++1y [dcl.init.aggr]p7:
553 // If there are fewer initializer-clauses in the list than there are
554 // members in the aggregate, then each member not explicitly initialized
555 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000556 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000557 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
558 if (DIE.isInvalid()) {
559 hadError = true;
560 return;
561 }
Richard Smith852c9db2013-04-20 22:23:05 +0000562 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000563 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000564 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000565 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000566 RequiresSecondPass = true;
567 }
568 return;
569 }
570
Douglas Gregor2bb07652009-12-22 00:05:34 +0000571 if (Field->getType()->isReferenceType()) {
572 // C++ [dcl.init.aggr]p9:
573 // If an incomplete or empty initializer-list leaves a
574 // member of reference type uninitialized, the program is
575 // ill-formed.
576 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
577 << Field->getType()
578 << ILE->getSyntacticForm()->getSourceRange();
579 SemaRef.Diag(Field->getLocation(),
580 diag::note_uninit_reference_member);
581 hadError = true;
582 return;
583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Richard Smith454a7cd2014-06-03 08:26:00 +0000585 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000586 /*VerifyOnly*/false,
587 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000588 if (MemberInit.isInvalid()) {
589 hadError = true;
590 return;
591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
Douglas Gregor2bb07652009-12-22 00:05:34 +0000593 if (hadError) {
594 // Do nothing
595 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000596 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000597 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
598 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000599 // extend the initializer list to include the constructor
600 // call and make a note that we'll need to take another pass
601 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000602 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000603 RequiresSecondPass = true;
604 }
605 } else if (InitListExpr *InnerILE
606 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000607 FillInEmptyInitializations(MemberEntity, InnerILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000608 RequiresSecondPass, FillWithNoInit);
609 else if (DesignatedInitUpdateExpr *InnerDIUE
610 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
611 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
612 RequiresSecondPass, /*FillWithNoInit =*/ true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000613}
614
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000615/// Recursively replaces NULL values within the given initializer list
616/// with expressions that perform value-initialization of the
617/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618void
Richard Smith454a7cd2014-06-03 08:26:00 +0000619InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000620 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000621 bool &RequiresSecondPass,
622 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000623 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000624 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000625
Richard Smith382bc512017-02-23 22:41:47 +0000626 // A transparent ILE is not performing aggregate initialization and should
627 // not be filled in.
628 if (ILE->isTransparent())
629 return;
630
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000631 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000632 const RecordDecl *RDecl = RType->getDecl();
633 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000634 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000635 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000636 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
637 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000638 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000639 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000640 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
641 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000642 break;
643 }
644 }
645 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000646 // The fields beyond ILE->getNumInits() are default initialized, so in
647 // order to leave them uninitialized, the ILE is expanded and the extra
648 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000649 unsigned NumElems = numStructUnionElements(ILE->getType());
650 if (RDecl->hasFlexibleArrayMember())
651 ++NumElems;
652 if (ILE->getNumInits() < NumElems)
653 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000654
Douglas Gregor2bb07652009-12-22 00:05:34 +0000655 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000656
657 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
658 for (auto &Base : CXXRD->bases()) {
659 if (hadError)
660 return;
661
662 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
663 FillWithNoInit);
664 ++Init;
665 }
666 }
667
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000668 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000669 if (Field->isUnnamedBitfield())
670 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000671
Douglas Gregor2bb07652009-12-22 00:05:34 +0000672 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000673 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000674
Yunzhong Gaocb779302015-06-10 00:27:52 +0000675 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
676 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000677 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000678 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000679
Douglas Gregor2bb07652009-12-22 00:05:34 +0000680 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000681
Douglas Gregor2bb07652009-12-22 00:05:34 +0000682 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000683 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000684 break;
685 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000686 }
687
688 return;
Mike Stump11289f42009-09-09 15:08:12 +0000689 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000690
691 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Douglas Gregor723796a2009-12-16 06:35:08 +0000693 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000694 unsigned NumInits = ILE->getNumInits();
695 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000696 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000697 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000698 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000699 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000700 // For an array new with an unknown bound, ask for one additional element
701 // in order to populate the array filler.
702 if (Entity.isVariableLengthArrayNew())
703 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000705 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000706 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000707 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000708 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000710 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000711 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000712 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000713
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000714 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000715 if (hadError)
716 return;
717
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000718 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
719 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000720 ElementEntity.setElementIndex(Init);
721
Craig Topperc3ec1492014-05-26 06:22:03 +0000722 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000723 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
724 ILE->setInit(Init, ILE->getArrayFiller());
725 else if (!InitExpr && !ILE->hasArrayFiller()) {
726 Expr *Filler = nullptr;
727
728 if (FillWithNoInit)
729 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
730 else {
731 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
732 ElementEntity,
Manman Ren073db022016-03-10 18:53:19 +0000733 /*VerifyOnly*/false,
734 TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000735 if (ElementInit.isInvalid()) {
736 hadError = true;
737 return;
738 }
739
740 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000741 }
742
743 if (hadError) {
744 // Do nothing
745 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000746 // For arrays, just set the expression used for value-initialization
747 // of the "holes" in the array.
748 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000749 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000750 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000751 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000752 } else {
753 // For arrays, just set the expression used for value-initialization
754 // of the rest of elements and exit.
755 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000756 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000757 return;
758 }
759
Yunzhong Gaocb779302015-06-10 00:27:52 +0000760 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000761 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000762 // extend the initializer list to include the constructor
763 // call and make a note that we'll need to take another pass
764 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000765 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000766 RequiresSecondPass = true;
767 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000768 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000769 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000770 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000771 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
772 FillWithNoInit);
773 else if (DesignatedInitUpdateExpr *InnerDIUE
774 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
775 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
776 RequiresSecondPass, /*FillWithNoInit =*/ true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000777 }
778}
779
Douglas Gregor723796a2009-12-16 06:35:08 +0000780InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000781 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000782 bool VerifyOnly,
783 bool TreatUnavailableAsInvalid)
784 : SemaRef(S), VerifyOnly(VerifyOnly),
785 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000786 // FIXME: Check that IL isn't already the semantic form of some other
787 // InitListExpr. If it is, we'd create a broken AST.
788
Steve Narofff8ecff22008-05-01 22:18:59 +0000789 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000790
Richard Smith4e0d2e42013-09-20 20:10:22 +0000791 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000792 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000793 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000794 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000795
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000797 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000798 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000799 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000800 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000801 RequiresSecondPass);
802 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000803}
804
805int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000806 // FIXME: use a proper constant
807 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000808 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000809 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000810 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
811 }
812 return maxElements;
813}
814
815int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000816 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000817 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000818 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
819 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000820 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000821 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000822 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000823
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000824 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000825 return std::min(InitializableMembers, 1);
826 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000827}
828
Richard Smith4e0d2e42013-09-20 20:10:22 +0000829/// Check whether the range of the initializer \p ParentIList from element
830/// \p Index onwards can be used to initialize an object of type \p T. Update
831/// \p Index to indicate how many elements of the list were consumed.
832///
833/// This also fills in \p StructuredList, from element \p StructuredIndex
834/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000835void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000836 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000837 QualType T, unsigned &Index,
838 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000839 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000840 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000841
Steve Narofff8ecff22008-05-01 22:18:59 +0000842 if (T->isArrayType())
843 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000844 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000845 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000846 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000847 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000848 else
David Blaikie83d382b2011-09-23 05:06:16 +0000849 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000850
Eli Friedmane0f832b2008-05-25 13:49:22 +0000851 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000852 if (!VerifyOnly)
853 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
854 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000855 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000856 hadError = true;
857 return;
858 }
859
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000860 // Build a structured initializer list corresponding to this subobject.
861 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000862 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
863 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000864 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000865 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000866 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000867
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000868 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000869 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000871 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000872 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000873 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000874
Richard Smithde229232013-06-06 11:41:05 +0000875 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000876 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000877
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000878 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000879 // Update the structured sub-object initializer so that it's ending
880 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000881 if (EndIndex < ParentIList->getNumInits() &&
882 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000883 SourceLocation EndLoc
884 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
885 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000888 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000889 if ((T->isArrayType() || T->isRecordType()) &&
890 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts())) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000891 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000892 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000893 << StructuredSubobjectInitList->getSourceRange()
894 << FixItHint::CreateInsertion(
895 StructuredSubobjectInitList->getLocStart(), "{")
896 << FixItHint::CreateInsertion(
897 SemaRef.getLocForEndOfToken(
898 StructuredSubobjectInitList->getLocEnd()),
899 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000900 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000901 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000902}
903
Richard Smith420fa122015-02-12 01:50:05 +0000904/// Warn that \p Entity was of scalar type and was initialized by a
905/// single-element braced initializer list.
906static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
907 SourceRange Braces) {
908 // Don't warn during template instantiation. If the initialization was
909 // non-dependent, we warned during the initial parse; otherwise, the
910 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000911 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000912 return;
913
914 unsigned DiagID = 0;
915
916 switch (Entity.getKind()) {
917 case InitializedEntity::EK_VectorElement:
918 case InitializedEntity::EK_ComplexElement:
919 case InitializedEntity::EK_ArrayElement:
920 case InitializedEntity::EK_Parameter:
921 case InitializedEntity::EK_Parameter_CF_Audited:
922 case InitializedEntity::EK_Result:
923 // Extra braces here are suspicious.
924 DiagID = diag::warn_braces_around_scalar_init;
925 break;
926
927 case InitializedEntity::EK_Member:
928 // Warn on aggregate initialization but not on ctor init list or
929 // default member initializer.
930 if (Entity.getParent())
931 DiagID = diag::warn_braces_around_scalar_init;
932 break;
933
934 case InitializedEntity::EK_Variable:
935 case InitializedEntity::EK_LambdaCapture:
936 // No warning, might be direct-list-initialization.
937 // FIXME: Should we warn for copy-list-initialization in these cases?
938 break;
939
940 case InitializedEntity::EK_New:
941 case InitializedEntity::EK_Temporary:
942 case InitializedEntity::EK_CompoundLiteralInit:
943 // No warning, braces are part of the syntax of the underlying construct.
944 break;
945
946 case InitializedEntity::EK_RelatedResult:
947 // No warning, we already warned when initializing the result.
948 break;
949
950 case InitializedEntity::EK_Exception:
951 case InitializedEntity::EK_Base:
952 case InitializedEntity::EK_Delegating:
953 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +0000954 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +0000955 case InitializedEntity::EK_Binding:
Richard Smith420fa122015-02-12 01:50:05 +0000956 llvm_unreachable("unexpected braced scalar init");
957 }
958
959 if (DiagID) {
960 S.Diag(Braces.getBegin(), DiagID)
961 << Braces
962 << FixItHint::CreateRemoval(Braces.getBegin())
963 << FixItHint::CreateRemoval(Braces.getEnd());
964 }
965}
966
Richard Smith4e0d2e42013-09-20 20:10:22 +0000967/// Check whether the initializer \p IList (that was written with explicit
968/// braces) can be used to initialize an object of type \p T.
969///
970/// This also fills in \p StructuredList with the fully-braced, desugared
971/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000972void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000973 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000974 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000975 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000976 if (!VerifyOnly) {
977 SyntacticToSemantic[IList] = StructuredList;
978 StructuredList->setSyntacticForm(IList);
979 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000980
981 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000982 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000983 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000984 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000985 QualType ExprTy = T;
986 if (!ExprTy->isArrayType())
987 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000988 IList->setType(ExprTy);
989 StructuredList->setType(ExprTy);
990 }
Eli Friedman85f54972008-05-25 13:22:35 +0000991 if (hadError)
992 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000993
Eli Friedman85f54972008-05-25 13:22:35 +0000994 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000995 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000996 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000997 if (SemaRef.getLangOpts().CPlusPlus ||
998 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000999 IList->getType()->isVectorType())) {
1000 hadError = true;
1001 }
1002 return;
1003 }
1004
Eli Friedmanbd327452009-05-29 20:20:05 +00001005 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001006 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1007 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001008 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001009 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001010 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001011 hadError = true;
1012 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001013 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +00001014 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +00001015 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001016 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001017 // Don't complain for incomplete types, since we'll get an error
1018 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001019 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001020 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001021 CurrentObjectType->isArrayType()? 0 :
1022 CurrentObjectType->isVectorType()? 1 :
1023 CurrentObjectType->isScalarType()? 2 :
1024 CurrentObjectType->isUnionType()? 3 :
1025 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001026
Richard Smith1b98ccc2014-07-19 01:39:17 +00001027 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001028 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001029 DK = diag::err_excess_initializers;
1030 hadError = true;
1031 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001032 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001033 DK = diag::err_excess_initializers;
1034 hadError = true;
1035 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001036
Chris Lattnerb0912a52009-02-24 22:50:46 +00001037 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001038 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001039 }
1040 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001041
Richard Smith420fa122015-02-12 01:50:05 +00001042 if (!VerifyOnly && T->isScalarType() &&
1043 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1044 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +00001045}
1046
Anders Carlsson6cabf312010-01-23 23:23:01 +00001047void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001048 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001049 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001050 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001051 unsigned &Index,
1052 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001053 unsigned &StructuredIndex,
1054 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001055 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1056 // Explicitly braced initializer for complex type can be real+imaginary
1057 // parts.
1058 CheckComplexType(Entity, IList, DeclType, Index,
1059 StructuredList, StructuredIndex);
1060 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001061 CheckScalarType(Entity, IList, DeclType, Index,
1062 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001063 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001065 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001066 } else if (DeclType->isRecordType()) {
1067 assert(DeclType->isAggregateType() &&
1068 "non-aggregate records should be handed in CheckSubElementType");
1069 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001070 auto Bases =
1071 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1072 CXXRecordDecl::base_class_iterator());
1073 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1074 Bases = CXXRD->bases();
1075 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1076 SubobjectIsDesignatorContext, Index, StructuredList,
1077 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001078 } else if (DeclType->isArrayType()) {
1079 llvm::APSInt Zero(
1080 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1081 false);
1082 CheckArrayType(Entity, IList, DeclType, Zero,
1083 SubobjectIsDesignatorContext, Index,
1084 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001085 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1086 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001087 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001088 if (!VerifyOnly)
1089 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1090 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001091 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001092 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001093 CheckReferenceType(Entity, IList, DeclType, Index,
1094 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001095 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001096 if (!VerifyOnly)
1097 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1098 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001099 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001100 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001101 if (!VerifyOnly)
1102 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1103 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001104 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001105 }
1106}
1107
Anders Carlsson6cabf312010-01-23 23:23:01 +00001108void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001109 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001110 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001111 unsigned &Index,
1112 InitListExpr *StructuredList,
1113 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001114 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001115
1116 if (ElemType->isReferenceType())
1117 return CheckReferenceType(Entity, IList, ElemType, Index,
1118 StructuredList, StructuredIndex);
1119
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001120 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001121 if (SubInitList->getNumInits() == 1 &&
1122 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1123 SIF_None) {
1124 expr = SubInitList->getInit(0);
1125 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001126 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001127 = getStructuredSubobjectInit(IList, Index, ElemType,
1128 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001129 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001130 CheckExplicitInitList(Entity, SubInitList, ElemType,
1131 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001132
1133 if (!hadError && !VerifyOnly) {
1134 bool RequiresSecondPass = false;
1135 FillInEmptyInitializations(Entity, InnerStructuredList,
1136 RequiresSecondPass);
1137 if (RequiresSecondPass && !hadError)
1138 FillInEmptyInitializations(Entity, InnerStructuredList,
1139 RequiresSecondPass);
1140 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001141 ++StructuredIndex;
1142 ++Index;
1143 return;
1144 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001145 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001146 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001147 // This happens during template instantiation when we see an InitListExpr
1148 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001149 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001150 "found implicit initialization for the wrong type");
1151 if (!VerifyOnly)
1152 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1153 ++Index;
1154 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001155 }
1156
Richard Smith3c567fc2015-02-12 01:55:09 +00001157 if (SemaRef.getLangOpts().CPlusPlus) {
1158 // C++ [dcl.init.aggr]p2:
1159 // Each member is copy-initialized from the corresponding
1160 // initializer-clause.
1161
1162 // FIXME: Better EqualLoc?
1163 InitializationKind Kind =
1164 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1165 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1166 /*TopLevelOfInitList*/ true);
1167
1168 // C++14 [dcl.init.aggr]p13:
1169 // If the assignment-expression can initialize a member, the member is
1170 // initialized. Otherwise [...] brace elision is assumed
1171 //
1172 // Brace elision is never performed if the element is not an
1173 // assignment-expression.
1174 if (Seq || isa<InitListExpr>(expr)) {
1175 if (!VerifyOnly) {
1176 ExprResult Result =
1177 Seq.Perform(SemaRef, Entity, Kind, expr);
1178 if (Result.isInvalid())
1179 hadError = true;
1180
1181 UpdateStructuredListElement(StructuredList, StructuredIndex,
1182 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001183 } else if (!Seq)
1184 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001185 ++Index;
1186 return;
1187 }
1188
1189 // Fall through for subaggregate initialization
1190 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1191 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001192 return CheckScalarType(Entity, IList, ElemType, Index,
1193 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001194 } else if (const ArrayType *arrayType =
1195 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001196 // arrayType can be incomplete if we're initializing a flexible
1197 // array member. There's nothing we can do with the completed
1198 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001199
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001200 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001201 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001202 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1203 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001204 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001205 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001206 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001207 }
John McCall5decec92011-02-21 07:57:55 +00001208
1209 // Fall through for subaggregate initialization.
1210
John McCall5decec92011-02-21 07:57:55 +00001211 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001212 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001213 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001214
John McCall5decec92011-02-21 07:57:55 +00001215 // C99 6.7.8p13:
1216 //
1217 // The initializer for a structure or union object that has
1218 // automatic storage duration shall be either an initializer
1219 // list as described below, or a single expression that has
1220 // compatible structure or union type. In the latter case, the
1221 // initial value of the object, including unnamed members, is
1222 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001223 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001224 if (SemaRef.CheckSingleAssignmentConstraints(
1225 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001226 if (ExprRes.isInvalid())
1227 hadError = true;
1228 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001229 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001230 if (ExprRes.isInvalid())
1231 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001232 }
1233 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001234 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001235 ++Index;
1236 return;
1237 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001238 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001239 // Fall through for subaggregate initialization
1240 }
1241
1242 // C++ [dcl.init.aggr]p12:
1243 //
1244 // [...] Otherwise, if the member is itself a non-empty
1245 // subaggregate, brace elision is assumed and the initializer is
1246 // considered for the initialization of the first member of
1247 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001248 // OpenCL vector initializer is handled elsewhere.
1249 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1250 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001251 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1252 StructuredIndex);
1253 ++StructuredIndex;
1254 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001255 if (!VerifyOnly) {
1256 // We cannot initialize this element, so let
1257 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001258 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001259 /*TopLevelOfInitList=*/true);
1260 }
John McCall5decec92011-02-21 07:57:55 +00001261 hadError = true;
1262 ++Index;
1263 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001264 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001265}
1266
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001267void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1268 InitListExpr *IList, QualType DeclType,
1269 unsigned &Index,
1270 InitListExpr *StructuredList,
1271 unsigned &StructuredIndex) {
1272 assert(Index == 0 && "Index in explicit init list must be zero");
1273
1274 // As an extension, clang supports complex initializers, which initialize
1275 // a complex number component-wise. When an explicit initializer list for
1276 // a complex number contains two two initializers, this extension kicks in:
1277 // it exepcts the initializer list to contain two elements convertible to
1278 // the element type of the complex type. The first element initializes
1279 // the real part, and the second element intitializes the imaginary part.
1280
1281 if (IList->getNumInits() != 2)
1282 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1283 StructuredIndex);
1284
1285 // This is an extension in C. (The builtin _Complex type does not exist
1286 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001287 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001288 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1289 << IList->getSourceRange();
1290
1291 // Initialize the complex number.
1292 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1293 InitializedEntity ElementEntity =
1294 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1295
1296 for (unsigned i = 0; i < 2; ++i) {
1297 ElementEntity.setElementIndex(Index);
1298 CheckSubElementType(ElementEntity, IList, elementType, Index,
1299 StructuredList, StructuredIndex);
1300 }
1301}
1302
Anders Carlsson6cabf312010-01-23 23:23:01 +00001303void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001304 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001305 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001306 InitListExpr *StructuredList,
1307 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001308 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001309 if (!VerifyOnly)
1310 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001311 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001312 diag::warn_cxx98_compat_empty_scalar_initializer :
1313 diag::err_empty_scalar_initializer)
1314 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001315 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001316 ++Index;
1317 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001318 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001319 }
John McCall643169b2010-11-11 00:46:36 +00001320
1321 Expr *expr = IList->getInit(Index);
1322 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001323 // FIXME: This is invalid, and accepting it causes overload resolution
1324 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001325 if (!VerifyOnly)
1326 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001327 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001328 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001329
1330 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1331 StructuredIndex);
1332 return;
1333 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001334 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001335 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001336 diag::err_designator_for_scalar_init)
1337 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001338 hadError = true;
1339 ++Index;
1340 ++StructuredIndex;
1341 return;
1342 }
1343
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001344 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001345 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001346 hadError = true;
1347 ++Index;
1348 return;
1349 }
1350
John McCall643169b2010-11-11 00:46:36 +00001351 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001352 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001353 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001354
Craig Topperc3ec1492014-05-26 06:22:03 +00001355 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001356
1357 if (Result.isInvalid())
1358 hadError = true; // types weren't compatible.
1359 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001360 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361
John McCall643169b2010-11-11 00:46:36 +00001362 if (ResultExpr != expr) {
1363 // The type was promoted, update initializer list.
1364 IList->setInit(Index, ResultExpr);
1365 }
1366 }
1367 if (hadError)
1368 ++StructuredIndex;
1369 else
1370 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1371 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001372}
1373
Anders Carlsson6cabf312010-01-23 23:23:01 +00001374void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1375 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001376 unsigned &Index,
1377 InitListExpr *StructuredList,
1378 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001379 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001380 // FIXME: It would be wonderful if we could point at the actual member. In
1381 // general, it would be useful to pass location information down the stack,
1382 // so that we know the location (or decl) of the "current object" being
1383 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001384 if (!VerifyOnly)
1385 SemaRef.Diag(IList->getLocStart(),
1386 diag::err_init_reference_member_uninitialized)
1387 << DeclType
1388 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001389 hadError = true;
1390 ++Index;
1391 ++StructuredIndex;
1392 return;
1393 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001394
1395 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001396 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001397 if (!VerifyOnly)
1398 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1399 << DeclType << IList->getSourceRange();
1400 hadError = true;
1401 ++Index;
1402 ++StructuredIndex;
1403 return;
1404 }
1405
1406 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001407 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001408 hadError = true;
1409 ++Index;
1410 return;
1411 }
1412
1413 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001414 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1415 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001416
1417 if (Result.isInvalid())
1418 hadError = true;
1419
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001420 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001421 IList->setInit(Index, expr);
1422
1423 if (hadError)
1424 ++StructuredIndex;
1425 else
1426 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1427 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001428}
1429
Anders Carlsson6cabf312010-01-23 23:23:01 +00001430void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001431 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001432 unsigned &Index,
1433 InitListExpr *StructuredList,
1434 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001435 const VectorType *VT = DeclType->getAs<VectorType>();
1436 unsigned maxElements = VT->getNumElements();
1437 unsigned numEltsInit = 0;
1438 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001439
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001440 if (Index >= IList->getNumInits()) {
1441 // Make sure the element type can be value-initialized.
1442 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001443 CheckEmptyInitializable(
1444 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1445 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001446 return;
1447 }
1448
David Blaikiebbafb8a2012-03-11 07:00:24 +00001449 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001450 // If the initializing element is a vector, try to copy-initialize
1451 // instead of breaking it apart (which is doomed to failure anyway).
1452 Expr *Init = IList->getInit(Index);
1453 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001454 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001455 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001456 hadError = true;
1457 ++Index;
1458 return;
1459 }
1460
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001461 ExprResult Result =
1462 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1463 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001464
Craig Topperc3ec1492014-05-26 06:22:03 +00001465 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001466 if (Result.isInvalid())
1467 hadError = true; // types weren't compatible.
1468 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001469 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470
John McCall6a16b2f2010-10-30 00:11:39 +00001471 if (ResultExpr != Init) {
1472 // The type was promoted, update initializer list.
1473 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001474 }
1475 }
John McCall6a16b2f2010-10-30 00:11:39 +00001476 if (hadError)
1477 ++StructuredIndex;
1478 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001479 UpdateStructuredListElement(StructuredList, StructuredIndex,
1480 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001481 ++Index;
1482 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001483 }
Mike Stump11289f42009-09-09 15:08:12 +00001484
John McCall6a16b2f2010-10-30 00:11:39 +00001485 InitializedEntity ElementEntity =
1486 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
John McCall6a16b2f2010-10-30 00:11:39 +00001488 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1489 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001490 if (Index >= IList->getNumInits()) {
1491 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001492 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001493 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
John McCall6a16b2f2010-10-30 00:11:39 +00001496 ElementEntity.setElementIndex(Index);
1497 CheckSubElementType(ElementEntity, IList, elementType, Index,
1498 StructuredList, StructuredIndex);
1499 }
James Molloy9eef2652014-06-20 14:35:13 +00001500
1501 if (VerifyOnly)
1502 return;
1503
1504 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1505 const VectorType *T = Entity.getType()->getAs<VectorType>();
1506 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1507 T->getVectorKind() == VectorType::NeonPolyVector)) {
1508 // The ability to use vector initializer lists is a GNU vector extension
1509 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1510 // endian machines it works fine, however on big endian machines it
1511 // exhibits surprising behaviour:
1512 //
1513 // uint32x2_t x = {42, 64};
1514 // return vget_lane_u32(x, 0); // Will return 64.
1515 //
1516 // Because of this, explicitly call out that it is non-portable.
1517 //
1518 SemaRef.Diag(IList->getLocStart(),
1519 diag::warn_neon_vector_initializer_non_portable);
1520
1521 const char *typeCode;
1522 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1523
1524 if (elementType->isFloatingType())
1525 typeCode = "f";
1526 else if (elementType->isSignedIntegerType())
1527 typeCode = "s";
1528 else if (elementType->isUnsignedIntegerType())
1529 typeCode = "u";
1530 else
1531 llvm_unreachable("Invalid element type!");
1532
1533 SemaRef.Diag(IList->getLocStart(),
1534 SemaRef.Context.getTypeSize(VT) > 64 ?
1535 diag::note_neon_vector_initializer_non_portable_q :
1536 diag::note_neon_vector_initializer_non_portable)
1537 << typeCode << typeSize;
1538 }
1539
John McCall6a16b2f2010-10-30 00:11:39 +00001540 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001541 }
John McCall6a16b2f2010-10-30 00:11:39 +00001542
1543 InitializedEntity ElementEntity =
1544 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001545
John McCall6a16b2f2010-10-30 00:11:39 +00001546 // OpenCL initializers allows vectors to be constructed from vectors.
1547 for (unsigned i = 0; i < maxElements; ++i) {
1548 // Don't attempt to go past the end of the init list
1549 if (Index >= IList->getNumInits())
1550 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551
John McCall6a16b2f2010-10-30 00:11:39 +00001552 ElementEntity.setElementIndex(Index);
1553
1554 QualType IType = IList->getInit(Index)->getType();
1555 if (!IType->isVectorType()) {
1556 CheckSubElementType(ElementEntity, IList, elementType, Index,
1557 StructuredList, StructuredIndex);
1558 ++numEltsInit;
1559 } else {
1560 QualType VecType;
1561 const VectorType *IVT = IType->getAs<VectorType>();
1562 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001563
John McCall6a16b2f2010-10-30 00:11:39 +00001564 if (IType->isExtVectorType())
1565 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1566 else
1567 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001568 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001569 CheckSubElementType(ElementEntity, IList, VecType, Index,
1570 StructuredList, StructuredIndex);
1571 numEltsInit += numIElts;
1572 }
1573 }
1574
1575 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001576 if (numEltsInit != maxElements) {
1577 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001578 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001579 diag::err_vector_incorrect_num_initializers)
1580 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1581 hadError = true;
1582 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001583}
1584
Anders Carlsson6cabf312010-01-23 23:23:01 +00001585void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001586 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001587 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001588 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001589 unsigned &Index,
1590 InitListExpr *StructuredList,
1591 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001592 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1593
Steve Narofff8ecff22008-05-01 22:18:59 +00001594 // Check for the special-case of initializing an array with a string.
1595 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001596 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1597 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001598 // We place the string literal directly into the resulting
1599 // initializer list. This is the only place where the structure
1600 // of the structured initializer list doesn't match exactly,
1601 // because doing so would involve allocating one character
1602 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001603 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001604 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1605 UpdateStructuredListElement(StructuredList, StructuredIndex,
1606 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001607 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1608 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001609 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001610 return;
1611 }
1612 }
John McCall66884dd2011-02-21 07:22:22 +00001613 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001614 // Check for VLAs; in standard C it would be possible to check this
1615 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1616 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001617 if (!VerifyOnly)
1618 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1619 diag::err_variable_object_no_init)
1620 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001621 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001622 ++Index;
1623 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001624 return;
1625 }
1626
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001627 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001628 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1629 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001630 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001631 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001632 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001633 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001634 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001635 maxElementsKnown = true;
1636 }
1637
John McCall66884dd2011-02-21 07:22:22 +00001638 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001639 while (Index < IList->getNumInits()) {
1640 Expr *Init = IList->getInit(Index);
1641 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001642 // If we're not the subobject that matches up with the '{' for
1643 // the designator, we shouldn't be handling the
1644 // designator. Return immediately.
1645 if (!SubobjectIsDesignatorContext)
1646 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001647
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001648 // Handle this designated initializer. elementIndex will be
1649 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001650 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001651 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001652 StructuredList, StructuredIndex, true,
1653 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001654 hadError = true;
1655 continue;
1656 }
1657
Douglas Gregor033d1252009-01-23 16:54:12 +00001658 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001659 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001660 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001661 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001662 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001663
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001664 // If the array is of incomplete type, keep track of the number of
1665 // elements in the initializer.
1666 if (!maxElementsKnown && elementIndex > maxElements)
1667 maxElements = elementIndex;
1668
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001669 continue;
1670 }
1671
1672 // If we know the maximum number of elements, and we've already
1673 // hit it, stop consuming elements in the initializer list.
1674 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001675 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001676
Anders Carlsson6cabf312010-01-23 23:23:01 +00001677 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001679 Entity);
1680 // Check this element.
1681 CheckSubElementType(ElementEntity, IList, elementType, Index,
1682 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001683 ++elementIndex;
1684
1685 // If the array is of incomplete type, keep track of the number of
1686 // elements in the initializer.
1687 if (!maxElementsKnown && elementIndex > maxElements)
1688 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001689 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001690 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001691 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001692 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001693 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001694 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001695 // Sizing an array implicitly to zero is not allowed by ISO C,
1696 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001697 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001698 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001699 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001700
Mike Stump11289f42009-09-09 15:08:12 +00001701 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001702 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001703 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001704 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001705 // If there are any members of the array that get value-initialized, check
1706 // that is possible. That happens if we know the bound and don't have
1707 // enough elements, or if we're performing an array new with an unknown
1708 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001709 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001710 if ((maxElementsKnown && elementIndex < maxElements) ||
1711 Entity.isVariableLengthArrayNew())
Richard Smith454a7cd2014-06-03 08:26:00 +00001712 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1713 SemaRef.Context, 0, Entity),
1714 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001715 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001716}
1717
Eli Friedman3fa64df2011-08-23 22:24:57 +00001718bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1719 Expr *InitExpr,
1720 FieldDecl *Field,
1721 bool TopLevelObject) {
1722 // Handle GNU flexible array initializers.
1723 unsigned FlexArrayDiag;
1724 if (isa<InitListExpr>(InitExpr) &&
1725 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1726 // Empty flexible array init always allowed as an extension
1727 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001728 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001729 // Disallow flexible array init in C++; it is not required for gcc
1730 // compatibility, and it needs work to IRGen correctly in general.
1731 FlexArrayDiag = diag::err_flexible_array_init;
1732 } else if (!TopLevelObject) {
1733 // Disallow flexible array init on non-top-level object
1734 FlexArrayDiag = diag::err_flexible_array_init;
1735 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1736 // Disallow flexible array init on anything which is not a variable.
1737 FlexArrayDiag = diag::err_flexible_array_init;
1738 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1739 // Disallow flexible array init on local variables.
1740 FlexArrayDiag = diag::err_flexible_array_init;
1741 } else {
1742 // Allow other cases.
1743 FlexArrayDiag = diag::ext_flexible_array_init;
1744 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001745
1746 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001747 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001748 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001749 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001750 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1751 << Field;
1752 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001753
1754 return FlexArrayDiag != diag::ext_flexible_array_init;
1755}
1756
Richard Smith872307e2016-03-08 22:17:41 +00001757void InitListChecker::CheckStructUnionTypes(
1758 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1759 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1760 bool SubobjectIsDesignatorContext, unsigned &Index,
1761 InitListExpr *StructuredList, unsigned &StructuredIndex,
1762 bool TopLevelObject) {
1763 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001764
Eli Friedman23a9e312008-05-19 19:16:24 +00001765 // If the record is invalid, some of it's members are invalid. To avoid
1766 // confusion, we forgo checking the intializer for the entire record.
1767 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001768 // Assume it was supposed to consume a single initializer.
1769 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001770 hadError = true;
1771 return;
Mike Stump11289f42009-09-09 15:08:12 +00001772 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001773
1774 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001775 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001776
1777 // If there's a default initializer, use it.
1778 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1779 if (VerifyOnly)
1780 return;
1781 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1782 Field != FieldEnd; ++Field) {
1783 if (Field->hasInClassInitializer()) {
1784 StructuredList->setInitializedFieldInUnion(*Field);
1785 // FIXME: Actually build a CXXDefaultInitExpr?
1786 return;
1787 }
1788 }
1789 }
1790
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001791 // Value-initialize the first member of the union that isn't an unnamed
1792 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001793 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1794 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001795 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001796 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001797 CheckEmptyInitializable(
1798 InitializedEntity::InitializeMember(*Field, &Entity),
1799 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001800 else
David Blaikie40ed2972012-06-06 20:45:41 +00001801 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001802 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001803 }
1804 }
1805 return;
1806 }
1807
Richard Smith872307e2016-03-08 22:17:41 +00001808 bool InitializedSomething = false;
1809
1810 // If we have any base classes, they are initialized prior to the fields.
1811 for (auto &Base : Bases) {
1812 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1813 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1814
1815 // Designated inits always initialize fields, so if we see one, all
1816 // remaining base classes have no explicit initializer.
1817 if (Init && isa<DesignatedInitExpr>(Init))
1818 Init = nullptr;
1819
1820 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1821 SemaRef.Context, &Base, false, &Entity);
1822 if (Init) {
1823 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1824 StructuredList, StructuredIndex);
1825 InitializedSomething = true;
1826 } else if (VerifyOnly) {
1827 CheckEmptyInitializable(BaseEntity, InitLoc);
1828 }
1829 }
1830
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001831 // If structDecl is a forward declaration, this loop won't do
1832 // anything except look at designated initializers; That's okay,
1833 // because an error should get printed out elsewhere. It might be
1834 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001835 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001836 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001837 bool CheckForMissingFields =
1838 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1839
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001840 while (Index < IList->getNumInits()) {
1841 Expr *Init = IList->getInit(Index);
1842
1843 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001844 // If we're not the subobject that matches up with the '{' for
1845 // the designator, we shouldn't be handling the
1846 // designator. Return immediately.
1847 if (!SubobjectIsDesignatorContext)
1848 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001849
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001850 // Handle this designated initializer. Field will be updated to
1851 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001852 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001853 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001854 StructuredList, StructuredIndex,
1855 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001856 hadError = true;
1857
Douglas Gregora9add4e2009-02-12 19:00:39 +00001858 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001859
1860 // Disable check for missing fields when designators are used.
1861 // This matches gcc behaviour.
1862 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001863 continue;
1864 }
1865
1866 if (Field == FieldEnd) {
1867 // We've run out of fields. We're done.
1868 break;
1869 }
1870
Douglas Gregora9add4e2009-02-12 19:00:39 +00001871 // We've already initialized a member of a union. We're done.
1872 if (InitializedSomething && DeclType->isUnionType())
1873 break;
1874
Douglas Gregor91f84212008-12-11 16:49:14 +00001875 // If we've hit the flexible array member at the end, we're done.
1876 if (Field->getType()->isIncompleteArrayType())
1877 break;
1878
Douglas Gregor51695702009-01-29 16:53:55 +00001879 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001880 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001881 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001882 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001883 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001884
Douglas Gregora82064c2011-06-29 21:51:31 +00001885 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001886 bool InvalidUse;
1887 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00001888 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001889 else
David Blaikie40ed2972012-06-06 20:45:41 +00001890 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001891 IList->getInit(Index)->getLocStart());
1892 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001893 ++Index;
1894 ++Field;
1895 hadError = true;
1896 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001897 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001898
Anders Carlsson6cabf312010-01-23 23:23:01 +00001899 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001900 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001901 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1902 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001903 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001904
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001905 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001906 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001907 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001908 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001909
1910 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001911 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001912
John McCalle40b58e2010-03-11 19:32:38 +00001913 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001914 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1915 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1916 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001917 // It is possible we have one or more unnamed bitfields remaining.
1918 // Find first (if any) named field and emit warning.
1919 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1920 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001921 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001922 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001923 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001924 break;
1925 }
1926 }
1927 }
1928
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001929 // Check that any remaining fields can be value-initialized.
1930 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1931 !Field->getType()->isIncompleteArrayType()) {
1932 // FIXME: Should check for holes left by designated initializers too.
1933 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001934 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001935 CheckEmptyInitializable(
1936 InitializedEntity::InitializeMember(*Field, &Entity),
1937 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001938 }
1939 }
1940
Mike Stump11289f42009-09-09 15:08:12 +00001941 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001942 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001943 return;
1944
David Blaikie40ed2972012-06-06 20:45:41 +00001945 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001946 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001947 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001948 ++Index;
1949 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001950 }
1951
Anders Carlsson6cabf312010-01-23 23:23:01 +00001952 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001953 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954
Anders Carlsson6cabf312010-01-23 23:23:01 +00001955 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001957 StructuredList, StructuredIndex);
1958 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001960 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001961}
Steve Narofff8ecff22008-05-01 22:18:59 +00001962
Douglas Gregord5846a12009-04-15 06:41:24 +00001963/// \brief Expand a field designator that refers to a member of an
1964/// anonymous struct or union into a series of field designators that
1965/// refers to the field within the appropriate subobject.
1966///
Douglas Gregord5846a12009-04-15 06:41:24 +00001967static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001968 DesignatedInitExpr *DIE,
1969 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001970 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001971 typedef DesignatedInitExpr::Designator Designator;
1972
Douglas Gregord5846a12009-04-15 06:41:24 +00001973 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001974 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001975 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1976 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1977 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001978 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001979 DIE->getDesignator(DesigIdx)->getDotLoc(),
1980 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1981 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001982 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1983 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001984 assert(isa<FieldDecl>(*PI));
1985 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001986 }
1987
1988 // Expand the current designator into the set of replacement
1989 // designators, so we have a full subobject path down to where the
1990 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001991 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001992 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001993}
Mike Stump11289f42009-09-09 15:08:12 +00001994
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001995static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1996 DesignatedInitExpr *DIE) {
1997 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1998 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1999 for (unsigned I = 0; I < NumIndexExprs; ++I)
2000 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002001 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2002 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002003 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002004 DIE->usesGNUSyntax(), DIE->getInit());
2005}
2006
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002007namespace {
2008
2009// Callback to only accept typo corrections that are for field members of
2010// the given struct or union.
2011class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2012 public:
2013 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2014 : Record(RD) {}
2015
Craig Toppere14c0f82014-03-12 04:55:44 +00002016 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002017 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2018 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2019 }
2020
2021 private:
2022 RecordDecl *Record;
2023};
2024
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002025} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002026
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002027/// @brief Check the well-formedness of a C99 designated initializer.
2028///
2029/// Determines whether the designated initializer @p DIE, which
2030/// resides at the given @p Index within the initializer list @p
2031/// IList, is well-formed for a current object of type @p DeclType
2032/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002033/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002034/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002035///
2036/// @param IList The initializer list in which this designated
2037/// initializer occurs.
2038///
Douglas Gregora5324162009-04-15 04:56:10 +00002039/// @param DIE The designated initializer expression.
2040///
2041/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002042///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002043/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002044/// into which the designation in @p DIE should refer.
2045///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002046/// @param NextField If non-NULL and the first designator in @p DIE is
2047/// a field, this will be set to the field declaration corresponding
2048/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002049///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002050/// @param NextElementIndex If non-NULL and the first designator in @p
2051/// DIE is an array designator or GNU array-range designator, this
2052/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002053///
2054/// @param Index Index into @p IList where the designated initializer
2055/// @p DIE occurs.
2056///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002057/// @param StructuredList The initializer list expression that
2058/// describes all of the subobject initializers in the order they'll
2059/// actually be initialized.
2060///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002061/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002062bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002063InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002064 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002065 DesignatedInitExpr *DIE,
2066 unsigned DesigIdx,
2067 QualType &CurrentObjectType,
2068 RecordDecl::field_iterator *NextField,
2069 llvm::APSInt *NextElementIndex,
2070 unsigned &Index,
2071 InitListExpr *StructuredList,
2072 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002073 bool FinishSubobjectInit,
2074 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002075 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002076 // Check the actual initialization for the designated object type.
2077 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002078
2079 // Temporarily remove the designator expression from the
2080 // initializer list that the child calls see, so that we don't try
2081 // to re-process the designator.
2082 unsigned OldIndex = Index;
2083 IList->setInit(OldIndex, DIE->getInit());
2084
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002085 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002086 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002087
2088 // Restore the designated initializer expression in the syntactic
2089 // form of the initializer list.
2090 if (IList->getInit(OldIndex) != DIE->getInit())
2091 DIE->setInit(IList->getInit(OldIndex));
2092 IList->setInit(OldIndex, DIE);
2093
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002094 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002095 }
2096
Douglas Gregora5324162009-04-15 04:56:10 +00002097 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002098 bool IsFirstDesignator = (DesigIdx == 0);
2099 if (!VerifyOnly) {
2100 assert((IsFirstDesignator || StructuredList) &&
2101 "Need a non-designated initializer list to start from");
2102
2103 // Determine the structural initializer list that corresponds to the
2104 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002105 if (IsFirstDesignator)
2106 StructuredList = SyntacticToSemantic.lookup(IList);
2107 else {
2108 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2109 StructuredList->getInit(StructuredIndex) : nullptr;
2110 if (!ExistingInit && StructuredList->hasArrayFiller())
2111 ExistingInit = StructuredList->getArrayFiller();
2112
2113 if (!ExistingInit)
2114 StructuredList =
2115 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2116 StructuredList, StructuredIndex,
2117 SourceRange(D->getLocStart(),
2118 DIE->getLocEnd()));
2119 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2120 StructuredList = Result;
2121 else {
2122 if (DesignatedInitUpdateExpr *E =
2123 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2124 StructuredList = E->getUpdater();
2125 else {
2126 DesignatedInitUpdateExpr *DIUE =
2127 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2128 D->getLocStart(), ExistingInit,
2129 DIE->getLocEnd());
2130 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2131 StructuredList = DIUE->getUpdater();
2132 }
2133
2134 // We need to check on source range validity because the previous
2135 // initializer does not have to be an explicit initializer. e.g.,
2136 //
2137 // struct P { int a, b; };
2138 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2139 //
2140 // There is an overwrite taking place because the first braced initializer
2141 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2142 if (ExistingInit->getSourceRange().isValid()) {
2143 // We are creating an initializer list that initializes the
2144 // subobjects of the current object, but there was already an
2145 // initialization that completely initialized the current
2146 // subobject, e.g., by a compound literal:
2147 //
2148 // struct X { int a, b; };
2149 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2150 //
2151 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2152 // designated initializer re-initializes the whole
2153 // subobject [0], overwriting previous initializers.
2154 SemaRef.Diag(D->getLocStart(),
2155 diag::warn_subobject_initializer_overrides)
2156 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2157
2158 SemaRef.Diag(ExistingInit->getLocStart(),
2159 diag::note_previous_initializer)
2160 << /*FIXME:has side effects=*/0
2161 << ExistingInit->getSourceRange();
2162 }
2163 }
2164 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002165 assert(StructuredList && "Expected a structured initializer list");
2166 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002167
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002168 if (D->isFieldDesignator()) {
2169 // C99 6.7.8p7:
2170 //
2171 // If a designator has the form
2172 //
2173 // . identifier
2174 //
2175 // then the current object (defined below) shall have
2176 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002177 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002178 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002179 if (!RT) {
2180 SourceLocation Loc = D->getDotLoc();
2181 if (Loc.isInvalid())
2182 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002183 if (!VerifyOnly)
2184 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002185 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002186 ++Index;
2187 return true;
2188 }
2189
Douglas Gregord5846a12009-04-15 06:41:24 +00002190 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002191 if (!KnownField) {
2192 IdentifierInfo *FieldName = D->getFieldName();
2193 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2194 for (NamedDecl *ND : Lookup) {
2195 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2196 KnownField = FD;
2197 break;
2198 }
2199 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002200 // In verify mode, don't modify the original.
2201 if (VerifyOnly)
2202 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002203 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002204 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002205 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002206 break;
2207 }
2208 }
David Majnemer36ef8982014-08-11 18:33:59 +00002209 if (!KnownField) {
2210 if (VerifyOnly) {
2211 ++Index;
2212 return true; // No typo correction when just trying this out.
2213 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002214
David Majnemer36ef8982014-08-11 18:33:59 +00002215 // Name lookup found something, but it wasn't a field.
2216 if (!Lookup.empty()) {
2217 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2218 << FieldName;
2219 SemaRef.Diag(Lookup.front()->getLocation(),
2220 diag::note_field_designator_found);
2221 ++Index;
2222 return true;
2223 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002224
David Majnemer36ef8982014-08-11 18:33:59 +00002225 // Name lookup didn't find anything.
2226 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002227 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2228 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002229 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002230 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2231 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002232 SemaRef.diagnoseTypo(
2233 Corrected,
2234 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002235 << FieldName << CurrentObjectType);
2236 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002237 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002238 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002239 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002240 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2241 << FieldName << CurrentObjectType;
2242 ++Index;
2243 return true;
2244 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002245 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002246 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002247
David Majnemer58e4ea92014-08-23 01:48:50 +00002248 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002249
2250 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2251 FieldIndex = CXXRD->getNumBases();
2252
David Majnemer58e4ea92014-08-23 01:48:50 +00002253 for (auto *FI : RT->getDecl()->fields()) {
2254 if (FI->isUnnamedBitfield())
2255 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002256 if (declaresSameEntity(KnownField, FI)) {
2257 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002258 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002259 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002260 ++FieldIndex;
2261 }
2262
David Majnemer36ef8982014-08-11 18:33:59 +00002263 RecordDecl::field_iterator Field =
2264 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2265
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002266 // All of the fields of a union are located at the same place in
2267 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002268 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002269 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002270 if (!VerifyOnly) {
2271 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002272 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002273 assert(StructuredList->getNumInits() == 1
2274 && "A union should never have more than one initializer!");
2275
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002276 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002277 if (ExistingInit) {
2278 // We're about to throw away an initializer, emit warning.
2279 SemaRef.Diag(D->getFieldLoc(),
2280 diag::warn_initializer_overrides)
2281 << D->getSourceRange();
2282 SemaRef.Diag(ExistingInit->getLocStart(),
2283 diag::note_previous_initializer)
2284 << /*FIXME:has side effects=*/0
2285 << ExistingInit->getSourceRange();
2286 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002287
2288 // remove existing initializer
2289 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002290 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002291 }
2292
David Blaikie40ed2972012-06-06 20:45:41 +00002293 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002294 }
Douglas Gregor51695702009-01-29 16:53:55 +00002295 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002296
Douglas Gregora82064c2011-06-29 21:51:31 +00002297 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002298 bool InvalidUse;
2299 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002300 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002301 else
David Blaikie40ed2972012-06-06 20:45:41 +00002302 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002303 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002304 ++Index;
2305 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002306 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002307
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002308 if (!VerifyOnly) {
2309 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002310 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002311
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002312 // Make sure that our non-designated initializer list has space
2313 // for a subobject corresponding to this field.
2314 if (FieldIndex >= StructuredList->getNumInits())
2315 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2316 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002317
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002318 // This designator names a flexible array member.
2319 if (Field->getType()->isIncompleteArrayType()) {
2320 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002321 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002322 // We can't designate an object within the flexible array
2323 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002324 if (!VerifyOnly) {
2325 DesignatedInitExpr::Designator *NextD
2326 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002327 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002328 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002329 << SourceRange(NextD->getLocStart(),
2330 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002331 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002332 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002333 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002334 Invalid = true;
2335 }
2336
Chris Lattner001b29c2010-10-10 17:49:49 +00002337 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2338 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002339 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002340 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002341 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002342 diag::err_flexible_array_init_needs_braces)
2343 << DIE->getInit()->getSourceRange();
2344 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002345 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002346 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002347 Invalid = true;
2348 }
2349
Eli Friedman3fa64df2011-08-23 22:24:57 +00002350 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002351 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002352 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002353 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002354
2355 if (Invalid) {
2356 ++Index;
2357 return true;
2358 }
2359
2360 // Initialize the array.
2361 bool prevHadError = hadError;
2362 unsigned newStructuredIndex = FieldIndex;
2363 unsigned OldIndex = Index;
2364 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002365
2366 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002367 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002368 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002369 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002370
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002371 IList->setInit(OldIndex, DIE);
2372 if (hadError && !prevHadError) {
2373 ++Field;
2374 ++FieldIndex;
2375 if (NextField)
2376 *NextField = Field;
2377 StructuredIndex = FieldIndex;
2378 return true;
2379 }
2380 } else {
2381 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002382 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002383 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002384
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002385 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002386 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002388 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002389 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002390 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002391 return true;
2392 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002393
2394 // Find the position of the next field to be initialized in this
2395 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002396 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002397 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002398
2399 // If this the first designator, our caller will continue checking
2400 // the rest of this struct/class/union subobject.
2401 if (IsFirstDesignator) {
2402 if (NextField)
2403 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002404 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002405 return false;
2406 }
2407
Douglas Gregor17bd0942009-01-28 23:36:17 +00002408 if (!FinishSubobjectInit)
2409 return false;
2410
Douglas Gregord5846a12009-04-15 06:41:24 +00002411 // We've already initialized something in the union; we're done.
2412 if (RT->getDecl()->isUnion())
2413 return hadError;
2414
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002415 // Check the remaining fields within this class/struct/union subobject.
2416 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002417
Richard Smith872307e2016-03-08 22:17:41 +00002418 auto NoBases =
2419 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2420 CXXRecordDecl::base_class_iterator());
2421 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2422 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002423 return hadError && !prevHadError;
2424 }
2425
2426 // C99 6.7.8p6:
2427 //
2428 // If a designator has the form
2429 //
2430 // [ constant-expression ]
2431 //
2432 // then the current object (defined below) shall have array
2433 // type and the expression shall be an integer constant
2434 // expression. If the array is of unknown size, any
2435 // nonnegative value is valid.
2436 //
2437 // Additionally, cope with the GNU extension that permits
2438 // designators of the form
2439 //
2440 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002441 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002442 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002443 if (!VerifyOnly)
2444 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2445 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002446 ++Index;
2447 return true;
2448 }
2449
Craig Topperc3ec1492014-05-26 06:22:03 +00002450 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002451 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2452 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002453 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002454 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002455 DesignatedEndIndex = DesignatedStartIndex;
2456 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002457 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002458
Mike Stump11289f42009-09-09 15:08:12 +00002459 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002460 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002461 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002462 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002463 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002464
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002465 // Codegen can't handle evaluating array range designators that have side
2466 // effects, because we replicate the AST value for each initialized element.
2467 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2468 // elements with something that has a side effect, so codegen can emit an
2469 // "error unsupported" error instead of miscompiling the app.
2470 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002471 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002472 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002473 }
2474
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002475 if (isa<ConstantArrayType>(AT)) {
2476 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002477 DesignatedStartIndex
2478 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002479 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002480 DesignatedEndIndex
2481 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002482 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2483 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002484 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002485 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002486 diag::err_array_designator_too_large)
2487 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2488 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002489 ++Index;
2490 return true;
2491 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002492 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002493 unsigned DesignatedIndexBitWidth =
2494 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2495 DesignatedStartIndex =
2496 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2497 DesignatedEndIndex =
2498 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002499 DesignatedStartIndex.setIsUnsigned(true);
2500 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002501 }
Mike Stump11289f42009-09-09 15:08:12 +00002502
Eli Friedman1f16b742013-06-11 21:48:11 +00002503 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2504 // We're modifying a string literal init; we have to decompose the string
2505 // so we can modify the individual characters.
2506 ASTContext &Context = SemaRef.Context;
2507 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2508
2509 // Compute the character type
2510 QualType CharTy = AT->getElementType();
2511
2512 // Compute the type of the integer literals.
2513 QualType PromotedCharTy = CharTy;
2514 if (CharTy->isPromotableIntegerType())
2515 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2516 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2517
2518 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2519 // Get the length of the string.
2520 uint64_t StrLen = SL->getLength();
2521 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2522 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2523 StructuredList->resizeInits(Context, StrLen);
2524
2525 // Build a literal for each character in the string, and put them into
2526 // the init list.
2527 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2528 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2529 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002530 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002531 if (CharTy != PromotedCharTy)
2532 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002533 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002534 StructuredList->updateInit(Context, i, Init);
2535 }
2536 } else {
2537 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2538 std::string Str;
2539 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2540
2541 // Get the length of the string.
2542 uint64_t StrLen = Str.size();
2543 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2544 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2545 StructuredList->resizeInits(Context, StrLen);
2546
2547 // Build a literal for each character in the string, and put them into
2548 // the init list.
2549 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2550 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2551 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002552 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002553 if (CharTy != PromotedCharTy)
2554 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002555 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002556 StructuredList->updateInit(Context, i, Init);
2557 }
2558 }
2559 }
2560
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002561 // Make sure that our non-designated initializer list has space
2562 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002563 if (!VerifyOnly &&
2564 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002565 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002566 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002567
Douglas Gregor17bd0942009-01-28 23:36:17 +00002568 // Repeatedly perform subobject initializations in the range
2569 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002570
Douglas Gregor17bd0942009-01-28 23:36:17 +00002571 // Move to the next designator
2572 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2573 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002575 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002576 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002577
Douglas Gregor17bd0942009-01-28 23:36:17 +00002578 while (DesignatedStartIndex <= DesignatedEndIndex) {
2579 // Recurse to check later designated subobjects.
2580 QualType ElementType = AT->getElementType();
2581 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002583 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002584 if (CheckDesignatedInitializer(
2585 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2586 nullptr, Index, StructuredList, ElementIndex,
2587 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2588 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002589 return true;
2590
2591 // Move to the next index in the array that we'll be initializing.
2592 ++DesignatedStartIndex;
2593 ElementIndex = DesignatedStartIndex.getZExtValue();
2594 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002595
2596 // If this the first designator, our caller will continue checking
2597 // the rest of this array subobject.
2598 if (IsFirstDesignator) {
2599 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002600 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002601 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002602 return false;
2603 }
Mike Stump11289f42009-09-09 15:08:12 +00002604
Douglas Gregor17bd0942009-01-28 23:36:17 +00002605 if (!FinishSubobjectInit)
2606 return false;
2607
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002608 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002609 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002610 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002611 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002612 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002613 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002614}
2615
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002616// Get the structured initializer list for a subobject of type
2617// @p CurrentObjectType.
2618InitListExpr *
2619InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2620 QualType CurrentObjectType,
2621 InitListExpr *StructuredList,
2622 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002623 SourceRange InitRange,
2624 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002625 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002626 return nullptr; // No structured list in verification-only mode.
2627 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002628 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002629 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002630 else if (StructuredIndex < StructuredList->getNumInits())
2631 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002632
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002633 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002634 // There might have already been initializers for subobjects of the current
2635 // object, but a subsequent initializer list will overwrite the entirety
2636 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2637 //
2638 // struct P { char x[6]; };
2639 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2640 //
2641 // The first designated initializer is ignored, and l.x is just "f".
2642 if (!IsFullyOverwritten)
2643 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002644
2645 if (ExistingInit) {
2646 // We are creating an initializer list that initializes the
2647 // subobjects of the current object, but there was already an
2648 // initialization that completely initialized the current
2649 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002650 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002651 // struct X { int a, b; };
2652 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002653 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002654 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2655 // designated initializer re-initializes the whole
2656 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002657 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002658 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002659 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002660 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002661 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002662 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002663 << ExistingInit->getSourceRange();
2664 }
2665
Mike Stump11289f42009-09-09 15:08:12 +00002666 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002667 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002668 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002669 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002670
Eli Friedman91f5ae52012-02-23 02:25:10 +00002671 QualType ResultType = CurrentObjectType;
2672 if (!ResultType->isArrayType())
2673 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2674 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002675
Douglas Gregor6d00c992009-03-20 23:58:33 +00002676 // Pre-allocate storage for the structured initializer list.
2677 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002678 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002679 bool GotNumInits = false;
2680 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002681 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002682 GotNumInits = true;
2683 } else if (Index < IList->getNumInits()) {
2684 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002685 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002686 GotNumInits = true;
2687 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002688 }
2689
Mike Stump11289f42009-09-09 15:08:12 +00002690 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002691 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2692 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2693 NumElements = CAType->getSize().getZExtValue();
2694 // Simple heuristic so that we don't allocate a very large
2695 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002696 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002697 NumElements = 0;
2698 }
John McCall9dd450b2009-09-21 23:43:11 +00002699 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002700 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002701 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002702 RecordDecl *RDecl = RType->getDecl();
2703 if (RDecl->isUnion())
2704 NumElements = 1;
2705 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002706 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002707 }
2708
Ted Kremenekac034612010-04-13 23:39:13 +00002709 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002710
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002711 // Link this new initializer list into the structured initializer
2712 // lists.
2713 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002714 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002715 else {
2716 Result->setSyntacticForm(IList);
2717 SyntacticToSemantic[IList] = Result;
2718 }
2719
2720 return Result;
2721}
2722
2723/// Update the initializer at index @p StructuredIndex within the
2724/// structured initializer list to the value @p expr.
2725void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2726 unsigned &StructuredIndex,
2727 Expr *expr) {
2728 // No structured initializer list to update
2729 if (!StructuredList)
2730 return;
2731
Ted Kremenekac034612010-04-13 23:39:13 +00002732 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2733 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002734 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002735 // We need to check on source range validity because the previous
2736 // initializer does not have to be an explicit initializer.
2737 // struct P { int a, b; };
2738 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2739 // There is an overwrite taking place because the first braced initializer
2740 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2741 if (PrevInit->getSourceRange().isValid()) {
2742 SemaRef.Diag(expr->getLocStart(),
2743 diag::warn_initializer_overrides)
2744 << expr->getSourceRange();
2745
2746 SemaRef.Diag(PrevInit->getLocStart(),
2747 diag::note_previous_initializer)
2748 << /*FIXME:has side effects=*/0
2749 << PrevInit->getSourceRange();
2750 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002751 }
Mike Stump11289f42009-09-09 15:08:12 +00002752
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002753 ++StructuredIndex;
2754}
2755
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002756/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002757/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002758/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002759/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002760/// failure. Returns the index expression, possibly with an implicit cast
2761/// added, on success. If everything went okay, Value will receive the
2762/// value of the constant expression.
2763static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002764CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002765 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002766
2767 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002768 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2769 if (Result.isInvalid())
2770 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002771
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002772 if (Value.isSigned() && Value.isNegative())
2773 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002774 << Value.toString(10) << Index->getSourceRange();
2775
Douglas Gregor51650d32009-01-23 21:04:18 +00002776 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002777 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002778}
2779
John McCalldadc5752010-08-24 06:29:42 +00002780ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002781 SourceLocation Loc,
2782 bool GNUSyntax,
2783 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002784 typedef DesignatedInitExpr::Designator ASTDesignator;
2785
2786 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002787 SmallVector<ASTDesignator, 32> Designators;
2788 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002789
2790 // Build designators and check array designator expressions.
2791 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2792 const Designator &D = Desig.getDesignator(Idx);
2793 switch (D.getKind()) {
2794 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002795 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002796 D.getFieldLoc()));
2797 break;
2798
2799 case Designator::ArrayDesignator: {
2800 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2801 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002802 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002803 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002804 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002805 Invalid = true;
2806 else {
2807 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002808 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002809 D.getRBracketLoc()));
2810 InitExpressions.push_back(Index);
2811 }
2812 break;
2813 }
2814
2815 case Designator::ArrayRangeDesignator: {
2816 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2817 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2818 llvm::APSInt StartValue;
2819 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002820 bool StartDependent = StartIndex->isTypeDependent() ||
2821 StartIndex->isValueDependent();
2822 bool EndDependent = EndIndex->isTypeDependent() ||
2823 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002824 if (!StartDependent)
2825 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002826 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002827 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002828 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002829
2830 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002831 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002832 else {
2833 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002834 if (StartDependent || EndDependent) {
2835 // Nothing to compute.
2836 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002837 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002838 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002839 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002840
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002841 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002842 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002843 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002844 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2845 Invalid = true;
2846 } else {
2847 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002848 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002849 D.getEllipsisLoc(),
2850 D.getRBracketLoc()));
2851 InitExpressions.push_back(StartIndex);
2852 InitExpressions.push_back(EndIndex);
2853 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002854 }
2855 break;
2856 }
2857 }
2858 }
2859
2860 if (Invalid || Init.isInvalid())
2861 return ExprError();
2862
2863 // Clear out the expressions within the designation.
2864 Desig.ClearExprs(*this);
2865
2866 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002867 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00002868 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002869 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002870 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002871
David Blaikiebbafb8a2012-03-11 07:00:24 +00002872 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002873 Diag(DIE->getLocStart(), diag::ext_designated_init)
2874 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002875
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002876 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002877}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002878
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002879//===----------------------------------------------------------------------===//
2880// Initialization entity
2881//===----------------------------------------------------------------------===//
2882
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002883InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002884 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002886{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002887 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2888 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002889 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002890 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002891 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002892 Type = VT->getElementType();
2893 } else {
2894 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2895 assert(CT && "Unexpected type");
2896 Kind = EK_ComplexElement;
2897 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002898 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002899}
2900
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002901InitializedEntity
2902InitializedEntity::InitializeBase(ASTContext &Context,
2903 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00002904 bool IsInheritedVirtualBase,
2905 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002906 InitializedEntity Result;
2907 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00002908 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002909 Result.Base = reinterpret_cast<uintptr_t>(Base);
2910 if (IsInheritedVirtualBase)
2911 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002912
Douglas Gregor1b303932009-12-22 15:35:07 +00002913 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002914 return Result;
2915}
2916
Douglas Gregor85dabae2009-12-16 01:38:02 +00002917DeclarationName InitializedEntity::getName() const {
2918 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002919 case EK_Parameter:
2920 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002921 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2922 return (D ? D->getDeclName() : DeclarationName());
2923 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002924
2925 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002926 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002927 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002928 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002929
Douglas Gregor19666fb2012-02-15 16:57:26 +00002930 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002931 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002932
Douglas Gregor85dabae2009-12-16 01:38:02 +00002933 case EK_Result:
2934 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002935 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002936 case EK_Temporary:
2937 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002938 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002939 case EK_ArrayElement:
2940 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002941 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002942 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00002943 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002944 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002945 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002946 return DeclarationName();
2947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948
David Blaikie8a40f702012-01-17 06:56:22 +00002949 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002950}
2951
Richard Smith7873de02016-08-11 22:25:46 +00002952ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00002953 switch (getKind()) {
2954 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002955 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002956 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002957 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002958
John McCall31168b02011-06-15 23:02:42 +00002959 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002960 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002961 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2962
Douglas Gregora4b592a2009-12-19 03:01:41 +00002963 case EK_Result:
2964 case EK_Exception:
2965 case EK_New:
2966 case EK_Temporary:
2967 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002968 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002969 case EK_ArrayElement:
2970 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002971 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002972 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00002973 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002974 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002975 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002976 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002977 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979
David Blaikie8a40f702012-01-17 06:56:22 +00002980 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002981}
2982
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002983bool InitializedEntity::allowsNRVO() const {
2984 switch (getKind()) {
2985 case EK_Result:
2986 case EK_Exception:
2987 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002988
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002989 case EK_Variable:
2990 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002991 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002992 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002993 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002994 case EK_New:
2995 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002996 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002997 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002998 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002999 case EK_ArrayElement:
3000 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003001 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003002 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003003 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003004 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003005 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003006 break;
3007 }
3008
3009 return false;
3010}
3011
Richard Smithe6c01442013-06-05 00:46:14 +00003012unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003013 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003014 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3015 for (unsigned I = 0; I != Depth; ++I)
3016 OS << "`-";
3017
3018 switch (getKind()) {
3019 case EK_Variable: OS << "Variable"; break;
3020 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003021 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3022 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003023 case EK_Result: OS << "Result"; break;
3024 case EK_Exception: OS << "Exception"; break;
3025 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003026 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003027 case EK_New: OS << "New"; break;
3028 case EK_Temporary: OS << "Temporary"; break;
3029 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003030 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003031 case EK_Base: OS << "Base"; break;
3032 case EK_Delegating: OS << "Delegating"; break;
3033 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3034 case EK_VectorElement: OS << "VectorElement " << Index; break;
3035 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3036 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003037 case EK_LambdaToBlockConversionBlockElement:
3038 OS << "Block (lambda)";
3039 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003040 case EK_LambdaCapture:
3041 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003042 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003043 break;
3044 }
3045
Richard Smith7873de02016-08-11 22:25:46 +00003046 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003047 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003048 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003049 }
3050
3051 OS << " '" << getType().getAsString() << "'\n";
3052
3053 return Depth + 1;
3054}
3055
Yaron Kerencdae9412016-01-29 19:38:18 +00003056LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003057 dumpImpl(llvm::errs());
3058}
3059
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003060//===----------------------------------------------------------------------===//
3061// Initialization sequence
3062//===----------------------------------------------------------------------===//
3063
3064void InitializationSequence::Step::Destroy() {
3065 switch (Kind) {
3066 case SK_ResolveAddressOfOverloadedFunction:
3067 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003068 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003069 case SK_CastDerivedToBaseLValue:
3070 case SK_BindReference:
3071 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003072 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003073 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003074 case SK_UserConversion:
3075 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003076 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003077 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003078 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003079 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003080 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003081 case SK_UnwrapInitList:
3082 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003083 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003084 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003085 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003086 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003087 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003088 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003089 case SK_ArrayLoopIndex:
3090 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003091 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003092 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003093 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003094 case SK_PassByIndirectCopyRestore:
3095 case SK_PassByIndirectRestore:
3096 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003097 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003098 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003099 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003100 case SK_OCLZeroEvent:
Egor Churaev89831422016-12-23 14:55:49 +00003101 case SK_OCLZeroQueue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003102 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003103
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003104 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003105 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003106 delete ICS;
3107 }
3108}
3109
Douglas Gregor838fcc32010-03-26 20:14:36 +00003110bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003111 // There can be some lvalue adjustments after the SK_BindReference step.
3112 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3113 if (I->Kind == SK_BindReference)
3114 return true;
3115 if (I->Kind == SK_BindReferenceToTemporary)
3116 return false;
3117 }
3118 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003119}
3120
3121bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003122 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003123 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003124
Douglas Gregor838fcc32010-03-26 20:14:36 +00003125 switch (getFailureKind()) {
3126 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003127 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003128 case FK_ArrayNeedsInitList:
3129 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003130 case FK_ArrayNeedsInitListOrWideStringLiteral:
3131 case FK_NarrowStringIntoWideCharArray:
3132 case FK_WideStringIntoCharArray:
3133 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003134 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3135 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003136 case FK_NonConstLValueReferenceBindingToBitfield:
3137 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003138 case FK_NonConstLValueReferenceBindingToUnrelated:
3139 case FK_RValueReferenceBindingToLValue:
3140 case FK_ReferenceInitDropsQualifiers:
3141 case FK_ReferenceInitFailed:
3142 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003143 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003144 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003145 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003146 case FK_ReferenceBindingToInitList:
3147 case FK_InitListBadDestinationType:
3148 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003149 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003150 case FK_ArrayTypeMismatch:
3151 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003152 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003153 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003154 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003155 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003156 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003157 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158
Douglas Gregor838fcc32010-03-26 20:14:36 +00003159 case FK_ReferenceInitOverloadFailed:
3160 case FK_UserConversionOverloadFailed:
3161 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003162 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003163 return FailedOverloadResult == OR_Ambiguous;
3164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
David Blaikie8a40f702012-01-17 06:56:22 +00003166 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003167}
3168
Douglas Gregorb33eed02010-04-16 22:09:46 +00003169bool InitializationSequence::isConstructorInitialization() const {
3170 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3171}
3172
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003173void
3174InitializationSequence
3175::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3176 DeclAccessPair Found,
3177 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003178 Step S;
3179 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3180 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003181 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003182 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003183 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003184 Steps.push_back(S);
3185}
3186
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003188 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003189 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003190 switch (VK) {
3191 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3192 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3193 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003194 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003195 S.Type = BaseType;
3196 Steps.push_back(S);
3197}
3198
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003200 bool BindingTemporary) {
3201 Step S;
3202 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3203 S.Type = T;
3204 Steps.push_back(S);
3205}
3206
Richard Smithb8c0f552016-12-09 18:49:13 +00003207void InitializationSequence::AddFinalCopy(QualType T) {
3208 Step S;
3209 S.Kind = SK_FinalCopy;
3210 S.Type = T;
3211 Steps.push_back(S);
3212}
3213
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003214void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3215 Step S;
3216 S.Kind = SK_ExtraneousCopyToTemporary;
3217 S.Type = T;
3218 Steps.push_back(S);
3219}
3220
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003221void
3222InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3223 DeclAccessPair FoundDecl,
3224 QualType T,
3225 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 Step S;
3227 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003228 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003229 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003230 S.Function.Function = Function;
3231 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003232 Steps.push_back(S);
3233}
3234
3235void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003236 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003237 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003238 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003239 switch (VK) {
3240 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003241 S.Kind = SK_QualificationConversionRValue;
3242 break;
John McCall2536c6d2010-08-25 10:28:54 +00003243 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003244 S.Kind = SK_QualificationConversionXValue;
3245 break;
John McCall2536c6d2010-08-25 10:28:54 +00003246 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003247 S.Kind = SK_QualificationConversionLValue;
3248 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003249 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003250 S.Type = Ty;
3251 Steps.push_back(S);
3252}
3253
Richard Smith77be48a2014-07-31 06:31:19 +00003254void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3255 Step S;
3256 S.Kind = SK_AtomicConversion;
3257 S.Type = Ty;
3258 Steps.push_back(S);
3259}
3260
Jordan Roseb1312a52013-04-11 00:58:58 +00003261void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3262 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3263
3264 Step S;
3265 S.Kind = SK_LValueToRValue;
3266 S.Type = Ty;
3267 Steps.push_back(S);
3268}
3269
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003270void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003271 const ImplicitConversionSequence &ICS, QualType T,
3272 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003273 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003274 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3275 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003276 S.Type = T;
3277 S.ICS = new ImplicitConversionSequence(ICS);
3278 Steps.push_back(S);
3279}
3280
Douglas Gregor51e77d52009-12-10 17:56:55 +00003281void InitializationSequence::AddListInitializationStep(QualType T) {
3282 Step S;
3283 S.Kind = SK_ListInitialization;
3284 S.Type = T;
3285 Steps.push_back(S);
3286}
3287
Richard Smith55c28882016-05-12 23:45:49 +00003288void InitializationSequence::AddConstructorInitializationStep(
3289 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3290 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003291 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003292 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003293 : SK_ConstructorInitializationFromList
3294 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003295 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003296 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003297 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003298 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003299 Steps.push_back(S);
3300}
3301
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003302void InitializationSequence::AddZeroInitializationStep(QualType T) {
3303 Step S;
3304 S.Kind = SK_ZeroInitialization;
3305 S.Type = T;
3306 Steps.push_back(S);
3307}
3308
Douglas Gregore1314a62009-12-18 05:02:21 +00003309void InitializationSequence::AddCAssignmentStep(QualType T) {
3310 Step S;
3311 S.Kind = SK_CAssignment;
3312 S.Type = T;
3313 Steps.push_back(S);
3314}
3315
Eli Friedman78275202009-12-19 08:11:05 +00003316void InitializationSequence::AddStringInitStep(QualType T) {
3317 Step S;
3318 S.Kind = SK_StringInit;
3319 S.Type = T;
3320 Steps.push_back(S);
3321}
3322
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003323void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3324 Step S;
3325 S.Kind = SK_ObjCObjectConversion;
3326 S.Type = T;
3327 Steps.push_back(S);
3328}
3329
Richard Smith378b8c82016-12-14 03:22:16 +00003330void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003331 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003332 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003333 S.Type = T;
3334 Steps.push_back(S);
3335}
3336
Richard Smith410306b2016-12-12 02:53:20 +00003337void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3338 Step S;
3339 S.Kind = SK_ArrayLoopIndex;
3340 S.Type = EltT;
3341 Steps.insert(Steps.begin(), S);
3342
3343 S.Kind = SK_ArrayLoopInit;
3344 S.Type = T;
3345 Steps.push_back(S);
3346}
3347
Richard Smithebeed412012-02-15 22:38:09 +00003348void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3349 Step S;
3350 S.Kind = SK_ParenthesizedArrayInit;
3351 S.Type = T;
3352 Steps.push_back(S);
3353}
3354
John McCall31168b02011-06-15 23:02:42 +00003355void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3356 bool shouldCopy) {
3357 Step s;
3358 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3359 : SK_PassByIndirectRestore);
3360 s.Type = type;
3361 Steps.push_back(s);
3362}
3363
3364void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3365 Step S;
3366 S.Kind = SK_ProduceObjCObject;
3367 S.Type = T;
3368 Steps.push_back(S);
3369}
3370
Sebastian Redlc1839b12012-01-17 22:49:42 +00003371void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3372 Step S;
3373 S.Kind = SK_StdInitializerList;
3374 S.Type = T;
3375 Steps.push_back(S);
3376}
3377
Guy Benyei61054192013-02-07 10:55:47 +00003378void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3379 Step S;
3380 S.Kind = SK_OCLSamplerInit;
3381 S.Type = T;
3382 Steps.push_back(S);
3383}
3384
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003385void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3386 Step S;
3387 S.Kind = SK_OCLZeroEvent;
3388 S.Type = T;
3389 Steps.push_back(S);
3390}
3391
Egor Churaev89831422016-12-23 14:55:49 +00003392void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3393 Step S;
3394 S.Kind = SK_OCLZeroQueue;
3395 S.Type = T;
3396 Steps.push_back(S);
3397}
3398
Sebastian Redl29526f02011-11-27 16:50:07 +00003399void InitializationSequence::RewrapReferenceInitList(QualType T,
3400 InitListExpr *Syntactic) {
3401 assert(Syntactic->getNumInits() == 1 &&
3402 "Can only rewrap trivial init lists.");
3403 Step S;
3404 S.Kind = SK_UnwrapInitList;
3405 S.Type = Syntactic->getInit(0)->getType();
3406 Steps.insert(Steps.begin(), S);
3407
3408 S.Kind = SK_RewrapInitList;
3409 S.Type = T;
3410 S.WrappingSyntacticList = Syntactic;
3411 Steps.push_back(S);
3412}
3413
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003415 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003416 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003417 this->Failure = Failure;
3418 this->FailedOverloadResult = Result;
3419}
3420
3421//===----------------------------------------------------------------------===//
3422// Attempt initialization
3423//===----------------------------------------------------------------------===//
3424
Nico Weber337d5aa2015-04-17 08:32:38 +00003425/// Tries to add a zero initializer. Returns true if that worked.
3426static bool
3427maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3428 const InitializedEntity &Entity) {
3429 if (Entity.getKind() != InitializedEntity::EK_Variable)
3430 return false;
3431
3432 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3433 if (VD->getInit() || VD->getLocEnd().isMacroID())
3434 return false;
3435
3436 QualType VariableTy = VD->getType().getCanonicalType();
3437 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3438 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3439 if (!Init.empty()) {
3440 Sequence.AddZeroInitializationStep(Entity.getType());
3441 Sequence.SetZeroInitializationFixit(Init, Loc);
3442 return true;
3443 }
3444 return false;
3445}
3446
John McCall31168b02011-06-15 23:02:42 +00003447static void MaybeProduceObjCObject(Sema &S,
3448 InitializationSequence &Sequence,
3449 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003450 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003451
3452 /// When initializing a parameter, produce the value if it's marked
3453 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003454 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003455 if (!Entity.isParameterConsumed())
3456 return;
3457
3458 assert(Entity.getType()->isObjCRetainableType() &&
3459 "consuming an object of unretainable type?");
3460 Sequence.AddProduceObjCObjectStep(Entity.getType());
3461
3462 /// When initializing a return value, if the return type is a
3463 /// retainable type, then returns need to immediately retain the
3464 /// object. If an autorelease is required, it will be done at the
3465 /// last instant.
3466 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3467 if (!Entity.getType()->isObjCRetainableType())
3468 return;
3469
3470 Sequence.AddProduceObjCObjectStep(Entity.getType());
3471 }
3472}
3473
Richard Smithcc1b96d2013-06-12 22:31:48 +00003474static void TryListInitialization(Sema &S,
3475 const InitializedEntity &Entity,
3476 const InitializationKind &Kind,
3477 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003478 InitializationSequence &Sequence,
3479 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003480
Richard Smithd86812d2012-07-05 08:39:21 +00003481/// \brief When initializing from init list via constructor, handle
3482/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003483///
Richard Smithd86812d2012-07-05 08:39:21 +00003484/// \return true if we have handled initialization of an object of type
3485/// std::initializer_list<T>, false otherwise.
3486static bool TryInitializerListConstruction(Sema &S,
3487 InitListExpr *List,
3488 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003489 InitializationSequence &Sequence,
3490 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003491 QualType E;
3492 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003493 return false;
3494
Richard Smithdb0ac552015-12-18 22:40:25 +00003495 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003496 Sequence.setIncompleteTypeFailure(E);
3497 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003498 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003499
3500 // Try initializing a temporary array from the init list.
3501 QualType ArrayType = S.Context.getConstantArrayType(
3502 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3503 List->getNumInits()),
3504 clang::ArrayType::Normal, 0);
3505 InitializedEntity HiddenArray =
3506 InitializedEntity::InitializeTemporary(ArrayType);
3507 InitializationKind Kind =
3508 InitializationKind::CreateDirectList(List->getExprLoc());
Manman Ren073db022016-03-10 18:53:19 +00003509 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3510 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003511 if (Sequence)
3512 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003513 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003514}
3515
Richard Smith7c2bcc92016-09-07 02:14:33 +00003516/// Determine if the constructor has the signature of a copy or move
3517/// constructor for the type T of the class in which it was found. That is,
3518/// determine if its first parameter is of type T or reference to (possibly
3519/// cv-qualified) T.
3520static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3521 const ConstructorInfo &Info) {
3522 if (Info.Constructor->getNumParams() == 0)
3523 return false;
3524
3525 QualType ParmT =
3526 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3527 QualType ClassT =
3528 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3529
3530 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3531}
3532
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003533static OverloadingResult
3534ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003535 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003536 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003537 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003538 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003539 OverloadCandidateSet::iterator &Best,
3540 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003541 bool OnlyListConstructors, bool IsListInit,
3542 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003543 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003544
Richard Smith40c78062015-02-21 02:31:57 +00003545 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003546 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003547 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003548 continue;
3549
Richard Smith7c2bcc92016-09-07 02:14:33 +00003550 if (!AllowExplicit && Info.Constructor->isExplicit())
3551 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003552
Richard Smith7c2bcc92016-09-07 02:14:33 +00003553 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3554 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003555
Richard Smith7c2bcc92016-09-07 02:14:33 +00003556 // C++11 [over.best.ics]p4:
3557 // ... and the constructor or user-defined conversion function is a
3558 // candidate by
3559 // - 13.3.1.3, when the argument is the temporary in the second step
3560 // of a class copy-initialization, or
3561 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3562 // - the second phase of 13.3.1.7 when the initializer list has exactly
3563 // one element that is itself an initializer list, and the target is
3564 // the first parameter of a constructor of class X, and the conversion
3565 // is to X or reference to (possibly cv-qualified X),
3566 // user-defined conversion sequences are not considered.
3567 bool SuppressUserConversions =
3568 SecondStepOfCopyInit ||
3569 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3570 hasCopyOrMoveCtorParam(S.Context, Info));
3571
3572 if (Info.ConstructorTmpl)
3573 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3574 /*ExplicitArgs*/ nullptr, Args,
3575 CandidateSet, SuppressUserConversions);
3576 else {
3577 // C++ [over.match.copy]p1:
3578 // - When initializing a temporary to be bound to the first parameter
3579 // of a constructor [for type T] that takes a reference to possibly
3580 // cv-qualified T as its first argument, called with a single
3581 // argument in the context of direct-initialization, explicit
3582 // conversion functions are also considered.
3583 // FIXME: What if a constructor template instantiates to such a signature?
3584 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3585 Args.size() == 1 &&
3586 hasCopyOrMoveCtorParam(S.Context, Info);
3587 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3588 CandidateSet, SuppressUserConversions,
3589 /*PartialOverloading=*/false,
3590 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003591 }
3592 }
3593
Richard Smith67ef14f2017-09-26 18:37:55 +00003594 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3595 //
3596 // When initializing an object of class type T by constructor
3597 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3598 // from a single expression of class type U, conversion functions of
3599 // U that convert to the non-reference type cv T are candidates.
3600 // Explicit conversion functions are only candidates during
3601 // direct-initialization.
3602 //
3603 // Note: SecondStepOfCopyInit is only ever true in this case when
3604 // evaluating whether to produce a C++98 compatibility warning.
3605 if (S.getLangOpts().CPlusPlus1z && Args.size() == 1 &&
3606 !SecondStepOfCopyInit) {
3607 Expr *Initializer = Args[0];
3608 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3609 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3610 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3611 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3612 NamedDecl *D = *I;
3613 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3614 D = D->getUnderlyingDecl();
3615
3616 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3617 CXXConversionDecl *Conv;
3618 if (ConvTemplate)
3619 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3620 else
3621 Conv = cast<CXXConversionDecl>(D);
3622
3623 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3624 if (ConvTemplate)
3625 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3626 ActingDC, Initializer, DestType,
3627 CandidateSet, AllowExplicit,
3628 /*AllowResultConversion*/false);
3629 else
3630 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3631 DestType, CandidateSet, AllowExplicit,
3632 /*AllowResultConversion*/false);
3633 }
3634 }
3635 }
3636 }
3637
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003638 // Perform overload resolution and return the result.
3639 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3640}
3641
Sebastian Redled2e5322011-12-22 14:44:04 +00003642/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3643/// enumerates the constructors of the initialized entity and performs overload
3644/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003645/// \param DestType The destination class type.
3646/// \param DestArrayType The destination type, which is either DestType or
3647/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003648/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003649/// \param IsInitListCopy Is this non-list-initialization resulting from a
3650/// list-initialization from {x} where x is the same
3651/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003652static void TryConstructorInitialization(Sema &S,
3653 const InitializedEntity &Entity,
3654 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003655 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003656 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003657 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003658 bool IsListInit = false,
3659 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003660 assert(((!IsListInit && !IsInitListCopy) ||
3661 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3662 "IsListInit/IsInitListCopy must come with a single initializer list "
3663 "argument.");
3664 InitListExpr *ILE =
3665 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3666 MultiExprArg UnwrappedArgs =
3667 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003668
Sebastian Redled2e5322011-12-22 14:44:04 +00003669 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003670 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003671 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003672 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003673 }
3674
Richard Smith122f88d2016-12-06 23:52:28 +00003675 // C++1z [dcl.init]p17:
3676 // - If the initializer expression is a prvalue and the cv-unqualified
3677 // version of the source type is the same class as the class of the
3678 // destination, the initializer expression is used to initialize the
3679 // destination object.
3680 // Per DR (no number yet), this does not apply when initializing a base
3681 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003682 // ObjC++: Lambda captured by the block in the lambda to block conversion
3683 // should avoid copy elision.
Richard Smith122f88d2016-12-06 23:52:28 +00003684 if (S.getLangOpts().CPlusPlus1z &&
3685 Entity.getKind() != InitializedEntity::EK_Base &&
3686 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003687 Entity.getKind() !=
3688 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003689 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3690 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3691 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003692 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003693 if (ILE)
3694 Sequence.RewrapReferenceInitList(DestType, ILE);
3695 return;
3696 }
3697
Sebastian Redled2e5322011-12-22 14:44:04 +00003698 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3699 assert(DestRecordType && "Constructor initialization requires record type");
3700 CXXRecordDecl *DestRecordDecl
3701 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3702
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003703 // Build the candidate set directly in the initialization sequence
3704 // structure, so that it will persist if we fail.
3705 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3706
3707 // Determine whether we are allowed to call explicit constructors or
3708 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003709 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003710 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003711
Sebastian Redled2e5322011-12-22 14:44:04 +00003712 // - Otherwise, if T is a class type, constructors are considered. The
3713 // applicable constructors are enumerated, and the best one is chosen
3714 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003715 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003716
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003717 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003718 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003719 bool AsInitializerList = false;
3720
Larisse Voufo19d08672015-01-27 18:47:05 +00003721 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003722 // When objects of non-aggregate type T are list-initialized, such that
3723 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3724 // according to the rules in this section, overload resolution selects
3725 // the constructor in two phases:
3726 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003727 // - Initially, the candidate functions are the initializer-list
3728 // constructors of the class T and the argument list consists of the
3729 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003730 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003731 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003732
3733 // If the initializer list has no elements and T has a default constructor,
3734 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003735 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003736 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003737 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003738 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003739 /*OnlyListConstructor=*/true,
3740 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003741 }
3742
3743 // C++11 [over.match.list]p1:
3744 // - If no viable initializer-list constructor is found, overload resolution
3745 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003746 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003747 // elements of the initializer list.
3748 if (Result == OR_No_Viable_Function) {
3749 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003750 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003751 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003752 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003753 /*OnlyListConstructors=*/false,
3754 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003755 }
3756 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003757 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003758 InitializationSequence::FK_ListConstructorOverloadFailed :
3759 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003760 Result);
3761 return;
3762 }
3763
Richard Smith67ef14f2017-09-26 18:37:55 +00003764 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3765
3766 // In C++17, ResolveConstructorOverload can select a conversion function
3767 // instead of a constructor.
3768 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3769 // Add the user-defined conversion step that calls the conversion function.
3770 QualType ConvType = CD->getConversionType();
3771 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3772 "should not have selected this conversion function");
3773 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3774 HadMultipleCandidates);
3775 if (!S.Context.hasSameType(ConvType, DestType))
3776 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3777 if (IsListInit)
3778 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3779 return;
3780 }
3781
Richard Smithd86812d2012-07-05 08:39:21 +00003782 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003783 // If a program calls for the default initialization of an object
3784 // of a const-qualified type T, T shall be a class type with a
3785 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003786 // C++ core issue 253 proposal:
3787 // If the implicit default constructor initializes all subobjects, no
3788 // initializer should be required.
3789 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3790 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003791 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003792 Entity.getType().isConstQualified()) {
3793 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3794 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3795 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3796 return;
3797 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003798 }
3799
Sebastian Redl048a6d72012-04-01 19:54:59 +00003800 // C++11 [over.match.list]p1:
3801 // In copy-list-initialization, if an explicit constructor is chosen, the
3802 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003803 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003804 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3805 return;
3806 }
3807
Sebastian Redled2e5322011-12-22 14:44:04 +00003808 // Add the constructor initialization step. Any cv-qualification conversion is
3809 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00003810 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003811 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003812 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003813}
3814
Sebastian Redl29526f02011-11-27 16:50:07 +00003815static bool
3816ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3817 Expr *Initializer,
3818 QualType &SourceType,
3819 QualType &UnqualifiedSourceType,
3820 QualType UnqualifiedTargetType,
3821 InitializationSequence &Sequence) {
3822 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3823 S.Context.OverloadTy) {
3824 DeclAccessPair Found;
3825 bool HadMultipleCandidates = false;
3826 if (FunctionDecl *Fn
3827 = S.ResolveAddressOfOverloadedFunction(Initializer,
3828 UnqualifiedTargetType,
3829 false, Found,
3830 &HadMultipleCandidates)) {
3831 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3832 HadMultipleCandidates);
3833 SourceType = Fn->getType();
3834 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3835 } else if (!UnqualifiedTargetType->isRecordType()) {
3836 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3837 return true;
3838 }
3839 }
3840 return false;
3841}
3842
3843static void TryReferenceInitializationCore(Sema &S,
3844 const InitializedEntity &Entity,
3845 const InitializationKind &Kind,
3846 Expr *Initializer,
3847 QualType cv1T1, QualType T1,
3848 Qualifiers T1Quals,
3849 QualType cv2T2, QualType T2,
3850 Qualifiers T2Quals,
3851 InitializationSequence &Sequence);
3852
Richard Smithd86812d2012-07-05 08:39:21 +00003853static void TryValueInitialization(Sema &S,
3854 const InitializedEntity &Entity,
3855 const InitializationKind &Kind,
3856 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003857 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003858
Sebastian Redl29526f02011-11-27 16:50:07 +00003859/// \brief Attempt list initialization of a reference.
3860static void TryReferenceListInitialization(Sema &S,
3861 const InitializedEntity &Entity,
3862 const InitializationKind &Kind,
3863 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003864 InitializationSequence &Sequence,
3865 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003866 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003867 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003868 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3869 return;
3870 }
David Majnemer9370dc22015-04-26 07:35:03 +00003871 // Can't reference initialize a compound literal.
3872 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3873 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3874 return;
3875 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003876
3877 QualType DestType = Entity.getType();
3878 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3879 Qualifiers T1Quals;
3880 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3881
3882 // Reference initialization via an initializer list works thus:
3883 // If the initializer list consists of a single element that is
3884 // reference-related to the referenced type, bind directly to that element
3885 // (possibly creating temporaries).
3886 // Otherwise, initialize a temporary with the initializer list and
3887 // bind to that.
3888 if (InitList->getNumInits() == 1) {
3889 Expr *Initializer = InitList->getInit(0);
3890 QualType cv2T2 = Initializer->getType();
3891 Qualifiers T2Quals;
3892 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3893
3894 // If this fails, creating a temporary wouldn't work either.
3895 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3896 T1, Sequence))
3897 return;
3898
3899 SourceLocation DeclLoc = Initializer->getLocStart();
3900 bool dummy1, dummy2, dummy3;
3901 Sema::ReferenceCompareResult RefRelationship
3902 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3903 dummy2, dummy3);
3904 if (RefRelationship >= Sema::Ref_Related) {
3905 // Try to bind the reference here.
3906 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3907 T1Quals, cv2T2, T2, T2Quals, Sequence);
3908 if (Sequence)
3909 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3910 return;
3911 }
Richard Smith03d93932013-01-15 07:58:29 +00003912
3913 // Update the initializer if we've resolved an overloaded function.
3914 if (Sequence.step_begin() != Sequence.step_end())
3915 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003916 }
3917
3918 // Not reference-related. Create a temporary and bind to that.
3919 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3920
Manman Ren073db022016-03-10 18:53:19 +00003921 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3922 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00003923 if (Sequence) {
3924 if (DestType->isRValueReferenceType() ||
3925 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3926 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3927 else
3928 Sequence.SetFailed(
3929 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3930 }
3931}
3932
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003933/// \brief Attempt list initialization (C++0x [dcl.init.list])
3934static void TryListInitialization(Sema &S,
3935 const InitializedEntity &Entity,
3936 const InitializationKind &Kind,
3937 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003938 InitializationSequence &Sequence,
3939 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003940 QualType DestType = Entity.getType();
3941
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003942 // C++ doesn't allow scalar initialization with more than one argument.
3943 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003944 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003945 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3946 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3947 return;
3948 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003949 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00003950 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
3951 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003952 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003953 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003954
Larisse Voufod2010992015-01-24 23:09:54 +00003955 if (DestType->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00003956 !S.isCompleteType(InitList->getLocStart(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00003957 Sequence.setIncompleteTypeFailure(DestType);
3958 return;
3959 }
Richard Smithd86812d2012-07-05 08:39:21 +00003960
Larisse Voufo19d08672015-01-27 18:47:05 +00003961 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003962 // - If T is a class type and the initializer list has a single element of
3963 // type cv U, where U is T or a class derived from T, the object is
3964 // initialized from that element (by copy-initialization for
3965 // copy-list-initialization, or by direct-initialization for
3966 // direct-list-initialization).
3967 // - Otherwise, if T is a character array and the initializer list has a
3968 // single element that is an appropriately-typed string literal
3969 // (8.5.2 [dcl.init.string]), initialization is performed as described
3970 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003971 // - Otherwise, if T is an aggregate, [...] (continue below).
3972 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003973 if (DestType->isRecordType()) {
3974 QualType InitType = InitList->getInit(0)->getType();
3975 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00003976 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00003977 Expr *InitListAsExpr = InitList;
3978 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003979 DestType, Sequence,
3980 /*InitListSyntax*/false,
3981 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00003982 return;
3983 }
3984 }
3985 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3986 Expr *SubInit[1] = {InitList->getInit(0)};
3987 if (!isa<VariableArrayType>(DestAT) &&
3988 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3989 InitializationKind SubKind =
3990 Kind.getKind() == InitializationKind::IK_DirectList
3991 ? InitializationKind::CreateDirect(Kind.getLocation(),
3992 InitList->getLBraceLoc(),
3993 InitList->getRBraceLoc())
3994 : Kind;
3995 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00003996 /*TopLevelOfInitList*/ true,
3997 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00003998
3999 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4000 // the element is not an appropriately-typed string literal, in which
4001 // case we should proceed as in C++11 (below).
4002 if (Sequence) {
4003 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4004 return;
4005 }
4006 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004007 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004008 }
Larisse Voufod2010992015-01-24 23:09:54 +00004009
4010 // C++11 [dcl.init.list]p3:
4011 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004012 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4013 (S.getLangOpts().CPlusPlus11 &&
4014 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004015 if (S.getLangOpts().CPlusPlus11) {
4016 // - Otherwise, if the initializer list has no elements and T is a
4017 // class type with a default constructor, the object is
4018 // value-initialized.
4019 if (InitList->getNumInits() == 0) {
4020 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4021 if (RD->hasDefaultConstructor()) {
4022 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4023 return;
4024 }
4025 }
4026
4027 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4028 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004029 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4030 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004031 return;
4032
4033 // - Otherwise, if T is a class type, constructors are considered.
4034 Expr *InitListAsExpr = InitList;
4035 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004036 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004037 } else
4038 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4039 return;
4040 }
4041
Richard Smith089c3162013-09-21 21:55:46 +00004042 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004043 InitList->getNumInits() == 1) {
4044 Expr *E = InitList->getInit(0);
4045
4046 // - Otherwise, if T is an enumeration with a fixed underlying type,
4047 // the initializer-list has a single element v, and the initialization
4048 // is direct-list-initialization, the object is initialized with the
4049 // value T(v); if a narrowing conversion is required to convert v to
4050 // the underlying type of T, the program is ill-formed.
4051 auto *ET = DestType->getAs<EnumType>();
4052 if (S.getLangOpts().CPlusPlus1z &&
4053 Kind.getKind() == InitializationKind::IK_DirectList &&
4054 ET && ET->getDecl()->isFixed() &&
4055 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4056 (E->getType()->isIntegralOrEnumerationType() ||
4057 E->getType()->isFloatingType())) {
4058 // There are two ways that T(v) can work when T is an enumeration type.
4059 // If there is either an implicit conversion sequence from v to T or
4060 // a conversion function that can convert from v to T, then we use that.
4061 // Otherwise, if v is of integral, enumeration, or floating-point type,
4062 // it is converted to the enumeration type via its underlying type.
4063 // There is no overlap possible between these two cases (except when the
4064 // source value is already of the destination type), and the first
4065 // case is handled by the general case for single-element lists below.
4066 ImplicitConversionSequence ICS;
4067 ICS.setStandard();
4068 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004069 if (!E->isRValue())
4070 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004071 // If E is of a floating-point type, then the conversion is ill-formed
4072 // due to narrowing, but go through the motions in order to produce the
4073 // right diagnostic.
4074 ICS.Standard.Second = E->getType()->isFloatingType()
4075 ? ICK_Floating_Integral
4076 : ICK_Integral_Conversion;
4077 ICS.Standard.setFromType(E->getType());
4078 ICS.Standard.setToType(0, E->getType());
4079 ICS.Standard.setToType(1, DestType);
4080 ICS.Standard.setToType(2, DestType);
4081 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4082 /*TopLevelOfInitList*/true);
4083 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4084 return;
4085 }
4086
Richard Smith089c3162013-09-21 21:55:46 +00004087 // - Otherwise, if the initializer list has a single element of type E
4088 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004089 // initialized from that element (by copy-initialization for
4090 // copy-list-initialization, or by direct-initialization for
4091 // direct-list-initialization); if a narrowing conversion is required
4092 // to convert the element to T, the program is ill-formed.
4093 //
Richard Smith089c3162013-09-21 21:55:46 +00004094 // Per core-24034, this is direct-initialization if we were performing
4095 // direct-list-initialization and copy-initialization otherwise.
4096 // We can't use InitListChecker for this, because it always performs
4097 // copy-initialization. This only matters if we might use an 'explicit'
4098 // conversion operator, so we only need to handle the cases where the source
4099 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004100 if (InitList->getInit(0)->getType()->isRecordType()) {
4101 InitializationKind SubKind =
4102 Kind.getKind() == InitializationKind::IK_DirectList
4103 ? InitializationKind::CreateDirect(Kind.getLocation(),
4104 InitList->getLBraceLoc(),
4105 InitList->getRBraceLoc())
4106 : Kind;
4107 Expr *SubInit[1] = { InitList->getInit(0) };
4108 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4109 /*TopLevelOfInitList*/true,
4110 TreatUnavailableAsInvalid);
4111 if (Sequence)
4112 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4113 return;
4114 }
Richard Smith089c3162013-09-21 21:55:46 +00004115 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004116
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004117 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004118 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004119 if (CheckInitList.HadError()) {
4120 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4121 return;
4122 }
4123
4124 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004125 Sequence.AddListInitializationStep(DestType);
4126}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004127
4128/// \brief Try a reference initialization that involves calling a conversion
4129/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004130static OverloadingResult TryRefInitWithConversionFunction(
4131 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4132 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4133 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004134 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004135 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4136 QualType T1 = cv1T1.getUnqualifiedType();
4137 QualType cv2T2 = Initializer->getType();
4138 QualType T2 = cv2T2.getUnqualifiedType();
4139
4140 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004141 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004142 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004144 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004145 ObjCConversion,
4146 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004147 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004148 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004149 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004150 (void)ObjCLifetimeConversion;
4151
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004152 // Build the candidate set directly in the initialization sequence
4153 // structure, so that it will persist if we fail.
4154 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004155 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004156
4157 // Determine whether we are allowed to call explicit constructors or
4158 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004159 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00004160 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4161
Craig Topperc3ec1492014-05-26 06:22:03 +00004162 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004163 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004164 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004165 // The type we're converting to is a class type. Enumerate its constructors
4166 // to see if there is a suitable conversion.
4167 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004168
Richard Smith40c78062015-02-21 02:31:57 +00004169 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004170 auto Info = getConstructorInfo(D);
4171 if (!Info.Constructor)
4172 continue;
John McCalla0296f72010-03-19 07:35:19 +00004173
Richard Smithc2bebe92016-05-11 20:37:46 +00004174 if (!Info.Constructor->isInvalidDecl() &&
4175 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4176 if (Info.ConstructorTmpl)
4177 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004178 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004179 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004180 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004181 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004182 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004183 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004184 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004187 }
John McCall3696dcb2010-08-17 07:23:57 +00004188 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4189 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190
Craig Topperc3ec1492014-05-26 06:22:03 +00004191 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004192 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004193 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004194 // The type we're converting from is a class type, enumerate its conversion
4195 // functions.
4196 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4197
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004198 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4199 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004200 NamedDecl *D = *I;
4201 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4202 if (isa<UsingShadowDecl>(D))
4203 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004205 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4206 CXXConversionDecl *Conv;
4207 if (ConvTemplate)
4208 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4209 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004210 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004212 // If the conversion function doesn't return a reference type,
4213 // it can't be considered for this conversion unless we're allowed to
4214 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215 // FIXME: Do we need to make sure that we only consider conversion
4216 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004217 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004218 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004219 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4220 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004221 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004222 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004223 DestType, CandidateSet,
4224 /*AllowObjCConversionOnExplicit=*/
4225 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004226 else
John McCalla0296f72010-03-19 07:35:19 +00004227 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004228 Initializer, DestType, CandidateSet,
4229 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004230 }
4231 }
4232 }
John McCall3696dcb2010-08-17 07:23:57 +00004233 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4234 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004236 SourceLocation DeclLoc = Initializer->getLocStart();
4237
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004239 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004241 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004242 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004243
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004244 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004245 // This is the overload that will be used for this initialization step if we
4246 // use this initialization. Mark it as referenced.
4247 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004248
Richard Smithb8c0f552016-12-09 18:49:13 +00004249 // Compute the returned type and value kind of the conversion.
4250 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004251 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004252 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004253 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004254 cv3T3 = T1;
4255
4256 ExprValueKind VK = VK_RValue;
4257 if (cv3T3->isLValueReferenceType())
4258 VK = VK_LValue;
4259 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4260 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4261 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004262
4263 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004264 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004265 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004266 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004267
Richard Smithb8c0f552016-12-09 18:49:13 +00004268 // Determine whether we'll need to perform derived-to-base adjustments or
4269 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004270 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004271 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004272 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004274 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004275 NewDerivedToBase, NewObjCConversion,
4276 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004277
4278 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004279 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004280 assert(!isa<CXXConstructorDecl>(Function) &&
4281 "should not have conversion after constructor");
4282
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004283 ImplicitConversionSequence ICS;
4284 ICS.setStandard();
4285 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004286 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4287
4288 // Every implicit conversion results in a prvalue, except for a glvalue
4289 // derived-to-base conversion, which we handle below.
4290 cv3T3 = ICS.Standard.getToType(2);
4291 VK = VK_RValue;
4292 }
4293
4294 // If the converted initializer is a prvalue, its type T4 is adjusted to
4295 // type "cv1 T4" and the temporary materialization conversion is applied.
4296 //
4297 // We adjust the cv-qualifications to match the reference regardless of
4298 // whether we have a prvalue so that the AST records the change. In this
4299 // case, T4 is "cv3 T3".
4300 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4301 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4302 Sequence.AddQualificationConversionStep(cv1T4, VK);
4303 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4304 VK = IsLValueRef ? VK_LValue : VK_XValue;
4305
4306 if (NewDerivedToBase)
4307 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004308 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004309 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004310
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004311 return OR_Success;
4312}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Richard Smithc620f552011-10-19 16:55:56 +00004314static void CheckCXX98CompatAccessibleCopy(Sema &S,
4315 const InitializedEntity &Entity,
4316 Expr *CurInitExpr);
4317
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4319static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004320 const InitializedEntity &Entity,
4321 const InitializationKind &Kind,
4322 Expr *Initializer,
4323 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004324 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004325 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004326 Qualifiers T1Quals;
4327 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004328 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004329 Qualifiers T2Quals;
4330 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004331
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004332 // If the initializer is the address of an overloaded function, try
4333 // to resolve the overloaded function. If all goes well, T2 is the
4334 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004335 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4336 T1, Sequence))
4337 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004338
Sebastian Redl29526f02011-11-27 16:50:07 +00004339 // Delegate everything else to a subfunction.
4340 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4341 T1Quals, cv2T2, T2, T2Quals, Sequence);
4342}
4343
Richard Smithb8c0f552016-12-09 18:49:13 +00004344/// Determine whether an expression is a non-referenceable glvalue (one to
4345/// which a reference can never bind). Attemting to bind a reference to
4346/// such a glvalue will always create a temporary.
4347static bool isNonReferenceableGLValue(Expr *E) {
4348 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004349}
4350
Sebastian Redl29526f02011-11-27 16:50:07 +00004351/// \brief Reference initialization without resolving overloaded functions.
4352static void TryReferenceInitializationCore(Sema &S,
4353 const InitializedEntity &Entity,
4354 const InitializationKind &Kind,
4355 Expr *Initializer,
4356 QualType cv1T1, QualType T1,
4357 Qualifiers T1Quals,
4358 QualType cv2T2, QualType T2,
4359 Qualifiers T2Quals,
4360 InitializationSequence &Sequence) {
4361 QualType DestType = Entity.getType();
4362 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004363 // Compute some basic properties of the types and the initializer.
4364 bool isLValueRef = DestType->isLValueReferenceType();
4365 bool isRValueRef = !isLValueRef;
4366 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004367 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004368 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004369 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004370 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004371 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004372 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004373
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004374 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004376 // "cv2 T2" as follows:
4377 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004379 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004380 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004381 // there are no function rvalues in C++, rvalue refs to functions are treated
4382 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004383 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004384 bool T1Function = T1->isFunctionType();
4385 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004386 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004387 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004389 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004391 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004392 if (T1Quals != T2Quals)
4393 // Convert to cv1 T2. This should only add qualifiers unless this is a
4394 // c-style cast. The removal of qualifiers in that case notionally
4395 // happens after the reference binding, but that doesn't matter.
4396 Sequence.AddQualificationConversionStep(
4397 S.Context.getQualifiedType(T2, T1Quals),
4398 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004399 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004400 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004401 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004402 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004403
Richard Smithb8c0f552016-12-09 18:49:13 +00004404 // We only create a temporary here when binding a reference to a
4405 // bit-field or vector element. Those cases are't supposed to be
4406 // handled by this bullet, but the outcome is the same either way.
4407 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004408 return;
4409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
4411 // - has a class type (i.e., T2 is a class type), where T1 is not
4412 // reference-related to T2, and can be implicitly converted to an
4413 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4414 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004415 // applicable conversion functions (13.3.1.6) and choosing the best
4416 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004417 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004418 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004419 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4420 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004421 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004422 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4423 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004424 if (ConvOvlResult == OR_Success)
4425 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004426 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004427 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004428 InitializationSequence::FK_ReferenceInitOverloadFailed,
4429 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004430 }
4431 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004432
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004434 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004435 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004436 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004437 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4438 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4439 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004440 Sequence.SetOverloadFailure(
4441 InitializationSequence::FK_ReferenceInitOverloadFailed,
4442 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004443 else if (!InitCategory.isLValue())
4444 Sequence.SetFailed(
4445 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4446 else {
4447 InitializationSequence::FailureKind FK;
4448 switch (RefRelationship) {
4449 case Sema::Ref_Compatible:
4450 if (Initializer->refersToBitField())
4451 FK = InitializationSequence::
4452 FK_NonConstLValueReferenceBindingToBitfield;
4453 else if (Initializer->refersToVectorElement())
4454 FK = InitializationSequence::
4455 FK_NonConstLValueReferenceBindingToVectorElement;
4456 else
4457 llvm_unreachable("unexpected kind of compatible initializer");
4458 break;
4459 case Sema::Ref_Related:
4460 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4461 break;
4462 case Sema::Ref_Incompatible:
4463 FK = InitializationSequence::
4464 FK_NonConstLValueReferenceBindingToUnrelated;
4465 break;
4466 }
4467 Sequence.SetFailed(FK);
4468 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004469 return;
4470 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004471
Douglas Gregor92e460e2011-01-20 16:44:54 +00004472 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004473 // - is an
4474 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4475 // [1z] rvalue (but not a bit-field) or
4476 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4477 //
4478 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004479 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004480 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004482 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004483 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004484 (InitCategory.isPRValue() &&
4485 (S.getLangOpts().CPlusPlus1z || T2->isRecordType() ||
4486 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004487 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004488 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004489 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4490 // compiler the freedom to perform a copy here or bind to the
4491 // object, while C++0x requires that we bind directly to the
4492 // object. Hence, we always bind to the object without making an
4493 // extra copy. However, in C++03 requires that we check for the
4494 // presence of a suitable copy constructor:
4495 //
4496 // The constructor that would be used to make the copy shall
4497 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004498 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004499 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004500 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004501 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Richard Smithb8c0f552016-12-09 18:49:13 +00004504 // C++1z [dcl.init.ref]/5.2.1.2:
4505 // If the converted initializer is a prvalue, its type T4 is adjusted
4506 // to type "cv1 T4" and the temporary materialization conversion is
4507 // applied.
4508 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4509 if (T1Quals != T2Quals)
4510 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4511 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4512 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4513
4514 // In any case, the reference is bound to the resulting glvalue (or to
4515 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004516 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004517 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004518 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004519 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
4523 // - has a class type (i.e., T2 is a class type), where T1 is not
4524 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004525 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4526 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004527 //
4528 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004529 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004530 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004531 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004532 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4533 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004534 if (ConvOvlResult)
4535 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004536 InitializationSequence::FK_ReferenceInitOverloadFailed,
4537 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004539 return;
4540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541
Richard Smithce766292016-10-21 23:01:55 +00004542 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004543 isRValueRef && InitCategory.isLValue()) {
4544 Sequence.SetFailed(
4545 InitializationSequence::FK_RValueReferenceBindingToLValue);
4546 return;
4547 }
4548
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004549 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4550 return;
4551 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004552
4553 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004554 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004555 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004556 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004557
John McCallec6f4e92010-06-04 02:29:22 +00004558 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4559
Richard Smith2eabf782013-06-13 00:57:57 +00004560 // FIXME: Why do we use an implicit conversion here rather than trying
4561 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004562 ImplicitConversionSequence ICS
4563 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004564 /*SuppressUserConversions=*/false,
4565 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004566 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004567 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4568 /*AllowObjCWritebackConversion=*/false);
4569
4570 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004571 // FIXME: Use the conversion function set stored in ICS to turn
4572 // this into an overloading ambiguity diagnostic. However, we need
4573 // to keep that set as an OverloadCandidateSet rather than as some
4574 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004575 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4576 Sequence.SetOverloadFailure(
4577 InitializationSequence::FK_ReferenceInitOverloadFailed,
4578 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004579 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4580 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004581 else
4582 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004583 return;
John McCall31168b02011-06-15 23:02:42 +00004584 } else {
4585 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004586 }
4587
4588 // [...] If T1 is reference-related to T2, cv1 must be the
4589 // same cv-qualification as, or greater cv-qualification
4590 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004591 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4592 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004594 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004595 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4596 return;
4597 }
4598
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004600 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004602 InitCategory.isLValue()) {
4603 Sequence.SetFailed(
4604 InitializationSequence::FK_RValueReferenceBindingToLValue);
4605 return;
4606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004608 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004609}
4610
4611/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612/// (C++ [dcl.init.string], C99 6.7.8).
4613static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004614 const InitializedEntity &Entity,
4615 const InitializationKind &Kind,
4616 Expr *Initializer,
4617 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004618 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004619}
4620
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004621/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004623 const InitializedEntity &Entity,
4624 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004625 InitializationSequence &Sequence,
4626 InitListExpr *InitList) {
4627 assert((!InitList || InitList->getNumInits() == 0) &&
4628 "Shouldn't use value-init for non-empty init lists");
4629
Richard Smith1bfe0682012-02-14 21:14:13 +00004630 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004631 //
4632 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004633 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004635 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004636 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004637
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004638 if (const RecordType *RT = T->getAs<RecordType>()) {
4639 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004640 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004641 // C++98:
4642 // -- if T is a class type (clause 9) with a user-declared constructor
4643 // (12.1), then the default constructor for T is called (and the
4644 // initialization is ill-formed if T has no accessible default
4645 // constructor);
4646 // C++11:
4647 // -- if T is a class type (clause 9) with either no default constructor
4648 // (12.1 [class.ctor]) or a default constructor that is user-provided
4649 // or deleted, then the object is default-initialized;
4650 //
4651 // Note that the C++11 rule is the same as the C++98 rule if there are no
4652 // defaulted or deleted constructors, so we just use it unconditionally.
4653 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4654 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4655 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656
Richard Smith1bfe0682012-02-14 21:14:13 +00004657 // -- if T is a (possibly cv-qualified) non-union class type without a
4658 // user-provided or deleted default constructor, then the object is
4659 // zero-initialized and, if T has a non-trivial default constructor,
4660 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004661 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4662 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004663 if (NeedZeroInitialization)
4664 Sequence.AddZeroInitializationStep(Entity.getType());
4665
Richard Smith593f9932012-12-08 02:01:17 +00004666 // C++03:
4667 // -- if T is a non-union class type without a user-declared constructor,
4668 // then every non-static data member and base class component of T is
4669 // value-initialized;
4670 // [...] A program that calls for [...] value-initialization of an
4671 // entity of reference type is ill-formed.
4672 //
4673 // C++11 doesn't need this handling, because value-initialization does not
4674 // occur recursively there, and the implicit default constructor is
4675 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004676 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004677 ClassDecl->hasUninitializedReferenceMember()) {
4678 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4679 return;
4680 }
4681
Richard Smithd86812d2012-07-05 08:39:21 +00004682 // If this is list-value-initialization, pass the empty init list on when
4683 // building the constructor call. This affects the semantics of a few
4684 // things (such as whether an explicit default constructor can be called).
4685 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004686 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004687 bool InitListSyntax = InitList;
4688
Richard Smith81f5ade2016-12-15 02:28:18 +00004689 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004690 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4691 return TryConstructorInitialization(
4692 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004693 }
4694 }
4695
Douglas Gregor1b303932009-12-22 15:35:07 +00004696 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004697}
4698
Douglas Gregor85dabae2009-12-16 01:38:02 +00004699/// \brief Attempt default initialization (C++ [dcl.init]p6).
4700static void TryDefaultInitialization(Sema &S,
4701 const InitializedEntity &Entity,
4702 const InitializationKind &Kind,
4703 InitializationSequence &Sequence) {
4704 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705
Douglas Gregor85dabae2009-12-16 01:38:02 +00004706 // C++ [dcl.init]p6:
4707 // To default-initialize an object of type T means:
4708 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004709 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4710
Douglas Gregor85dabae2009-12-16 01:38:02 +00004711 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4712 // constructor for T is called (and the initialization is ill-formed if
4713 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004714 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004715 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4716 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004717 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719
Douglas Gregor85dabae2009-12-16 01:38:02 +00004720 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721
Douglas Gregor85dabae2009-12-16 01:38:02 +00004722 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004724 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004725 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004726 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4727 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004728 return;
4729 }
4730
4731 // If the destination type has a lifetime property, zero-initialize it.
4732 if (DestType.getQualifiers().hasObjCLifetime()) {
4733 Sequence.AddZeroInitializationStep(Entity.getType());
4734 return;
4735 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004736}
4737
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004738/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4739/// which enumerates all conversion functions and performs overload resolution
4740/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004742 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004743 const InitializationKind &Kind,
4744 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004745 InitializationSequence &Sequence,
4746 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004747 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4748 QualType SourceType = Initializer->getType();
4749 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4750 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004751
Douglas Gregor540c3b02009-12-14 17:27:33 +00004752 // Build the candidate set directly in the initialization sequence
4753 // structure, so that it will persist if we fail.
4754 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004755 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004756
Douglas Gregor540c3b02009-12-14 17:27:33 +00004757 // Determine whether we are allowed to call explicit constructors or
4758 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004759 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760
Douglas Gregor540c3b02009-12-14 17:27:33 +00004761 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4762 // The type we're converting to is a class type. Enumerate its constructors
4763 // to see if there is a suitable conversion.
4764 CXXRecordDecl *DestRecordDecl
4765 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004766
Douglas Gregord9848152010-04-26 14:36:57 +00004767 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004768 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004769 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004770 auto Info = getConstructorInfo(D);
4771 if (!Info.Constructor)
4772 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773
Richard Smithc2bebe92016-05-11 20:37:46 +00004774 if (!Info.Constructor->isInvalidDecl() &&
4775 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4776 if (Info.ConstructorTmpl)
4777 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004778 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004779 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004780 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004781 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004782 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004783 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004784 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004786 }
Douglas Gregord9848152010-04-26 14:36:57 +00004787 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004788 }
Eli Friedman78275202009-12-19 08:11:05 +00004789
4790 SourceLocation DeclLoc = Initializer->getLocStart();
4791
Douglas Gregor540c3b02009-12-14 17:27:33 +00004792 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4793 // The type we're converting from is a class type, enumerate its conversion
4794 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004795
Eli Friedman4afe9a32009-12-20 22:12:03 +00004796 // We can only enumerate the conversion functions for a complete type; if
4797 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004798 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004799 CXXRecordDecl *SourceRecordDecl
4800 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004802 const auto &Conversions =
4803 SourceRecordDecl->getVisibleConversionFunctions();
4804 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004805 NamedDecl *D = *I;
4806 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4807 if (isa<UsingShadowDecl>(D))
4808 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809
Eli Friedman4afe9a32009-12-20 22:12:03 +00004810 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4811 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004812 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004813 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004814 else
John McCallda4458e2010-03-31 01:36:47 +00004815 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004816
Eli Friedman4afe9a32009-12-20 22:12:03 +00004817 if (AllowExplicit || !Conv->isExplicit()) {
4818 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004819 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004820 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004821 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004822 else
John McCalla0296f72010-03-19 07:35:19 +00004823 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004824 Initializer, DestType, CandidateSet,
4825 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004826 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004827 }
4828 }
4829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
4831 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004832 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004833 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004834 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004835 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004837 Result);
4838 return;
4839 }
John McCall0d1da222010-01-12 00:44:57 +00004840
Douglas Gregor540c3b02009-12-14 17:27:33 +00004841 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004842 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004843 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844
Douglas Gregor540c3b02009-12-14 17:27:33 +00004845 if (isa<CXXConstructorDecl>(Function)) {
4846 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004847 // subsumed by the initialization. Per DR5, the created temporary is of the
4848 // cv-unqualified type of the destination.
4849 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4850 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004851 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00004852
4853 // C++14 and before:
4854 // - if the function is a constructor, the call initializes a temporary
4855 // of the cv-unqualified version of the destination type. The [...]
4856 // temporary [...] is then used to direct-initialize, according to the
4857 // rules above, the object that is the destination of the
4858 // copy-initialization.
4859 // Note that this just performs a simple object copy from the temporary.
4860 //
4861 // C++1z:
4862 // - if the function is a constructor, the call is a prvalue of the
4863 // cv-unqualified version of the destination type whose return object
4864 // is initialized by the constructor. The call is used to
4865 // direct-initialize, according to the rules above, the object that
4866 // is the destination of the copy-initialization.
4867 // Therefore we need to do nothing further.
4868 //
4869 // FIXME: Mark this copy as extraneous.
4870 if (!S.getLangOpts().CPlusPlus1z)
4871 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004872 else if (DestType.hasQualifiers())
4873 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004874 return;
4875 }
4876
4877 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004878 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004879 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4880 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881
Richard Smithb8c0f552016-12-09 18:49:13 +00004882 if (ConvType->getAs<RecordType>()) {
4883 // The call is used to direct-initialize [...] the object that is the
4884 // destination of the copy-initialization.
4885 //
4886 // In C++1z, this does not call a constructor if we enter /17.6.1:
4887 // - If the initializer expression is a prvalue and the cv-unqualified
4888 // version of the source type is the same as the class of the
4889 // destination [... do not make an extra copy]
4890 //
4891 // FIXME: Mark this copy as extraneous.
4892 if (!S.getLangOpts().CPlusPlus1z ||
4893 Function->getReturnType()->isReferenceType() ||
4894 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4895 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004896 else if (!S.Context.hasSameType(ConvType, DestType))
4897 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00004898 return;
4899 }
4900
Douglas Gregor5ab11652010-04-17 22:01:05 +00004901 // If the conversion following the call to the conversion function
4902 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004903 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4904 Best->FinalConversion.Third) {
4905 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004906 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004907 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004908 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004909 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004910}
4911
Richard Smithf032001b2013-06-20 02:18:31 +00004912/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4913/// a function with a pointer return type contains a 'return false;' statement.
4914/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4915/// code using that header.
4916///
4917/// Work around this by treating 'return false;' as zero-initializing the result
4918/// if it's used in a pointer-returning function in a system header.
4919static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4920 const InitializedEntity &Entity,
4921 const Expr *Init) {
4922 return S.getLangOpts().CPlusPlus11 &&
4923 Entity.getKind() == InitializedEntity::EK_Result &&
4924 Entity.getType()->isPointerType() &&
4925 isa<CXXBoolLiteralExpr>(Init) &&
4926 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4927 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4928}
4929
John McCall31168b02011-06-15 23:02:42 +00004930/// The non-zero enum values here are indexes into diagnostic alternatives.
4931enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4932
4933/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004934static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004935 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004936 // Skip parens.
4937 e = e->IgnoreParens();
4938
4939 // Skip address-of nodes.
4940 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4941 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004942 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4943 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004944
4945 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004946 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4947 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004948 case CK_Dependent:
4949 case CK_BitCast:
4950 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004951 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004952 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004953
4954 case CK_ArrayToPointerDecay:
4955 return IIK_nonscalar;
4956
4957 case CK_NullToPointer:
4958 return IIK_okay;
4959
4960 default:
4961 break;
4962 }
4963
4964 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004965 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004966 // set isWeakAccess to true, to mean that there will be an implicit
4967 // load which requires a cleanup.
4968 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4969 isWeakAccess = true;
4970
John McCall63f84442011-06-27 23:59:58 +00004971 if (!isAddressOf) return IIK_nonlocal;
4972
John McCall113bee02012-03-10 09:33:50 +00004973 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4974 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004975
4976 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004977
4978 // If we have a conditional operator, check both sides.
4979 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004980 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4981 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004982 return iik;
4983
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004984 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004985
4986 // These are never scalar.
4987 } else if (isa<ArraySubscriptExpr>(e)) {
4988 return IIK_nonscalar;
4989
4990 // Otherwise, it needs to be a null pointer constant.
4991 } else {
4992 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4993 ? IIK_okay : IIK_nonlocal);
4994 }
4995
4996 return IIK_nonlocal;
4997}
4998
4999/// Check whether the given expression is a valid operand for an
5000/// indirect copy/restore.
5001static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5002 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005003 bool isWeakAccess = false;
5004 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5005 // If isWeakAccess to true, there will be an implicit
5006 // load which requires a cleanup.
5007 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005008 S.Cleanup.setExprNeedsCleanups(true);
5009
John McCall31168b02011-06-15 23:02:42 +00005010 if (iik == IIK_okay) return;
5011
5012 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5013 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5014 << src->getSourceRange();
5015}
5016
Douglas Gregore2f943b2011-02-22 18:29:51 +00005017/// \brief Determine whether we have compatible array types for the
5018/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005019static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005020 const ArrayType *Source) {
5021 // If the source and destination array types are equivalent, we're
5022 // done.
5023 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5024 return true;
5025
5026 // Make sure that the element types are the same.
5027 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5028 return false;
5029
5030 // The only mismatch we allow is when the destination is an
5031 // incomplete array type and the source is a constant array type.
5032 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5033}
5034
John McCall31168b02011-06-15 23:02:42 +00005035static bool tryObjCWritebackConversion(Sema &S,
5036 InitializationSequence &Sequence,
5037 const InitializedEntity &Entity,
5038 Expr *Initializer) {
5039 bool ArrayDecay = false;
5040 QualType ArgType = Initializer->getType();
5041 QualType ArgPointee;
5042 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5043 ArrayDecay = true;
5044 ArgPointee = ArgArrayType->getElementType();
5045 ArgType = S.Context.getPointerType(ArgPointee);
5046 }
5047
5048 // Handle write-back conversion.
5049 QualType ConvertedArgType;
5050 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5051 ConvertedArgType))
5052 return false;
5053
5054 // We should copy unless we're passing to an argument explicitly
5055 // marked 'out'.
5056 bool ShouldCopy = true;
5057 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5058 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5059
5060 // Do we need an lvalue conversion?
5061 if (ArrayDecay || Initializer->isGLValue()) {
5062 ImplicitConversionSequence ICS;
5063 ICS.setStandard();
5064 ICS.Standard.setAsIdentityConversion();
5065
5066 QualType ResultType;
5067 if (ArrayDecay) {
5068 ICS.Standard.First = ICK_Array_To_Pointer;
5069 ResultType = S.Context.getPointerType(ArgPointee);
5070 } else {
5071 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5072 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5073 }
5074
5075 Sequence.AddConversionSequenceStep(ICS, ResultType);
5076 }
5077
5078 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5079 return true;
5080}
5081
Guy Benyei61054192013-02-07 10:55:47 +00005082static bool TryOCLSamplerInitialization(Sema &S,
5083 InitializationSequence &Sequence,
5084 QualType DestType,
5085 Expr *Initializer) {
5086 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005087 (!Initializer->isIntegerConstantExpr(S.Context) &&
5088 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005089 return false;
5090
5091 Sequence.AddOCLSamplerInitStep(DestType);
5092 return true;
5093}
5094
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005095//
5096// OpenCL 1.2 spec, s6.12.10
5097//
5098// The event argument can also be used to associate the
5099// async_work_group_copy with a previous async copy allowing
5100// an event to be shared by multiple async copies; otherwise
5101// event should be zero.
5102//
5103static bool TryOCLZeroEventInitialization(Sema &S,
5104 InitializationSequence &Sequence,
5105 QualType DestType,
5106 Expr *Initializer) {
5107 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5108 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5109 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5110 return false;
5111
5112 Sequence.AddOCLZeroEventStep(DestType);
5113 return true;
5114}
5115
Egor Churaev89831422016-12-23 14:55:49 +00005116static bool TryOCLZeroQueueInitialization(Sema &S,
5117 InitializationSequence &Sequence,
5118 QualType DestType,
5119 Expr *Initializer) {
5120 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5121 !DestType->isQueueT() ||
5122 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5123 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5124 return false;
5125
5126 Sequence.AddOCLZeroQueueStep(DestType);
5127 return true;
5128}
5129
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005130InitializationSequence::InitializationSequence(Sema &S,
5131 const InitializedEntity &Entity,
5132 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005133 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005134 bool TopLevelOfInitList,
5135 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005136 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005137 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5138 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005139}
5140
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005141/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5142/// address of that function, this returns true. Otherwise, it returns false.
5143static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5144 auto *DRE = dyn_cast<DeclRefExpr>(E);
5145 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5146 return false;
5147
5148 return !S.checkAddressOfFunctionIsAvailable(
5149 cast<FunctionDecl>(DRE->getDecl()));
5150}
5151
Richard Smith410306b2016-12-12 02:53:20 +00005152/// Determine whether we can perform an elementwise array copy for this kind
5153/// of entity.
5154static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5155 switch (Entity.getKind()) {
5156 case InitializedEntity::EK_LambdaCapture:
5157 // C++ [expr.prim.lambda]p24:
5158 // For array members, the array elements are direct-initialized in
5159 // increasing subscript order.
5160 return true;
5161
5162 case InitializedEntity::EK_Variable:
5163 // C++ [dcl.decomp]p1:
5164 // [...] each element is copy-initialized or direct-initialized from the
5165 // corresponding element of the assignment-expression [...]
5166 return isa<DecompositionDecl>(Entity.getDecl());
5167
5168 case InitializedEntity::EK_Member:
5169 // C++ [class.copy.ctor]p14:
5170 // - if the member is an array, each element is direct-initialized with
5171 // the corresponding subobject of x
5172 return Entity.isImplicitMemberInitializer();
5173
5174 case InitializedEntity::EK_ArrayElement:
5175 // All the above cases are intended to apply recursively, even though none
5176 // of them actually say that.
5177 if (auto *E = Entity.getParent())
5178 return canPerformArrayCopy(*E);
5179 break;
5180
5181 default:
5182 break;
5183 }
5184
5185 return false;
5186}
5187
Richard Smith089c3162013-09-21 21:55:46 +00005188void InitializationSequence::InitializeFrom(Sema &S,
5189 const InitializedEntity &Entity,
5190 const InitializationKind &Kind,
5191 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005192 bool TopLevelOfInitList,
5193 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005194 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195
John McCall5e77d762013-04-16 07:28:30 +00005196 // Eliminate non-overload placeholder types in the arguments. We
5197 // need to do this before checking whether types are dependent
5198 // because lowering a pseudo-object expression might well give us
5199 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005200 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005201 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5202 // FIXME: should we be doing this here?
5203 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5204 if (result.isInvalid()) {
5205 SetFailed(FK_PlaceholderType);
5206 return;
5207 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005208 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005209 }
5210
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005211 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212 // The semantics of initializers are as follows. The destination type is
5213 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005214 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005215 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005216 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005217 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005218
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005219 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005220 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005221 SequenceKind = DependentSequence;
5222 return;
5223 }
5224
Sebastian Redld201edf2011-06-05 13:59:11 +00005225 // Almost everything is a normal sequence.
5226 setSequenceKind(NormalSequence);
5227
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005228 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005229 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005230 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005231 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005232 if (S.getLangOpts().ObjC1) {
5233 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5234 DestType, Initializer->getType(),
5235 Initializer) ||
5236 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5237 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005238 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005239 if (!isa<InitListExpr>(Initializer))
5240 SourceType = Initializer->getType();
5241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005242
Sebastian Redl0501c632012-02-12 16:37:36 +00005243 // - If the initializer is a (non-parenthesized) braced-init-list, the
5244 // object is list-initialized (8.5.4).
5245 if (Kind.getKind() != InitializationKind::IK_Direct) {
5246 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005247 TryListInitialization(S, Entity, Kind, InitList, *this,
5248 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005249 return;
5250 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005251 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005252
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005253 // - If the destination type is a reference type, see 8.5.3.
5254 if (DestType->isReferenceType()) {
5255 // C++0x [dcl.init.ref]p1:
5256 // A variable declared to be a T& or T&&, that is, "reference to type T"
5257 // (8.3.2), shall be initialized by an object, or function, of type T or
5258 // by an object that can be converted into a T.
5259 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005260 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005261 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005262 // C++17 [dcl.init.ref]p5:
5263 // A reference [...] is initialized by an expression [...] as follows:
5264 // If the initializer is not an expression, presumably we should reject,
5265 // but the standard fails to actually say so.
5266 else if (isa<InitListExpr>(Args[0]))
5267 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005268 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005269 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005270 return;
5271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005273 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005274 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005275 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005276 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005277 return;
5278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279
Douglas Gregor85dabae2009-12-16 01:38:02 +00005280 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005281 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005282 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005283 return;
5284 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005285
John McCall66884dd2011-02-21 07:22:22 +00005286 // - If the destination type is an array of characters, an array of
5287 // char16_t, an array of char32_t, or an array of wchar_t, and the
5288 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005289 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005290 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005291 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005292 if (Initializer && isa<VariableArrayType>(DestAT)) {
5293 SetFailed(FK_VariableLengthArrayHasInitializer);
5294 return;
5295 }
5296
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005297 if (Initializer) {
5298 switch (IsStringInit(Initializer, DestAT, Context)) {
5299 case SIF_None:
5300 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5301 return;
5302 case SIF_NarrowStringIntoWideChar:
5303 SetFailed(FK_NarrowStringIntoWideCharArray);
5304 return;
5305 case SIF_WideStringIntoChar:
5306 SetFailed(FK_WideStringIntoCharArray);
5307 return;
5308 case SIF_IncompatWideStringIntoWideChar:
5309 SetFailed(FK_IncompatWideStringIntoWideChar);
5310 return;
5311 case SIF_Other:
5312 break;
5313 }
John McCall66884dd2011-02-21 07:22:22 +00005314 }
5315
Richard Smith410306b2016-12-12 02:53:20 +00005316 // Some kinds of initialization permit an array to be initialized from
5317 // another array of the same type, and perform elementwise initialization.
5318 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5319 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5320 Entity.getType()) &&
5321 canPerformArrayCopy(Entity)) {
5322 // If source is a prvalue, use it directly.
5323 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005324 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005325 return;
5326 }
5327
5328 // Emit element-at-a-time copy loop.
5329 InitializedEntity Element =
5330 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5331 QualType InitEltT =
5332 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005333 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5334 Initializer->getValueKind(),
5335 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005336 Expr *OVEAsExpr = &OVE;
5337 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5338 TreatUnavailableAsInvalid);
5339 if (!Failed())
5340 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5341 return;
5342 }
5343
Douglas Gregore2f943b2011-02-22 18:29:51 +00005344 // Note: as an GNU C extension, we allow initialization of an
5345 // array from a compound literal that creates an array of the same
5346 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005347 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005348 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5349 Initializer->getType()->isArrayType()) {
5350 const ArrayType *SourceAT
5351 = Context.getAsArrayType(Initializer->getType());
5352 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005353 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005354 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005355 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005356 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005357 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005358 }
Richard Smithebeed412012-02-15 22:38:09 +00005359 }
Richard Smithd86812d2012-07-05 08:39:21 +00005360 // Note: as a GNU C++ extension, we allow list-initialization of a
5361 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005362 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005363 Entity.getKind() == InitializedEntity::EK_Member &&
5364 Initializer && isa<InitListExpr>(Initializer)) {
5365 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005366 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005367 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005368 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005369 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005370 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5371 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005372 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005373 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005374
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005375 return;
5376 }
Eli Friedman78275202009-12-19 08:11:05 +00005377
Larisse Voufod2010992015-01-24 23:09:54 +00005378 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005379 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005380 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005381 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005382
5383 // We're at the end of the line for C: it's either a write-back conversion
5384 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005385 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005386 // If allowed, check whether this is an Objective-C writeback conversion.
5387 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005388 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005389 return;
5390 }
Guy Benyei61054192013-02-07 10:55:47 +00005391
5392 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5393 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005394
5395 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5396 return;
5397
Egor Churaev89831422016-12-23 14:55:49 +00005398 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5399 return;
5400
John McCall31168b02011-06-15 23:02:42 +00005401 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005402 AddCAssignmentStep(DestType);
5403 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005404 return;
5405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005406
David Blaikiebbafb8a2012-03-11 07:00:24 +00005407 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005408
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005409 // - If the destination type is a (possibly cv-qualified) class type:
5410 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005411 // - If the initialization is direct-initialization, or if it is
5412 // copy-initialization where the cv-unqualified version of the
5413 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005414 // class of the destination, constructors are considered. [...]
5415 if (Kind.getKind() == InitializationKind::IK_Direct ||
5416 (Kind.getKind() == InitializationKind::IK_Copy &&
5417 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005418 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005419 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005420 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005421 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005422 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005424 // used) to a derived class thereof are enumerated as described in
5425 // 13.3.1.4, and the best one is chosen through overload resolution
5426 // (13.3).
5427 else
Richard Smith77be48a2014-07-31 06:31:19 +00005428 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005429 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005430 return;
5431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005432
Richard Smith49a6b6e2017-03-24 01:14:25 +00005433 assert(Args.size() >= 1 && "Zero-argument case handled above");
5434
5435 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005436 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005437 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005438 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005439 } else if (isa<InitListExpr>(Args[0])) {
5440 SetFailed(FK_ParenthesizedListInitForScalar);
5441 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005443
5444 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005445 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005446 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005447 // For a conversion to _Atomic(T) from either T or a class type derived
5448 // from T, initialize the T object then convert to _Atomic type.
5449 bool NeedAtomicConversion = false;
5450 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5451 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005452 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5453 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005454 DestType = Atomic->getValueType();
5455 NeedAtomicConversion = true;
5456 }
5457 }
5458
5459 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005460 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005461 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005462 if (!Failed() && NeedAtomicConversion)
5463 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005464 return;
5465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005466
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005467 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005468 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005469 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005470 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005471 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005472
John McCall31168b02011-06-15 23:02:42 +00005473 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005474 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005475 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005476 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005477 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005478 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5479 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005480
5481 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005482 ICS.Standard.Second == ICK_Writeback_Conversion) {
5483 // Objective-C ARC writeback conversion.
5484
5485 // We should copy unless we're passing to an argument explicitly
5486 // marked 'out'.
5487 bool ShouldCopy = true;
5488 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5489 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5490
5491 // If there was an lvalue adjustment, add it as a separate conversion.
5492 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5493 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5494 ImplicitConversionSequence LvalueICS;
5495 LvalueICS.setStandard();
5496 LvalueICS.Standard.setAsIdentityConversion();
5497 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5498 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005499 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005500 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005501
Richard Smith77be48a2014-07-31 06:31:19 +00005502 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005503 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005504 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005505 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5506 AddZeroInitializationStep(Entity.getType());
5507 } else if (Initializer->getType() == Context.OverloadTy &&
5508 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5509 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005510 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005511 else if (Initializer->getType()->isFunctionType() &&
5512 isExprAnUnaddressableFunction(S, Initializer))
5513 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005514 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005515 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005516 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005517 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005518
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005519 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005520 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005521}
5522
5523InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005524 for (auto &S : Steps)
5525 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005526}
5527
5528//===----------------------------------------------------------------------===//
5529// Perform initialization
5530//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005532getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005533 switch(Entity.getKind()) {
5534 case InitializedEntity::EK_Variable:
5535 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005536 case InitializedEntity::EK_Exception:
5537 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005538 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005539 return Sema::AA_Initializing;
5540
5541 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005542 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005543 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5544 return Sema::AA_Sending;
5545
Douglas Gregore1314a62009-12-18 05:02:21 +00005546 return Sema::AA_Passing;
5547
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005548 case InitializedEntity::EK_Parameter_CF_Audited:
5549 if (Entity.getDecl() &&
5550 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5551 return Sema::AA_Sending;
5552
5553 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5554
Douglas Gregore1314a62009-12-18 05:02:21 +00005555 case InitializedEntity::EK_Result:
5556 return Sema::AA_Returning;
5557
Douglas Gregore1314a62009-12-18 05:02:21 +00005558 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005559 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005560 // FIXME: Can we tell apart casting vs. converting?
5561 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562
Douglas Gregore1314a62009-12-18 05:02:21 +00005563 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005564 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005565 case InitializedEntity::EK_ArrayElement:
5566 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005567 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005568 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005569 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005570 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005571 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005572 return Sema::AA_Initializing;
5573 }
5574
David Blaikie8a40f702012-01-17 06:56:22 +00005575 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005576}
5577
Richard Smith27874d62013-01-08 00:08:23 +00005578/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005579/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005580static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005581 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005582 case InitializedEntity::EK_ArrayElement:
5583 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005584 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00005585 case InitializedEntity::EK_New:
5586 case InitializedEntity::EK_Variable:
5587 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005588 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005589 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005590 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005591 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005592 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005593 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005594 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005595 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005596 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005597
Douglas Gregore1314a62009-12-18 05:02:21 +00005598 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005599 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005600 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005601 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005602 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005603 return true;
5604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605
Douglas Gregore1314a62009-12-18 05:02:21 +00005606 llvm_unreachable("missed an InitializedEntity kind?");
5607}
5608
Douglas Gregor95562572010-04-24 23:45:46 +00005609/// \brief Whether the given entity, when initialized with an object
5610/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005611static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005612 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005613 case InitializedEntity::EK_Result:
5614 case InitializedEntity::EK_New:
5615 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005616 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005617 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005618 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005619 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005620 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005621 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005622 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623
Richard Smith27874d62013-01-08 00:08:23 +00005624 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005625 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005626 case InitializedEntity::EK_Variable:
5627 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005628 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005629 case InitializedEntity::EK_Temporary:
5630 case InitializedEntity::EK_ArrayElement:
5631 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005632 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005633 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005634 return true;
5635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005636
5637 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005638}
5639
Richard Smithc620f552011-10-19 16:55:56 +00005640/// \brief Get the location at which initialization diagnostics should appear.
5641static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5642 Expr *Initializer) {
5643 switch (Entity.getKind()) {
5644 case InitializedEntity::EK_Result:
5645 return Entity.getReturnLoc();
5646
5647 case InitializedEntity::EK_Exception:
5648 return Entity.getThrowLoc();
5649
5650 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005651 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005652 return Entity.getDecl()->getLocation();
5653
Douglas Gregor19666fb2012-02-15 16:57:26 +00005654 case InitializedEntity::EK_LambdaCapture:
5655 return Entity.getCaptureLoc();
5656
Richard Smithc620f552011-10-19 16:55:56 +00005657 case InitializedEntity::EK_ArrayElement:
5658 case InitializedEntity::EK_Member:
5659 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005660 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005661 case InitializedEntity::EK_Temporary:
5662 case InitializedEntity::EK_New:
5663 case InitializedEntity::EK_Base:
5664 case InitializedEntity::EK_Delegating:
5665 case InitializedEntity::EK_VectorElement:
5666 case InitializedEntity::EK_ComplexElement:
5667 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005668 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005669 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005670 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005671 return Initializer->getLocStart();
5672 }
5673 llvm_unreachable("missed an InitializedEntity kind?");
5674}
5675
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005676/// \brief Make a (potentially elidable) temporary copy of the object
5677/// provided by the given initializer by calling the appropriate copy
5678/// constructor.
5679///
5680/// \param S The Sema object used for type-checking.
5681///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005682/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005683/// the type of the initializer expression or a superclass thereof.
5684///
James Dennett634962f2012-06-14 21:40:34 +00005685/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005686///
5687/// \param CurInit The initializer expression.
5688///
5689/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5690/// is permitted in C++03 (but not C++0x) when binding a reference to
5691/// an rvalue.
5692///
5693/// \returns An expression that copies the initializer expression into
5694/// a temporary object, or an error expression if a copy could not be
5695/// created.
John McCalldadc5752010-08-24 06:29:42 +00005696static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005697 QualType T,
5698 const InitializedEntity &Entity,
5699 ExprResult CurInit,
5700 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005701 if (CurInit.isInvalid())
5702 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005703 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005704 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005705 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005706 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005707 Class = cast<CXXRecordDecl>(Record->getDecl());
5708 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005709 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005710
Richard Smithc620f552011-10-19 16:55:56 +00005711 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005712
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005714 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005715 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005716
Richard Smith7c2bcc92016-09-07 02:14:33 +00005717 // Perform overload resolution using the class's constructors. Per
5718 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005719 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005720 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005721 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005722
Douglas Gregore1314a62009-12-18 05:02:21 +00005723 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005724 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005725 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005726 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5727 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5728 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005729 case OR_Success:
5730 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005731
Douglas Gregore1314a62009-12-18 05:02:21 +00005732 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005733 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5734 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5735 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005736 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005737 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005738 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005739 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005740 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005741 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005742
Douglas Gregore1314a62009-12-18 05:02:21 +00005743 case OR_Ambiguous:
5744 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005745 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005746 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005747 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005748 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005749
Douglas Gregore1314a62009-12-18 05:02:21 +00005750 case OR_Deleted:
5751 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005752 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005753 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005754 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005755 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005756 }
5757
Richard Smith7c2bcc92016-09-07 02:14:33 +00005758 bool HadMultipleCandidates = CandidateSet.size() > 1;
5759
Douglas Gregor5ab11652010-04-17 22:01:05 +00005760 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005761 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005762 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005763
Richard Smith5179eb72016-06-28 19:03:57 +00005764 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5765 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005766
5767 if (IsExtraneousCopy) {
5768 // If this is a totally extraneous copy for C++03 reference
5769 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005770 // expression. We don't generate an (elided) copy operation here
5771 // because doing so would require us to pass down a flag to avoid
5772 // infinite recursion, where each step adds another extraneous,
5773 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005774
Douglas Gregor30b52772010-04-18 07:57:34 +00005775 // Instantiate the default arguments of any extra parameters in
5776 // the selected copy constructor, as if we were going to create a
5777 // proper call to the copy constructor.
5778 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5779 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5780 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005781 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005782 break;
5783
5784 // Build the default argument expression; we don't actually care
5785 // if this succeeds or not, because this routine will complain
5786 // if there was a problem.
5787 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5788 }
5789
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005790 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005792
Douglas Gregor5ab11652010-04-17 22:01:05 +00005793 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005794 // constructor call (we might have derived-to-base conversions, or
5795 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005796 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005797 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005798
Richard Smith7c2bcc92016-09-07 02:14:33 +00005799 // C++0x [class.copy]p32:
5800 // When certain criteria are met, an implementation is allowed to
5801 // omit the copy/move construction of a class object, even if the
5802 // copy/move constructor and/or destructor for the object have
5803 // side effects. [...]
5804 // - when a temporary class object that has not been bound to a
5805 // reference (12.2) would be copied/moved to a class object
5806 // with the same cv-unqualified type, the copy/move operation
5807 // can be omitted by constructing the temporary object
5808 // directly into the target of the omitted copy/move
5809 //
5810 // Note that the other three bullets are handled elsewhere. Copy
5811 // elision for return statements and throw expressions are handled as part
5812 // of constructor initialization, while copy elision for exception handlers
5813 // is handled by the run-time.
5814 //
5815 // FIXME: If the function parameter is not the same type as the temporary, we
5816 // should still be able to elide the copy, but we don't have a way to
5817 // represent in the AST how much should be elided in this case.
5818 bool Elidable =
5819 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5820 S.Context.hasSameUnqualifiedType(
5821 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5822 CurInitExpr->getType());
5823
Douglas Gregord0ace022010-04-25 00:55:24 +00005824 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00005825 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5826 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005827 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005828 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005829 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005830 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005831 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005832 CXXConstructExpr::CK_Complete,
5833 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005834
Douglas Gregord0ace022010-04-25 00:55:24 +00005835 // If we're supposed to bind temporaries, do so.
5836 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005837 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005838 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005839}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005840
Richard Smithc620f552011-10-19 16:55:56 +00005841/// \brief Check whether elidable copy construction for binding a reference to
5842/// a temporary would have succeeded if we were building in C++98 mode, for
5843/// -Wc++98-compat.
5844static void CheckCXX98CompatAccessibleCopy(Sema &S,
5845 const InitializedEntity &Entity,
5846 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005847 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005848
5849 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5850 if (!Record)
5851 return;
5852
5853 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005854 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005855 return;
5856
5857 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005858 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005859 DeclContext::lookup_result Ctors =
5860 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00005861
5862 // Perform overload resolution.
5863 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005864 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005865 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005866 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5867 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5868 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00005869
5870 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5871 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5872 << CurInitExpr->getSourceRange();
5873
5874 switch (OR) {
5875 case OR_Success:
5876 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00005877 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005878 // FIXME: Check default arguments as far as that's possible.
5879 break;
5880
5881 case OR_No_Viable_Function:
5882 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005883 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005884 break;
5885
5886 case OR_Ambiguous:
5887 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005888 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005889 break;
5890
5891 case OR_Deleted:
5892 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005893 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005894 break;
5895 }
5896}
5897
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005898void InitializationSequence::PrintInitLocationNote(Sema &S,
5899 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005900 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005901 if (Entity.getDecl()->getLocation().isInvalid())
5902 return;
5903
5904 if (Entity.getDecl()->getDeclName())
5905 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5906 << Entity.getDecl()->getDeclName();
5907 else
5908 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5909 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005910 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5911 Entity.getMethodDecl())
5912 S.Diag(Entity.getMethodDecl()->getLocation(),
5913 diag::note_method_return_type_change)
5914 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005915}
5916
Jordan Rose6c0505e2013-05-06 16:48:12 +00005917/// Returns true if the parameters describe a constructor initialization of
5918/// an explicit temporary object, e.g. "Point(x, y)".
5919static bool isExplicitTemporary(const InitializedEntity &Entity,
5920 const InitializationKind &Kind,
5921 unsigned NumArgs) {
5922 switch (Entity.getKind()) {
5923 case InitializedEntity::EK_Temporary:
5924 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005925 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005926 break;
5927 default:
5928 return false;
5929 }
5930
5931 switch (Kind.getKind()) {
5932 case InitializationKind::IK_DirectList:
5933 return true;
5934 // FIXME: Hack to work around cast weirdness.
5935 case InitializationKind::IK_Direct:
5936 case InitializationKind::IK_Value:
5937 return NumArgs != 1;
5938 default:
5939 return false;
5940 }
5941}
5942
Sebastian Redled2e5322011-12-22 14:44:04 +00005943static ExprResult
5944PerformConstructorInitialization(Sema &S,
5945 const InitializedEntity &Entity,
5946 const InitializationKind &Kind,
5947 MultiExprArg Args,
5948 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005949 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005950 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005951 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005952 SourceLocation LBraceLoc,
5953 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005954 unsigned NumArgs = Args.size();
5955 CXXConstructorDecl *Constructor
5956 = cast<CXXConstructorDecl>(Step.Function.Function);
5957 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5958
5959 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005960 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005961 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5962 ? Kind.getEqualLoc()
5963 : Kind.getLocation();
5964
5965 if (Kind.getKind() == InitializationKind::IK_Default) {
5966 // Force even a trivial, implicit default constructor to be
5967 // semantically checked. We do this explicitly because we don't build
5968 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005969 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005970 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005971 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005972 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5973 }
5974
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005975 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005976
Douglas Gregor6073dca2012-02-24 23:56:31 +00005977 // C++ [over.match.copy]p1:
5978 // - When initializing a temporary to be bound to the first parameter
5979 // of a constructor that takes a reference to possibly cv-qualified
5980 // T as its first argument, called with a single argument in the
5981 // context of direct-initialization, explicit conversion functions
5982 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00005983 bool AllowExplicitConv =
5984 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
5985 hasCopyOrMoveCtorParam(S.Context,
5986 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00005987
Sebastian Redled2e5322011-12-22 14:44:04 +00005988 // Determine the arguments required to actually perform the constructor
5989 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005990 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005991 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005992 AllowExplicitConv,
5993 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005994 return ExprError();
5995
5996
Jordan Rose6c0505e2013-05-06 16:48:12 +00005997 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005998 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00005999 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6000 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006001
6002 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6003 if (!TSInfo)
6004 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006005 SourceRange ParenOrBraceRange =
6006 (Kind.getKind() == InitializationKind::IK_DirectList)
6007 ? SourceRange(LBraceLoc, RBraceLoc)
6008 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006009
Richard Smith5179eb72016-06-28 19:03:57 +00006010 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006011 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006012 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006013 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6014 return ExprError();
6015 }
Richard Smith5179eb72016-06-28 19:03:57 +00006016 S.MarkFunctionReferenced(Loc, Constructor);
6017
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006018 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00006019 S.Context, Constructor,
6020 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006021 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6022 IsListInitialization, IsStdInitListInitialization,
6023 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006024 } else {
6025 CXXConstructExpr::ConstructionKind ConstructKind =
6026 CXXConstructExpr::CK_Complete;
6027
6028 if (Entity.getKind() == InitializedEntity::EK_Base) {
6029 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6030 CXXConstructExpr::CK_VirtualBase :
6031 CXXConstructExpr::CK_NonVirtualBase;
6032 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6033 ConstructKind = CXXConstructExpr::CK_Delegating;
6034 }
6035
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006036 // Only get the parenthesis or brace range if it is a list initialization or
6037 // direct construction.
6038 SourceRange ParenOrBraceRange;
6039 if (IsListInitialization)
6040 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6041 else if (Kind.getKind() == InitializationKind::IK_Direct)
6042 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006043
6044 // If the entity allows NRVO, mark the construction as elidable
6045 // unconditionally.
6046 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006047 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006048 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006049 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006050 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006051 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006052 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006053 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006054 ConstructorInitRequiresZeroInit,
6055 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006056 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006057 else
Richard Smith410306b2016-12-12 02:53:20 +00006058 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006059 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006060 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006061 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006062 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006063 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006064 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006065 ConstructorInitRequiresZeroInit,
6066 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006067 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006068 }
6069 if (CurInit.isInvalid())
6070 return ExprError();
6071
6072 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006073 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006074 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6075 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006076
6077 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006078 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006079
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006080 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006081}
6082
Richard Smitheb3cad52012-06-04 22:27:30 +00006083/// Determine whether the specified InitializedEntity definitely has a lifetime
6084/// longer than the current full-expression. Conservatively returns false if
6085/// it's unclear.
6086static bool
6087InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6088 const InitializedEntity *Top = &Entity;
6089 while (Top->getParent())
6090 Top = Top->getParent();
6091
6092 switch (Top->getKind()) {
6093 case InitializedEntity::EK_Variable:
6094 case InitializedEntity::EK_Result:
6095 case InitializedEntity::EK_Exception:
6096 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00006097 case InitializedEntity::EK_Binding:
Richard Smitheb3cad52012-06-04 22:27:30 +00006098 case InitializedEntity::EK_New:
6099 case InitializedEntity::EK_Base:
6100 case InitializedEntity::EK_Delegating:
6101 return true;
6102
6103 case InitializedEntity::EK_ArrayElement:
6104 case InitializedEntity::EK_VectorElement:
6105 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006106 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smitheb3cad52012-06-04 22:27:30 +00006107 case InitializedEntity::EK_ComplexElement:
6108 // Could not determine what the full initialization is. Assume it might not
6109 // outlive the full-expression.
6110 return false;
6111
6112 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006113 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00006114 case InitializedEntity::EK_Temporary:
6115 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006116 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006117 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00006118 // The entity being initialized might not outlive the full-expression.
6119 return false;
6120 }
6121
6122 llvm_unreachable("unknown entity kind");
6123}
6124
Richard Smithe6c01442013-06-05 00:46:14 +00006125/// Determine the declaration which an initialized entity ultimately refers to,
6126/// for the purpose of lifetime-extending a temporary bound to a reference in
6127/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00006128static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
6129 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00006130 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006131 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006132 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006133 case InitializedEntity::EK_Variable:
6134 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00006135 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006136
6137 case InitializedEntity::EK_Member:
6138 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006139 if (Entity->getParent())
6140 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6141 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006142
6143 // except:
6144 // -- A temporary bound to a reference member in a constructor's
6145 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00006146 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006147
Richard Smith7873de02016-08-11 22:25:46 +00006148 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006149 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6150 // type.
6151 return Entity;
Richard Smith7873de02016-08-11 22:25:46 +00006152
Richard Smithe6c01442013-06-05 00:46:14 +00006153 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006154 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006155 // -- A temporary bound to a reference parameter in a function call
6156 // persists until the completion of the full-expression containing
6157 // the call.
6158 case InitializedEntity::EK_Result:
6159 // -- The lifetime of a temporary bound to the returned value in a
6160 // function return statement is not extended; the temporary is
6161 // destroyed at the end of the full-expression in the return statement.
6162 case InitializedEntity::EK_New:
6163 // -- A temporary bound to a reference in a new-initializer persists
6164 // until the completion of the full-expression containing the
6165 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006166 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006167
6168 case InitializedEntity::EK_Temporary:
6169 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006170 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006171 // We don't yet know the storage duration of the surrounding temporary.
6172 // Assume it's got full-expression duration for now, it will patch up our
6173 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00006174 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006175
6176 case InitializedEntity::EK_ArrayElement:
6177 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006178 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6179 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00006180
6181 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006182 // For subobjects, we look at the complete object.
6183 if (Entity->getParent())
6184 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6185 Entity);
6186 // Fall through.
Richard Smithe6c01442013-06-05 00:46:14 +00006187 case InitializedEntity::EK_Delegating:
6188 // We can reach this case for aggregate initialization in a constructor:
6189 // struct A { int &&r; };
6190 // struct B : A { B() : A{0} {} };
6191 // In this case, use the innermost field decl as the context.
6192 return FallbackDecl;
6193
6194 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006195 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006196 case InitializedEntity::EK_LambdaCapture:
6197 case InitializedEntity::EK_Exception:
6198 case InitializedEntity::EK_VectorElement:
6199 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00006200 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006201 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006202 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006203}
6204
David Majnemerdaff3702014-05-01 17:50:17 +00006205static void performLifetimeExtension(Expr *Init,
6206 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006207
6208/// Update a glvalue expression that is used as the initializer of a reference
6209/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006210/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00006211static bool
6212performReferenceExtension(Expr *Init,
6213 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006214 // Walk past any constructs which we can lifetime-extend across.
6215 Expr *Old;
6216 do {
6217 Old = Init;
6218
Richard Smithdbc82492015-01-10 01:28:13 +00006219 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6220 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
6221 // This is just redundant braces around an initializer. Step over it.
6222 Init = ILE->getInit(0);
6223 }
6224 }
6225
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006226 // Step over any subobject adjustments; we may have a materialized
6227 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006228 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006229
6230 // Per current approach for DR1376, look through casts to reference type
6231 // when performing lifetime extension.
6232 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6233 if (CE->getSubExpr()->isGLValue())
6234 Init = CE->getSubExpr();
6235
Richard Smithb3189a12016-12-05 07:49:14 +00006236 // Per the current approach for DR1299, look through array element access
6237 // when performing lifetime extension.
6238 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6239 Init = ASE->getBase();
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006240 } while (Init != Old);
6241
Richard Smithe6c01442013-06-05 00:46:14 +00006242 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6243 // Update the storage duration of the materialized temporary.
6244 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00006245 ME->setExtendingDecl(ExtendingEntity->getDecl(),
6246 ExtendingEntity->allocateManglingNumber());
6247 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006248 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00006249 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006250
6251 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00006252}
6253
6254/// Update a prvalue expression that is going to be materialized as a
6255/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00006256static void performLifetimeExtension(Expr *Init,
6257 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00006258 // Dig out the expression which constructs the extended temporary.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006259 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smithe6c01442013-06-05 00:46:14 +00006260
Richard Smith736a9472013-06-12 20:42:33 +00006261 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6262 Init = BTE->getSubExpr();
6263
Richard Smithcc1b96d2013-06-12 22:31:48 +00006264 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006265 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00006266 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006267 return;
6268 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006269
Richard Smithe6c01442013-06-05 00:46:14 +00006270 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006271 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006272 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00006273 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006274 return;
6275 }
6276
Richard Smithcc1b96d2013-06-12 22:31:48 +00006277 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006278 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6279
6280 // If we lifetime-extend a braced initializer which is initializing an
6281 // aggregate, and that aggregate contains reference members which are
6282 // bound to temporaries, those temporaries are also lifetime-extended.
6283 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6284 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006285 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006286 else {
6287 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006288 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006289 if (Index >= ILE->getNumInits())
6290 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006291 if (I->isUnnamedBitfield())
6292 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006293 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006294 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006295 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00006296 else if (isa<InitListExpr>(SubInit) ||
6297 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00006298 // This may be either aggregate-initialization of a member or
6299 // initialization of a std::initializer_list object. Either way,
6300 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006301 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006302 ++Index;
6303 }
6304 }
6305 }
6306 }
6307}
6308
Richard Smithcc1b96d2013-06-12 22:31:48 +00006309static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6310 const Expr *Init, bool IsInitializerList,
6311 const ValueDecl *ExtendingDecl) {
6312 // Warn if a field lifetime-extends a temporary.
6313 if (isa<FieldDecl>(ExtendingDecl)) {
6314 if (IsInitializerList) {
6315 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6316 << /*at end of constructor*/true;
6317 return;
6318 }
6319
6320 bool IsSubobjectMember = false;
6321 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6322 Ent = Ent->getParent()) {
6323 if (Ent->getKind() != InitializedEntity::EK_Base) {
6324 IsSubobjectMember = true;
6325 break;
6326 }
6327 }
6328 S.Diag(Init->getExprLoc(),
6329 diag::warn_bind_ref_member_to_temporary)
6330 << ExtendingDecl << Init->getSourceRange()
6331 << IsSubobjectMember << IsInitializerList;
6332 if (IsSubobjectMember)
6333 S.Diag(ExtendingDecl->getLocation(),
6334 diag::note_ref_subobject_of_member_declared_here);
6335 else
6336 S.Diag(ExtendingDecl->getLocation(),
6337 diag::note_ref_or_ptr_member_declared_here)
6338 << /*is pointer*/false;
6339 }
6340}
6341
Richard Smithaaa0ec42013-09-21 21:19:19 +00006342static void DiagnoseNarrowingInInitList(Sema &S,
6343 const ImplicitConversionSequence &ICS,
6344 QualType PreNarrowingType,
6345 QualType EntityType,
6346 const Expr *PostInit);
6347
Richard Trieuac3eca52015-04-29 01:52:17 +00006348/// Provide warnings when std::move is used on construction.
6349static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6350 bool IsReturnStmt) {
6351 if (!InitExpr)
6352 return;
6353
Richard Smith51ec0cf2017-02-21 01:17:38 +00006354 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00006355 return;
6356
Richard Trieuac3eca52015-04-29 01:52:17 +00006357 QualType DestType = InitExpr->getType();
6358 if (!DestType->isRecordType())
6359 return;
6360
6361 unsigned DiagID = 0;
6362 if (IsReturnStmt) {
6363 const CXXConstructExpr *CCE =
6364 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6365 if (!CCE || CCE->getNumArgs() != 1)
6366 return;
6367
6368 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6369 return;
6370
6371 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00006372 }
6373
6374 // Find the std::move call and get the argument.
6375 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6376 if (!CE || CE->getNumArgs() != 1)
6377 return;
6378
6379 const FunctionDecl *MoveFunction = CE->getDirectCallee();
6380 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6381 !MoveFunction->getIdentifier() ||
6382 !MoveFunction->getIdentifier()->isStr("move"))
6383 return;
6384
6385 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6386
6387 if (IsReturnStmt) {
6388 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6389 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6390 return;
6391
6392 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6393 if (!VD || !VD->hasLocalStorage())
6394 return;
6395
Richard Trieu8d4006a2015-07-28 19:06:16 +00006396 QualType SourceType = VD->getType();
6397 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00006398 return;
6399
Richard Trieu8d4006a2015-07-28 19:06:16 +00006400 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00006401 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00006402 }
6403
Davide Italiano7842c3f2015-07-18 01:15:19 +00006404 // If we're returning a function parameter, copy elision
6405 // is not possible.
6406 if (isa<ParmVarDecl>(VD))
6407 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00006408 else
6409 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00006410 } else {
6411 DiagID = diag::warn_pessimizing_move_on_initialization;
6412 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6413 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6414 return;
6415 }
6416
6417 S.Diag(CE->getLocStart(), DiagID);
6418
6419 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6420 // is within a macro.
6421 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6422 if (CallBegin.isMacroID())
6423 return;
6424 SourceLocation RParen = CE->getRParenLoc();
6425 if (RParen.isMacroID())
6426 return;
6427 SourceLocation LParen;
6428 SourceLocation ArgLoc = Arg->getLocStart();
6429
6430 // Special testing for the argument location. Since the fix-it needs the
6431 // location right before the argument, the argument location can be in a
6432 // macro only if it is at the beginning of the macro.
6433 while (ArgLoc.isMacroID() &&
6434 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
6435 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6436 }
6437
6438 if (LParen.isMacroID())
6439 return;
6440
6441 LParen = ArgLoc.getLocWithOffset(-1);
6442
6443 S.Diag(CE->getLocStart(), diag::note_remove_move)
6444 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6445 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6446}
6447
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006448static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6449 // Check to see if we are dereferencing a null pointer. If so, this is
6450 // undefined behavior, so warn about it. This only handles the pattern
6451 // "*null", which is a very syntactic check.
6452 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6453 if (UO->getOpcode() == UO_Deref &&
6454 UO->getSubExpr()->IgnoreParenCasts()->
6455 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6456 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6457 S.PDiag(diag::warn_binding_null_to_reference)
6458 << UO->getSubExpr()->getSourceRange());
6459 }
6460}
6461
Tim Shen4a05bb82016-06-21 20:29:17 +00006462MaterializeTemporaryExpr *
6463Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6464 bool BoundToLvalueReference) {
6465 auto MTE = new (Context)
6466 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6467
6468 // Order an ExprWithCleanups for lifetime marks.
6469 //
6470 // TODO: It'll be good to have a single place to check the access of the
6471 // destructor and generate ExprWithCleanups for various uses. Currently these
6472 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6473 // but there may be a chance to merge them.
6474 Cleanup.setExprNeedsCleanups(false);
6475 return MTE;
6476}
6477
Richard Smith4baaa5a2016-12-03 01:14:32 +00006478ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6479 // In C++98, we don't want to implicitly create an xvalue.
6480 // FIXME: This means that AST consumers need to deal with "prvalues" that
6481 // denote materialized temporaries. Maybe we should add another ValueKind
6482 // for "xvalue pretending to be a prvalue" for C++98 support.
6483 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6484 return E;
6485
6486 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00006487 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6488 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006489 QualType T = E->getType();
6490 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6491 return ExprError();
6492
6493 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6494}
6495
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006496ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006497InitializationSequence::Perform(Sema &S,
6498 const InitializedEntity &Entity,
6499 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00006500 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006501 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006502 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006503 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00006504 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006505 }
Nico Weber337d5aa2015-04-17 08:32:38 +00006506 if (!ZeroInitializationFixit.empty()) {
6507 unsigned DiagID = diag::err_default_init_const;
6508 if (Decl *D = Entity.getDecl())
6509 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6510 DiagID = diag::ext_default_init_const;
6511
6512 // The initialization would have succeeded with this fixit. Since the fixit
6513 // is on the error, we need to build a valid AST in this case, so this isn't
6514 // handled in the Failed() branch above.
6515 QualType DestType = Entity.getType();
6516 S.Diag(Kind.getLocation(), DiagID)
6517 << DestType << (bool)DestType->getAs<RecordType>()
6518 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6519 ZeroInitializationFixit);
6520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521
Sebastian Redld201edf2011-06-05 13:59:11 +00006522 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006523 // If the declaration is a non-dependent, incomplete array type
6524 // that has an initializer, then its type will be completed once
6525 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00006526 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00006527 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006528 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006529 if (const IncompleteArrayType *ArrayT
6530 = S.Context.getAsIncompleteArrayType(DeclType)) {
6531 // FIXME: We don't currently have the ability to accurately
6532 // compute the length of an initializer list without
6533 // performing full type-checking of the initializer list
6534 // (since we have to determine where braces are implicitly
6535 // introduced and such). So, we fall back to making the array
6536 // type a dependently-sized array type with no specified
6537 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006538 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006539 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00006540
Douglas Gregor51e77d52009-12-10 17:56:55 +00006541 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00006542 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006543 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6544 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00006545 if (IncompleteArrayTypeLoc ArrayLoc =
6546 TL.getAs<IncompleteArrayTypeLoc>())
6547 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00006548 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00006549 }
6550
6551 *ResultType
6552 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006553 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006554 ArrayT->getSizeModifier(),
6555 ArrayT->getIndexTypeCVRQualifiers(),
6556 Brackets);
6557 }
6558
6559 }
6560 }
Sebastian Redla9351792012-02-11 23:51:47 +00006561 if (Kind.getKind() == InitializationKind::IK_Direct &&
6562 !Kind.isExplicitCast()) {
6563 // Rebuild the ParenListExpr.
6564 SourceRange ParenRange = Kind.getParenRange();
6565 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006566 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00006567 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00006568 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00006569 Kind.isExplicitCast() ||
6570 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006571 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006572 }
6573
Sebastian Redld201edf2011-06-05 13:59:11 +00006574 // No steps means no initialization.
6575 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006576 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006578 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006579 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006580 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00006581 // Produce a C++98 compatibility warning if we are initializing a reference
6582 // from an initializer list. For parameters, we produce a better warning
6583 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006584 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00006585 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6586 << Init->getSourceRange();
6587 }
6588
Egor Churaev3bccec52017-04-05 12:47:10 +00006589 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6590 QualType ETy = Entity.getType();
6591 Qualifiers TyQualifiers = ETy.getQualifiers();
6592 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6593 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6594
6595 if (S.getLangOpts().OpenCLVersion >= 200 &&
6596 ETy->isAtomicType() && !HasGlobalAS &&
6597 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6598 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6599 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6600 return ExprError();
6601 }
6602
Richard Smitheb3cad52012-06-04 22:27:30 +00006603 // Diagnose cases where we initialize a pointer to an array temporary, and the
6604 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006605 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00006606 Entity.getType()->isPointerType() &&
6607 InitializedEntityOutlivesFullExpression(Entity)) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00006608 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6609 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6610 Init = MTE->GetTemporaryExpr();
Richard Smitheb3cad52012-06-04 22:27:30 +00006611 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6612 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6613 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6614 << Init->getSourceRange();
6615 }
6616
Douglas Gregor1b303932009-12-22 15:35:07 +00006617 QualType DestType = Entity.getType().getNonReferenceType();
6618 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00006619 // the same as Entity.getDecl()->getType() in cases involving type merging,
6620 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00006621 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00006622 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00006623 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006624
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006625 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00006626 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006627
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006628 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00006629 // grab the only argument out the Args and place it into the "current"
6630 // initializer.
6631 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006632 case SK_ResolveAddressOfOverloadedFunction:
6633 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006634 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006635 case SK_CastDerivedToBaseLValue:
6636 case SK_BindReference:
6637 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00006638 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006639 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00006640 case SK_UserConversion:
6641 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006642 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006643 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00006644 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00006645 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006646 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00006647 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00006648 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00006649 case SK_UnwrapInitList:
6650 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00006651 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00006652 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00006653 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00006654 case SK_ArrayLoopIndex:
6655 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00006656 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00006657 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00006658 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00006659 case SK_PassByIndirectCopyRestore:
6660 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00006661 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006662 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00006663 case SK_OCLSamplerInit:
Egor Churaev89831422016-12-23 14:55:49 +00006664 case SK_OCLZeroEvent:
6665 case SK_OCLZeroQueue: {
Douglas Gregore1314a62009-12-18 05:02:21 +00006666 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006667 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00006668 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006669 break;
John McCall34376a62010-12-04 03:47:34 +00006670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006671
Douglas Gregore1314a62009-12-18 05:02:21 +00006672 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00006673 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006674 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00006675 case SK_ZeroInitialization:
6676 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006678
Richard Smithd6a15082017-01-07 00:48:55 +00006679 // Promote from an unevaluated context to an unevaluated list context in
6680 // C++11 list-initialization; we need to instantiate entities usable in
6681 // constant expressions here in order to perform narrowing checks =(
6682 EnterExpressionEvaluationContext Evaluated(
6683 S, EnterExpressionEvaluationContext::InitList,
6684 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6685
Richard Smith81f5ade2016-12-15 02:28:18 +00006686 // C++ [class.abstract]p2:
6687 // no objects of an abstract class can be created except as subobjects
6688 // of a class derived from it
6689 auto checkAbstractType = [&](QualType T) -> bool {
6690 if (Entity.getKind() == InitializedEntity::EK_Base ||
6691 Entity.getKind() == InitializedEntity::EK_Delegating)
6692 return false;
6693 return S.RequireNonAbstractType(Kind.getLocation(), T,
6694 diag::err_allocation_of_abstract_type);
6695 };
6696
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006697 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006698 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006699 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006700 for (step_iterator Step = step_begin(), StepEnd = step_end();
6701 Step != StepEnd; ++Step) {
6702 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006703 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006704
John Wiegley01296292011-04-08 18:41:53 +00006705 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006706
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006707 switch (Step->Kind) {
6708 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006709 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006710 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00006711 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00006712 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6713 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006714 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00006715 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00006716 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006717 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006718
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006719 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006720 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006721 case SK_CastDerivedToBaseLValue: {
6722 // We have a derived-to-base cast that produces either an rvalue or an
6723 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006724
John McCallcf142162010-08-07 06:22:56 +00006725 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00006726
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006727 // Casts to inaccessible base classes are allowed with C-style casts.
6728 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6729 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00006730 CurInit.get()->getLocStart(),
6731 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00006732 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00006733 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006734
John McCall2536c6d2010-08-25 10:28:54 +00006735 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006736 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006737 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006738 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006739 VK_XValue :
6740 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006741 CurInit =
6742 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6743 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006744 break;
6745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006746
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006747 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006748 // Reference binding does not have any corresponding ASTs.
6749
6750 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006751 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006752 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006753
George Burgess IVcfd48d92017-04-13 23:47:08 +00006754 // We don't check for e.g. function pointers here, since address
6755 // availability checks should only occur when the function first decays
6756 // into a pointer or reference.
6757 if (CurInit.get()->getType()->isFunctionProtoType()) {
6758 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
6759 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6760 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
6761 DRE->getLocStart()))
6762 return ExprError();
6763 }
6764 }
6765 }
6766
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006767 // Even though we didn't materialize a temporary, the binding may still
6768 // extend the lifetime of a temporary. This happens if we bind a reference
6769 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00006770 if (const InitializedEntity *ExtendingEntity =
6771 getEntityForTemporaryLifetimeExtension(&Entity))
6772 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6773 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6774 /*IsInitializerList=*/false,
6775 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006776
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006777 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006778 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006779
Richard Smithe6c01442013-06-05 00:46:14 +00006780 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00006781 // Make sure the "temporary" is actually an rvalue.
6782 assert(CurInit.get()->isRValue() && "not a temporary");
6783
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006784 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006785 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006786 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006787
Douglas Gregorfe314812011-06-21 17:03:29 +00006788 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00006789 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00006790 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
David Majnemerdaff3702014-05-01 17:50:17 +00006791
6792 // Maybe lifetime-extend the temporary's subobjects to match the
6793 // entity's lifetime.
6794 if (const InitializedEntity *ExtendingEntity =
6795 getEntityForTemporaryLifetimeExtension(&Entity))
6796 if (performReferenceExtension(MTE, ExtendingEntity))
Richard Smithb8c0f552016-12-09 18:49:13 +00006797 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6798 /*IsInitializerList=*/false,
David Majnemerdaff3702014-05-01 17:50:17 +00006799 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006800
Brian Kelley762f9282017-03-29 18:16:38 +00006801 // If we're extending this temporary to automatic storage duration -- we
6802 // need to register its cleanup during the full-expression's cleanups.
6803 if (MTE->getStorageDuration() == SD_Automatic &&
6804 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00006805 S.Cleanup.setExprNeedsCleanups(true);
Richard Smith736a9472013-06-12 20:42:33 +00006806
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006807 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006808 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810
Richard Smithb8c0f552016-12-09 18:49:13 +00006811 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00006812 if (checkAbstractType(Step->Type))
6813 return ExprError();
6814
Richard Smithb8c0f552016-12-09 18:49:13 +00006815 // If the overall initialization is initializing a temporary, we already
6816 // bound our argument if it was necessary to do so. If not (if we're
6817 // ultimately initializing a non-temporary), our argument needs to be
6818 // bound since it's initializing a function parameter.
6819 // FIXME: This is a mess. Rationalize temporary destruction.
6820 if (!shouldBindAsTemporary(Entity))
6821 CurInit = S.MaybeBindToTemporary(CurInit.get());
6822 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6823 /*IsExtraneousCopy=*/false);
6824 break;
6825
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006826 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006827 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006828 /*IsExtraneousCopy=*/true);
6829 break;
6830
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006831 case SK_UserConversion: {
6832 // We have a user-defined conversion that invokes either a constructor
6833 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006834 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00006835 FunctionDecl *Fn = Step->Function.Function;
6836 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006837 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006838 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006839 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006840 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006841 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006842 SourceLocation Loc = CurInit.get()->getLocStart();
John McCall760af172010-02-01 03:16:54 +00006843
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006844 // Determine the arguments required to actually perform the constructor
6845 // call.
John Wiegley01296292011-04-08 18:41:53 +00006846 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006847 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006848 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006849 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006850 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006851
Richard Smithb24f0672012-02-11 19:22:50 +00006852 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00006853 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6854 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006855 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006856 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006857 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006858 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006859 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006860 CXXConstructExpr::CK_Complete,
6861 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006862 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006863 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006864
Richard Smith5179eb72016-06-28 19:03:57 +00006865 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6866 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006867 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6868 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006869
John McCalle3027922010-08-25 11:45:40 +00006870 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00006871 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006872 } else {
6873 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006874 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006875 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006876 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006877 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6878 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006879
6880 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006881 // derived-to-base conversion? I believe the answer is "no", because
6882 // we don't want to turn off access control here for c-style casts.
Richard Smithb8c0f552016-12-09 18:49:13 +00006883 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
6884 /*Qualifier=*/nullptr,
6885 FoundFn, Conversion);
6886 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006887 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006888
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006889 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006890 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6891 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00006892 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006893 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894
John McCalle3027922010-08-25 11:45:40 +00006895 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00006896 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006898
Richard Smith81f5ade2016-12-15 02:28:18 +00006899 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
6900 return ExprError();
6901
Richard Smithb8c0f552016-12-09 18:49:13 +00006902 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6903 CastKind, CurInit.get(), nullptr,
6904 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006905
Richard Smithb8c0f552016-12-09 18:49:13 +00006906 if (shouldBindAsTemporary(Entity))
6907 // The overall entity is temporary, so this expression should be
6908 // destroyed at the end of its full-expression.
6909 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6910 else if (CreatedObject && shouldDestroyEntity(Entity)) {
6911 // The object outlasts the full-expression, but we need to prepare for
6912 // a destructor being run on it.
6913 // FIXME: It makes no sense to do this here. This should happen
6914 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00006915 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006916 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006917 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006918 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006919 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006920 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006921 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006922 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6923 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006924 }
6925 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006926 break;
6927 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006928
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006929 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006930 case SK_QualificationConversionXValue:
6931 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006932 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006933 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006934 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006935 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006936 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006937 VK_XValue :
6938 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006939 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006940 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006941 }
6942
Richard Smith77be48a2014-07-31 06:31:19 +00006943 case SK_AtomicConversion: {
6944 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6945 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6946 CK_NonAtomicToAtomic, VK_RValue);
6947 break;
6948 }
6949
Jordan Roseb1312a52013-04-11 00:58:58 +00006950 case SK_LValueToRValue: {
6951 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006952 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6953 CK_LValueToRValue, CurInit.get(),
6954 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006955 break;
6956 }
6957
Richard Smithaaa0ec42013-09-21 21:19:19 +00006958 case SK_ConversionSequence:
6959 case SK_ConversionSequenceNoNarrowing: {
6960 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006961 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6962 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006963 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006964 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006965 ExprResult CurInitExprRes =
6966 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006967 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006968 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006969 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00006970
6971 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
6972
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006973 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006974
6975 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00006976 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00006977 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6978 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00006979
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006980 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006982
Douglas Gregor51e77d52009-12-10 17:56:55 +00006983 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00006984 if (checkAbstractType(Step->Type))
6985 return ExprError();
6986
John Wiegley01296292011-04-08 18:41:53 +00006987 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006988 // If we're not initializing the top-level entity, we need to create an
6989 // InitializeTemporary entity for our target type.
6990 QualType Ty = Step->Type;
6991 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006992 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006993 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6994 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00006995 InitList, Ty, /*VerifyOnly=*/false,
6996 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006997 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006998 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006999
Richard Smithcc1b96d2013-06-12 22:31:48 +00007000 // Hack: We must update *ResultType if available in order to set the
7001 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7002 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7003 if (ResultType &&
7004 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007005 if ((*ResultType)->isRValueReferenceType())
7006 Ty = S.Context.getRValueReferenceType(Ty);
7007 else if ((*ResultType)->isLValueReferenceType())
7008 Ty = S.Context.getLValueReferenceType(Ty,
7009 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7010 *ResultType = Ty;
7011 }
7012
7013 InitListExpr *StructuredInitList =
7014 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007015 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007016 CurInit = shouldBindAsTemporary(InitEntity)
7017 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007018 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007019 break;
7020 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007021
Richard Smith53324112014-07-16 21:33:43 +00007022 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007023 if (checkAbstractType(Step->Type))
7024 return ExprError();
7025
Sebastian Redl5a41f682012-02-12 16:37:24 +00007026 // When an initializer list is passed for a parameter of type "reference
7027 // to object", we don't get an EK_Temporary entity, but instead an
7028 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007029 // FIXME: This is a hack. What we really should do is create a user
7030 // conversion step for this case, but this makes it considerably more
7031 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007032 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7033 Entity.getType().getNonReferenceType());
7034 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007035 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007036 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007037 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7038 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007039 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007040 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7041 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007042 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007043 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007044 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007045 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007046 InitList->getLBraceLoc(),
7047 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007048 break;
7049 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007050
Sebastian Redl29526f02011-11-27 16:50:07 +00007051 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007052 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007053 break;
7054
7055 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007056 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007057 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7058 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007059 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007060 ILE->setSyntacticForm(Syntactic);
7061 ILE->setType(E->getType());
7062 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007063 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007064 break;
7065 }
7066
Richard Smith53324112014-07-16 21:33:43 +00007067 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007068 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007069 if (checkAbstractType(Step->Type))
7070 return ExprError();
7071
Sebastian Redl99f66162012-02-19 12:27:56 +00007072 // When an initializer list is passed for a parameter of type "reference
7073 // to object", we don't get an EK_Temporary entity, but instead an
7074 // EK_Parameter entity with reference type.
7075 // FIXME: This is a hack. What we really should do is create a user
7076 // conversion step for this case, but this makes it considerably more
7077 // complicated. For now, this will do.
7078 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7079 Entity.getType().getNonReferenceType());
7080 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00007081 bool IsStdInitListInit =
7082 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00007083 Expr *Source = CurInit.get();
Richard Smith53324112014-07-16 21:33:43 +00007084 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00007085 S, UseTemporary ? TempEntity : Entity, Kind,
7086 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00007087 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00007088 /*IsListInitialization*/ IsStdInitListInit,
7089 /*IsStdInitListInitialization*/ IsStdInitListInit,
7090 /*LBraceLoc*/ SourceLocation(),
7091 /*RBraceLoc*/ SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007092 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00007093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007094
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007095 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007096 step_iterator NextStep = Step;
7097 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007099 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007100 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007101 // The need for zero-initialization is recorded directly into
7102 // the call to the object's constructor within the next step.
7103 ConstructorInitRequiresZeroInit = true;
7104 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007105 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007106 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007107 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7108 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007109 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007110 Kind.getRange().getBegin());
7111
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007112 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007113 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007114 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007115 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007116 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007117 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007118 break;
7119 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007120
7121 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007122 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007123 // Save off the initial CurInit in case we need to emit a diagnostic
7124 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007125 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007126 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007127 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7128 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007129 if (Result.isInvalid())
7130 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007131 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007132
7133 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007134 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007135 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007136 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007137 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007138 == Sema::Compatible)
7139 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007140 if (CurInitExprRes.isInvalid())
7141 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007142 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007143
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007144 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007145 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7146 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007147 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007148 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007149 &Complained)) {
7150 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007151 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007152 } else if (Complained)
7153 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007154 break;
7155 }
Eli Friedman78275202009-12-19 08:11:05 +00007156
7157 case SK_StringInit: {
7158 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007159 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007160 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007161 break;
7162 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007163
7164 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007165 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007166 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007167 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007168 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007169
Richard Smith410306b2016-12-12 02:53:20 +00007170 case SK_ArrayLoopIndex: {
7171 Expr *Cur = CurInit.get();
7172 Expr *BaseExpr = new (S.Context)
7173 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7174 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7175 Expr *IndexExpr =
7176 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7177 CurInit = S.CreateBuiltinArraySubscriptExpr(
7178 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7179 ArrayLoopCommonExprs.push_back(BaseExpr);
7180 break;
7181 }
7182
7183 case SK_ArrayLoopInit: {
7184 assert(!ArrayLoopCommonExprs.empty() &&
7185 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7186 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7187 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7188 CurInit.get());
7189 break;
7190 }
7191
Richard Smith378b8c82016-12-14 03:22:16 +00007192 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007193 // Okay: we checked everything before creating this step. Note that
7194 // this is a GNU extension.
7195 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007196 << Step->Type << CurInit.get()->getType()
7197 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007198 LLVM_FALLTHROUGH;
7199 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007200 // If the destination type is an incomplete array type, update the
7201 // type accordingly.
7202 if (ResultType) {
7203 if (const IncompleteArrayType *IncompleteDest
7204 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7205 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007206 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007207 *ResultType = S.Context.getConstantArrayType(
7208 IncompleteDest->getElementType(),
7209 ConstantSource->getSize(),
7210 ArrayType::Normal, 0);
7211 }
7212 }
7213 }
John McCall31168b02011-06-15 23:02:42 +00007214 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007215
Richard Smithebeed412012-02-15 22:38:09 +00007216 case SK_ParenthesizedArrayInit:
7217 // Okay: we checked everything before creating this step. Note that
7218 // this is a GNU extension.
7219 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7220 << CurInit.get()->getSourceRange();
7221 break;
7222
John McCall31168b02011-06-15 23:02:42 +00007223 case SK_PassByIndirectCopyRestore:
7224 case SK_PassByIndirectRestore:
7225 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007226 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7227 CurInit.get(), Step->Type,
7228 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007229 break;
7230
7231 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007232 CurInit =
7233 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7234 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007235 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007236
7237 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007238 S.Diag(CurInit.get()->getExprLoc(),
7239 diag::warn_cxx98_compat_initializer_list_init)
7240 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007241
Richard Smithcc1b96d2013-06-12 22:31:48 +00007242 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007243 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7244 CurInit.get()->getType(), CurInit.get(),
7245 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007246
7247 // Maybe lifetime-extend the array temporary's subobjects to match the
7248 // entity's lifetime.
7249 if (const InitializedEntity *ExtendingEntity =
7250 getEntityForTemporaryLifetimeExtension(&Entity))
7251 if (performReferenceExtension(MTE, ExtendingEntity))
7252 warnOnLifetimeExtension(S, Entity, CurInit.get(),
7253 /*IsInitializerList=*/true,
7254 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007255
7256 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007257 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007258
7259 // Bind the result, in case the library has given initializer_list a
7260 // non-trivial destructor.
7261 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007262 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007263 break;
7264 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007265
Guy Benyei61054192013-02-07 10:55:47 +00007266 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007267 // Sampler initialzation have 5 cases:
7268 // 1. function argument passing
7269 // 1a. argument is a file-scope variable
7270 // 1b. argument is a function-scope variable
7271 // 1c. argument is one of caller function's parameters
7272 // 2. variable initialization
7273 // 2a. initializing a file-scope variable
7274 // 2b. initializing a function-scope variable
7275 //
7276 // For file-scope variables, since they cannot be initialized by function
7277 // call of __translate_sampler_initializer in LLVM IR, their references
7278 // need to be replaced by a cast from their literal initializers to
7279 // sampler type. Since sampler variables can only be used in function
7280 // calls as arguments, we only need to replace them when handling the
7281 // argument passing.
7282 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007283 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007284 Expr *Init = CurInit.get();
7285 QualType SourceType = Init->getType();
7286 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007287 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00007288 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00007289 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7290 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007291 break;
7292 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7293 auto Var = cast<VarDecl>(DRE->getDecl());
7294 // Case 1b and 1c
7295 // No cast from integer to sampler is needed.
7296 if (!Var->hasGlobalStorage()) {
7297 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7298 CK_LValueToRValue, Init,
7299 /*BasePath=*/nullptr, VK_RValue);
7300 break;
7301 }
7302 // Case 1a
7303 // For function call with a file-scope sampler variable as argument,
7304 // get the integer literal.
7305 // Do not diagnose if the file-scope variable does not have initializer
7306 // since this has already been diagnosed when parsing the variable
7307 // declaration.
7308 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7309 break;
7310 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7311 Var->getInit()))->getSubExpr();
7312 SourceType = Init->getType();
7313 }
7314 } else {
7315 // Case 2
7316 // Check initializer is 32 bit integer constant.
7317 // If the initializer is taken from global variable, do not diagnose since
7318 // this has already been done when parsing the variable declaration.
7319 if (!Init->isConstantInitializer(S.Context, false))
7320 break;
7321
7322 if (!SourceType->isIntegerType() ||
7323 32 != S.Context.getIntWidth(SourceType)) {
7324 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7325 << SourceType;
7326 break;
7327 }
7328
7329 llvm::APSInt Result;
7330 Init->EvaluateAsInt(Result, S.Context);
7331 const uint64_t SamplerValue = Result.getLimitedValue();
7332 // 32-bit value of sampler's initializer is interpreted as
7333 // bit-field with the following structure:
7334 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7335 // |31 6|5 4|3 1| 0|
7336 // This structure corresponds to enum values of sampler properties
7337 // defined in SPIR spec v1.2 and also opencl-c.h
7338 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7339 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7340 if (FilterMode != 1 && FilterMode != 2)
7341 S.Diag(Kind.getLocation(),
7342 diag::warn_sampler_initializer_invalid_bits)
7343 << "Filter Mode";
7344 if (AddressingMode > 4)
7345 S.Diag(Kind.getLocation(),
7346 diag::warn_sampler_initializer_invalid_bits)
7347 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00007348 }
7349
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007350 // Cases 1a, 2a and 2b
7351 // Insert cast from integer to sampler.
7352 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7353 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00007354 break;
7355 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007356 case SK_OCLZeroEvent: {
7357 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007358 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007359
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007360 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007361 CK_ZeroToOCLEvent,
7362 CurInit.get()->getValueKind());
7363 break;
7364 }
Egor Churaev89831422016-12-23 14:55:49 +00007365 case SK_OCLZeroQueue: {
7366 assert(Step->Type->isQueueT() &&
7367 "Event initialization on non queue type.");
7368
7369 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7370 CK_ZeroToOCLQueue,
7371 CurInit.get()->getValueKind());
7372 break;
7373 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007374 }
7375 }
John McCall1f425642010-11-11 03:21:53 +00007376
7377 // Diagnose non-fatal problems with the completed initialization.
7378 if (Entity.getKind() == InitializedEntity::EK_Member &&
7379 cast<FieldDecl>(Entity.getDecl())->isBitField())
7380 S.CheckBitFieldInitialization(Kind.getLocation(),
7381 cast<FieldDecl>(Entity.getDecl()),
7382 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007383
Richard Trieuac3eca52015-04-29 01:52:17 +00007384 // Check for std::move on construction.
7385 if (const Expr *E = CurInit.get()) {
7386 CheckMoveOnConstruction(S, E,
7387 Entity.getKind() == InitializedEntity::EK_Result);
7388 }
7389
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007390 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007391}
7392
Richard Smith593f9932012-12-08 02:01:17 +00007393/// Somewhere within T there is an uninitialized reference subobject.
7394/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00007395static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7396 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00007397 if (T->isReferenceType()) {
7398 S.Diag(Loc, diag::err_reference_without_init)
7399 << T.getNonReferenceType();
7400 return true;
7401 }
7402
7403 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7404 if (!RD || !RD->hasUninitializedReferenceMember())
7405 return false;
7406
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007407 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00007408 if (FI->isUnnamedBitfield())
7409 continue;
7410
7411 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7412 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7413 return true;
7414 }
7415 }
7416
Aaron Ballman574705e2014-03-13 15:41:46 +00007417 for (const auto &BI : RD->bases()) {
7418 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00007419 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7420 return true;
7421 }
7422 }
7423
7424 return false;
7425}
7426
7427
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007428//===----------------------------------------------------------------------===//
7429// Diagnose initialization failures
7430//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00007431
7432/// Emit notes associated with an initialization that failed due to a
7433/// "simple" conversion failure.
7434static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7435 Expr *op) {
7436 QualType destType = entity.getType();
7437 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7438 op->getType()->isObjCObjectPointerType()) {
7439
7440 // Emit a possible note about the conversion failing because the
7441 // operand is a message send with a related result type.
7442 S.EmitRelatedResultTypeNote(op);
7443
7444 // Emit a possible note about a return failing because we're
7445 // expecting a related result type.
7446 if (entity.getKind() == InitializedEntity::EK_Result)
7447 S.EmitRelatedResultTypeNoteForReturn(destType);
7448 }
7449}
7450
Richard Smith0449aaf2013-11-21 23:30:57 +00007451static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7452 InitListExpr *InitList) {
7453 QualType DestType = Entity.getType();
7454
7455 QualType E;
7456 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7457 QualType ArrayType = S.Context.getConstantArrayType(
7458 E.withConst(),
7459 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7460 InitList->getNumInits()),
7461 clang::ArrayType::Normal, 0);
7462 InitializedEntity HiddenArray =
7463 InitializedEntity::InitializeTemporary(ArrayType);
7464 return diagnoseListInit(S, HiddenArray, InitList);
7465 }
7466
Richard Smith8d082d12014-09-04 22:13:39 +00007467 if (DestType->isReferenceType()) {
7468 // A list-initialization failure for a reference means that we tried to
7469 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7470 // inner initialization failed.
7471 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7472 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7473 SourceLocation Loc = InitList->getLocStart();
7474 if (auto *D = Entity.getDecl())
7475 Loc = D->getLocation();
7476 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7477 return;
7478 }
7479
Richard Smith0449aaf2013-11-21 23:30:57 +00007480 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00007481 /*VerifyOnly=*/false,
7482 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00007483 assert(DiagnoseInitList.HadError() &&
7484 "Inconsistent init list check result.");
7485}
7486
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007487bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007488 const InitializedEntity &Entity,
7489 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007490 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007491 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007492 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007493
Douglas Gregor1b303932009-12-22 15:35:07 +00007494 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007495 switch (Failure) {
7496 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007497 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007498 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00007499 // Dig out the reference subobject which is uninitialized and diagnose it.
7500 // If this is value-initialization, this could be nested some way within
7501 // the target type.
7502 assert(Kind.getKind() == InitializationKind::IK_Value ||
7503 DestType->isReferenceType());
7504 bool Diagnosed =
7505 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7506 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7507 (void)Diagnosed;
7508 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007509 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007510 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007511 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00007512 case FK_ParenthesizedListInitForReference:
7513 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7514 << 1 << Entity.getType() << Args[0]->getSourceRange();
7515 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007516
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007517 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007518 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007519 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007520 case FK_ArrayNeedsInitListOrStringLiteral:
7521 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7522 break;
7523 case FK_ArrayNeedsInitListOrWideStringLiteral:
7524 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7525 break;
7526 case FK_NarrowStringIntoWideCharArray:
7527 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7528 break;
7529 case FK_WideStringIntoCharArray:
7530 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7531 break;
7532 case FK_IncompatWideStringIntoWideChar:
7533 S.Diag(Kind.getLocation(),
7534 diag::err_array_init_incompat_wide_string_into_wchar);
7535 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007536 case FK_ArrayTypeMismatch:
7537 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00007538 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00007539 (Failure == FK_ArrayTypeMismatch
7540 ? diag::err_array_init_different_type
7541 : diag::err_array_init_non_constant_array))
7542 << DestType.getNonReferenceType()
7543 << Args[0]->getType()
7544 << Args[0]->getSourceRange();
7545 break;
7546
John McCalla59dc2f2012-01-05 00:13:19 +00007547 case FK_VariableLengthArrayHasInitializer:
7548 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7549 << Args[0]->getSourceRange();
7550 break;
7551
John McCall16df1e52010-03-30 21:47:33 +00007552 case FK_AddressOfOverloadFailed: {
7553 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007554 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007555 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00007556 true,
7557 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007558 break;
John McCall16df1e52010-03-30 21:47:33 +00007559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007560
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007561 case FK_AddressOfUnaddressableFunction: {
7562 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7563 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7564 Args[0]->getLocStart());
7565 break;
7566 }
7567
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007568 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00007569 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007570 switch (FailedOverloadResult) {
7571 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00007572 if (Failure == FK_UserConversionOverloadFailed)
7573 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7574 << Args[0]->getType() << DestType
7575 << Args[0]->getSourceRange();
7576 else
7577 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7578 << DestType << Args[0]->getType()
7579 << Args[0]->getSourceRange();
7580
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007581 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007582 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007583
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007584 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00007585 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007586 DestType.getNonReferenceType(),
7587 diag::err_typecheck_nonviable_condition_incomplete,
7588 Args[0]->getType(), Args[0]->getSourceRange()))
7589 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00007590 << (Entity.getKind() == InitializedEntity::EK_Result)
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007591 << Args[0]->getType() << Args[0]->getSourceRange()
7592 << DestType.getNonReferenceType();
7593
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007594 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007595 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007596
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007597 case OR_Deleted: {
7598 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7599 << Args[0]->getType() << DestType.getNonReferenceType()
7600 << Args[0]->getSourceRange();
7601 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007602 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00007603 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007604 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00007605 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007606 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007607 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007608 }
7609 break;
7610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007611
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007612 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007613 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007614 }
7615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007616
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007617 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00007618 if (isa<InitListExpr>(Args[0])) {
7619 S.Diag(Kind.getLocation(),
7620 diag::err_lvalue_reference_bind_to_initlist)
7621 << DestType.getNonReferenceType().isVolatileQualified()
7622 << DestType.getNonReferenceType()
7623 << Args[0]->getSourceRange();
7624 break;
7625 }
7626 // Intentional fallthrough
7627
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007628 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007629 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007630 Failure == FK_NonConstLValueReferenceBindingToTemporary
7631 ? diag::err_lvalue_reference_bind_to_temporary
7632 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00007633 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007634 << DestType.getNonReferenceType()
7635 << Args[0]->getType()
7636 << Args[0]->getSourceRange();
7637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007638
Richard Smithb8c0f552016-12-09 18:49:13 +00007639 case FK_NonConstLValueReferenceBindingToBitfield: {
7640 // We don't necessarily have an unambiguous source bit-field.
7641 FieldDecl *BitField = Args[0]->getSourceBitField();
7642 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7643 << DestType.isVolatileQualified()
7644 << (BitField ? BitField->getDeclName() : DeclarationName())
7645 << (BitField != nullptr)
7646 << Args[0]->getSourceRange();
7647 if (BitField)
7648 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7649 break;
7650 }
7651
7652 case FK_NonConstLValueReferenceBindingToVectorElement:
7653 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7654 << DestType.isVolatileQualified()
7655 << Args[0]->getSourceRange();
7656 break;
7657
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007658 case FK_RValueReferenceBindingToLValue:
7659 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00007660 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007661 << Args[0]->getSourceRange();
7662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007663
Richard Trieuf956a492015-05-16 01:27:03 +00007664 case FK_ReferenceInitDropsQualifiers: {
7665 QualType SourceType = Args[0]->getType();
7666 QualType NonRefType = DestType.getNonReferenceType();
7667 Qualifiers DroppedQualifiers =
7668 SourceType.getQualifiers() - NonRefType.getQualifiers();
7669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007670 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00007671 << SourceType
7672 << NonRefType
7673 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007674 << Args[0]->getSourceRange();
7675 break;
Richard Trieuf956a492015-05-16 01:27:03 +00007676 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007677
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007678 case FK_ReferenceInitFailed:
7679 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7680 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00007681 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007682 << Args[0]->getType()
7683 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00007684 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007685 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007686
Douglas Gregorb491ed32011-02-19 21:32:49 +00007687 case FK_ConversionFailed: {
7688 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00007689 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00007690 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007691 << DestType
John McCall086a4642010-11-24 05:12:34 +00007692 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00007693 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007694 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00007695 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7696 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00007697 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00007698 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007699 }
John Wiegley01296292011-04-08 18:41:53 +00007700
7701 case FK_ConversionFromPropertyFailed:
7702 // No-op. This error has already been reported.
7703 break;
7704
Douglas Gregor51e77d52009-12-10 17:56:55 +00007705 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00007706 SourceRange R;
7707
David Majnemerbd385442015-04-10 04:52:06 +00007708 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007709 if (InitList && InitList->getNumInits() >= 1) {
David Majnemerbd385442015-04-10 04:52:06 +00007710 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007711 } else {
7712 assert(Args.size() > 1 && "Expected multiple initializers!");
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007713 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007714 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007715
Alp Tokerb6cc5922014-05-03 03:45:55 +00007716 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00007717 if (Kind.isCStyleOrFunctionalCast())
7718 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7719 << R;
7720 else
7721 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7722 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007723 break;
7724 }
7725
Richard Smith49a6b6e2017-03-24 01:14:25 +00007726 case FK_ParenthesizedListInitForScalar:
7727 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7728 << 0 << Entity.getType() << Args[0]->getSourceRange();
7729 break;
7730
Douglas Gregor51e77d52009-12-10 17:56:55 +00007731 case FK_ReferenceBindingToInitList:
7732 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7733 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7734 break;
7735
7736 case FK_InitListBadDestinationType:
7737 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7738 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7739 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007740
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007741 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007742 case FK_ConstructorOverloadFailed: {
7743 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007744 if (Args.size())
7745 ArgsRange = SourceRange(Args.front()->getLocStart(),
7746 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007747
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007748 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00007749 assert(Args.size() == 1 &&
7750 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007751 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007752 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007753 }
7754
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007755 // FIXME: Using "DestType" for the entity we're printing is probably
7756 // bad.
7757 switch (FailedOverloadResult) {
7758 case OR_Ambiguous:
7759 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7760 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007761 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007762 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007763
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007764 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007765 if (Kind.getKind() == InitializationKind::IK_Default &&
7766 (Entity.getKind() == InitializedEntity::EK_Base ||
7767 Entity.getKind() == InitializedEntity::EK_Member) &&
7768 isa<CXXConstructorDecl>(S.CurContext)) {
7769 // This is implicit default initialization of a member or
7770 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00007771 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007772 // initialize this base/member.
7773 CXXConstructorDecl *Constructor
7774 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00007775 const CXXRecordDecl *InheritedFrom = nullptr;
7776 if (auto Inherited = Constructor->getInheritedConstructor())
7777 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007778 if (Entity.getKind() == InitializedEntity::EK_Base) {
7779 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007780 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007781 << S.Context.getTypeDeclType(Constructor->getParent())
7782 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00007783 << Entity.getType()
7784 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007785
7786 RecordDecl *BaseDecl
7787 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7788 ->getDecl();
7789 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7790 << S.Context.getTagDeclType(BaseDecl);
7791 } else {
7792 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007793 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007794 << S.Context.getTypeDeclType(Constructor->getParent())
7795 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00007796 << Entity.getName()
7797 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00007798 S.Diag(Entity.getDecl()->getLocation(),
7799 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007800
7801 if (const RecordType *Record
7802 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007804 diag::note_previous_decl)
7805 << S.Context.getTagDeclType(Record->getDecl());
7806 }
7807 break;
7808 }
7809
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007810 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7811 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007812 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007813 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007814
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007815 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007816 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007817 OverloadingResult Ovl
7818 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00007819 if (Ovl != OR_Deleted) {
7820 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7821 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007822 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00007823 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007824 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00007825
7826 // If this is a defaulted or implicitly-declared function, then
7827 // it was implicitly deleted. Make it clear that the deletion was
7828 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00007829 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007830 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00007831 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007832 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00007833 else
7834 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7835 << true << DestType << ArgsRange;
7836
7837 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007838 break;
7839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007840
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007841 case OR_Success:
7842 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007843 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007844 }
David Blaikie60deeee2012-01-17 08:24:58 +00007845 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007846
Douglas Gregor85dabae2009-12-16 01:38:02 +00007847 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007848 if (Entity.getKind() == InitializedEntity::EK_Member &&
7849 isa<CXXConstructorDecl>(S.CurContext)) {
7850 // This is implicit default-initialization of a const member in
7851 // a constructor. Complain that it needs to be explicitly
7852 // initialized.
7853 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7854 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007855 << (Constructor->getInheritedConstructor() ? 2 :
7856 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007857 << S.Context.getTypeDeclType(Constructor->getParent())
7858 << /*const=*/1
7859 << Entity.getName();
7860 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7861 << Entity.getName();
7862 } else {
7863 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00007864 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007865 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00007866 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007867
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007868 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00007869 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007870 diag::err_init_incomplete_type);
7871 break;
7872
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007873 case FK_ListInitializationFailed: {
7874 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00007875 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7876 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007877 break;
7878 }
John McCall4124c492011-10-17 18:40:02 +00007879
7880 case FK_PlaceholderType: {
7881 // FIXME: Already diagnosed!
7882 break;
7883 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00007884
Sebastian Redl048a6d72012-04-01 19:54:59 +00007885 case FK_ExplicitConstructor: {
7886 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7887 << Args[0]->getSourceRange();
7888 OverloadCandidateSet::iterator Best;
7889 OverloadingResult Ovl
7890 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00007891 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007892 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7893 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00007894 S.Diag(CtorDecl->getLocation(),
7895 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007896 break;
7897 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007899
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007900 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007901 return true;
7902}
Douglas Gregore1314a62009-12-18 05:02:21 +00007903
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007904void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007905 switch (SequenceKind) {
7906 case FailedSequence: {
7907 OS << "Failed sequence: ";
7908 switch (Failure) {
7909 case FK_TooManyInitsForReference:
7910 OS << "too many initializers for reference";
7911 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007912
Richard Smith49a6b6e2017-03-24 01:14:25 +00007913 case FK_ParenthesizedListInitForReference:
7914 OS << "parenthesized list init for reference";
7915 break;
7916
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007917 case FK_ArrayNeedsInitList:
7918 OS << "array requires initializer list";
7919 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007920
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007921 case FK_AddressOfUnaddressableFunction:
7922 OS << "address of unaddressable function was taken";
7923 break;
7924
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007925 case FK_ArrayNeedsInitListOrStringLiteral:
7926 OS << "array requires initializer list or string literal";
7927 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007928
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007929 case FK_ArrayNeedsInitListOrWideStringLiteral:
7930 OS << "array requires initializer list or wide string literal";
7931 break;
7932
7933 case FK_NarrowStringIntoWideCharArray:
7934 OS << "narrow string into wide char array";
7935 break;
7936
7937 case FK_WideStringIntoCharArray:
7938 OS << "wide string into char array";
7939 break;
7940
7941 case FK_IncompatWideStringIntoWideChar:
7942 OS << "incompatible wide string into wide char array";
7943 break;
7944
Douglas Gregore2f943b2011-02-22 18:29:51 +00007945 case FK_ArrayTypeMismatch:
7946 OS << "array type mismatch";
7947 break;
7948
7949 case FK_NonConstantArrayInit:
7950 OS << "non-constant array initializer";
7951 break;
7952
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007953 case FK_AddressOfOverloadFailed:
7954 OS << "address of overloaded function failed";
7955 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007956
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007957 case FK_ReferenceInitOverloadFailed:
7958 OS << "overload resolution for reference initialization failed";
7959 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007960
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007961 case FK_NonConstLValueReferenceBindingToTemporary:
7962 OS << "non-const lvalue reference bound to temporary";
7963 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007964
Richard Smithb8c0f552016-12-09 18:49:13 +00007965 case FK_NonConstLValueReferenceBindingToBitfield:
7966 OS << "non-const lvalue reference bound to bit-field";
7967 break;
7968
7969 case FK_NonConstLValueReferenceBindingToVectorElement:
7970 OS << "non-const lvalue reference bound to vector element";
7971 break;
7972
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007973 case FK_NonConstLValueReferenceBindingToUnrelated:
7974 OS << "non-const lvalue reference bound to unrelated type";
7975 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007976
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007977 case FK_RValueReferenceBindingToLValue:
7978 OS << "rvalue reference bound to an lvalue";
7979 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007980
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007981 case FK_ReferenceInitDropsQualifiers:
7982 OS << "reference initialization drops qualifiers";
7983 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007984
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007985 case FK_ReferenceInitFailed:
7986 OS << "reference initialization failed";
7987 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007988
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007989 case FK_ConversionFailed:
7990 OS << "conversion failed";
7991 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007992
John Wiegley01296292011-04-08 18:41:53 +00007993 case FK_ConversionFromPropertyFailed:
7994 OS << "conversion from property failed";
7995 break;
7996
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007997 case FK_TooManyInitsForScalar:
7998 OS << "too many initializers for scalar";
7999 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008000
Richard Smith49a6b6e2017-03-24 01:14:25 +00008001 case FK_ParenthesizedListInitForScalar:
8002 OS << "parenthesized list init for reference";
8003 break;
8004
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008005 case FK_ReferenceBindingToInitList:
8006 OS << "referencing binding to initializer list";
8007 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008008
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008009 case FK_InitListBadDestinationType:
8010 OS << "initializer list for non-aggregate, non-scalar type";
8011 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008012
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008013 case FK_UserConversionOverloadFailed:
8014 OS << "overloading failed for user-defined conversion";
8015 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008016
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008017 case FK_ConstructorOverloadFailed:
8018 OS << "constructor overloading failed";
8019 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008021 case FK_DefaultInitOfConst:
8022 OS << "default initialization of a const variable";
8023 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008024
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00008025 case FK_Incomplete:
8026 OS << "initialization of incomplete type";
8027 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008028
8029 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008030 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00008031 break;
8032
John McCalla59dc2f2012-01-05 00:13:19 +00008033 case FK_VariableLengthArrayHasInitializer:
8034 OS << "variable length array has an initializer";
8035 break;
8036
John McCall4124c492011-10-17 18:40:02 +00008037 case FK_PlaceholderType:
8038 OS << "initializer expression isn't contextually valid";
8039 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00008040
8041 case FK_ListConstructorOverloadFailed:
8042 OS << "list constructor overloading failed";
8043 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008044
Sebastian Redl048a6d72012-04-01 19:54:59 +00008045 case FK_ExplicitConstructor:
8046 OS << "list copy initialization chose explicit constructor";
8047 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008048 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008049 OS << '\n';
8050 return;
8051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008052
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008053 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00008054 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008055 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008056
Sebastian Redld201edf2011-06-05 13:59:11 +00008057 case NormalSequence:
8058 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008059 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008061
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008062 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8063 if (S != step_begin()) {
8064 OS << " -> ";
8065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008067 switch (S->Kind) {
8068 case SK_ResolveAddressOfOverloadedFunction:
8069 OS << "resolve address of overloaded function";
8070 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008071
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008072 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008073 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008074 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008075
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008076 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008077 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008078 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008079
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008080 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008081 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008082 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008083
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008084 case SK_BindReference:
8085 OS << "bind reference to lvalue";
8086 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008087
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008088 case SK_BindReferenceToTemporary:
8089 OS << "bind reference to a temporary";
8090 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008091
Richard Smithb8c0f552016-12-09 18:49:13 +00008092 case SK_FinalCopy:
8093 OS << "final copy in class direct-initialization";
8094 break;
8095
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008096 case SK_ExtraneousCopyToTemporary:
8097 OS << "extraneous C++03 copy to temporary";
8098 break;
8099
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008100 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008101 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008102 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008103
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008104 case SK_QualificationConversionRValue:
8105 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008106 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008107
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008108 case SK_QualificationConversionXValue:
8109 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008110 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008111
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008112 case SK_QualificationConversionLValue:
8113 OS << "qualification conversion (lvalue)";
8114 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008115
Richard Smith77be48a2014-07-31 06:31:19 +00008116 case SK_AtomicConversion:
8117 OS << "non-atomic-to-atomic conversion";
8118 break;
8119
Jordan Roseb1312a52013-04-11 00:58:58 +00008120 case SK_LValueToRValue:
8121 OS << "load (lvalue to rvalue)";
8122 break;
8123
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008124 case SK_ConversionSequence:
8125 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008126 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008127 OS << ")";
8128 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008129
Richard Smithaaa0ec42013-09-21 21:19:19 +00008130 case SK_ConversionSequenceNoNarrowing:
8131 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008132 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008133 OS << ")";
8134 break;
8135
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008136 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008137 OS << "list aggregate initialization";
8138 break;
8139
Sebastian Redl29526f02011-11-27 16:50:07 +00008140 case SK_UnwrapInitList:
8141 OS << "unwrap reference initializer list";
8142 break;
8143
8144 case SK_RewrapInitList:
8145 OS << "rewrap reference initializer list";
8146 break;
8147
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008148 case SK_ConstructorInitialization:
8149 OS << "constructor initialization";
8150 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008151
Richard Smith53324112014-07-16 21:33:43 +00008152 case SK_ConstructorInitializationFromList:
8153 OS << "list initialization via constructor";
8154 break;
8155
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008156 case SK_ZeroInitialization:
8157 OS << "zero initialization";
8158 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008159
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008160 case SK_CAssignment:
8161 OS << "C assignment";
8162 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008163
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008164 case SK_StringInit:
8165 OS << "string initialization";
8166 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008167
8168 case SK_ObjCObjectConversion:
8169 OS << "Objective-C object conversion";
8170 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008171
Richard Smith410306b2016-12-12 02:53:20 +00008172 case SK_ArrayLoopIndex:
8173 OS << "indexing for array initialization loop";
8174 break;
8175
8176 case SK_ArrayLoopInit:
8177 OS << "array initialization loop";
8178 break;
8179
Douglas Gregore2f943b2011-02-22 18:29:51 +00008180 case SK_ArrayInit:
8181 OS << "array initialization";
8182 break;
John McCall31168b02011-06-15 23:02:42 +00008183
Richard Smith378b8c82016-12-14 03:22:16 +00008184 case SK_GNUArrayInit:
8185 OS << "array initialization (GNU extension)";
8186 break;
8187
Richard Smithebeed412012-02-15 22:38:09 +00008188 case SK_ParenthesizedArrayInit:
8189 OS << "parenthesized array initialization";
8190 break;
8191
John McCall31168b02011-06-15 23:02:42 +00008192 case SK_PassByIndirectCopyRestore:
8193 OS << "pass by indirect copy and restore";
8194 break;
8195
8196 case SK_PassByIndirectRestore:
8197 OS << "pass by indirect restore";
8198 break;
8199
8200 case SK_ProduceObjCObject:
8201 OS << "Objective-C object retension";
8202 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008203
8204 case SK_StdInitializerList:
8205 OS << "std::initializer_list from initializer list";
8206 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008207
Richard Smithf8adcdc2014-07-17 05:12:35 +00008208 case SK_StdInitializerListConstructorCall:
8209 OS << "list initialization from std::initializer_list";
8210 break;
8211
Guy Benyei61054192013-02-07 10:55:47 +00008212 case SK_OCLSamplerInit:
8213 OS << "OpenCL sampler_t from integer constant";
8214 break;
8215
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008216 case SK_OCLZeroEvent:
8217 OS << "OpenCL event_t from zero";
8218 break;
Egor Churaev89831422016-12-23 14:55:49 +00008219
8220 case SK_OCLZeroQueue:
8221 OS << "OpenCL queue_t from zero";
8222 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008223 }
Richard Smith6b216962013-02-05 05:52:24 +00008224
8225 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008226 }
Richard Smith6b216962013-02-05 05:52:24 +00008227
8228 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008229}
8230
8231void InitializationSequence::dump() const {
8232 dump(llvm::errs());
8233}
8234
Richard Smithaaa0ec42013-09-21 21:19:19 +00008235static void DiagnoseNarrowingInInitList(Sema &S,
8236 const ImplicitConversionSequence &ICS,
8237 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008238 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008239 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008240 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008241 switch (ICS.getKind()) {
8242 case ImplicitConversionSequence::StandardConversion:
8243 SCS = &ICS.Standard;
8244 break;
8245 case ImplicitConversionSequence::UserDefinedConversion:
8246 SCS = &ICS.UserDefined.After;
8247 break;
8248 case ImplicitConversionSequence::AmbiguousConversion:
8249 case ImplicitConversionSequence::EllipsisConversion:
8250 case ImplicitConversionSequence::BadConversion:
8251 return;
8252 }
8253
Richard Smith66e05fe2012-01-18 05:21:49 +00008254 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8255 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00008256 QualType ConstantType;
8257 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8258 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00008259 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00008260 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00008261 // No narrowing occurred.
8262 return;
8263
8264 case NK_Type_Narrowing:
8265 // This was a floating-to-integer conversion, which is always considered a
8266 // narrowing conversion even if the value is a constant and can be
8267 // represented exactly as an integer.
8268 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008269 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8270 ? diag::warn_init_list_type_narrowing
8271 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008272 << PostInit->getSourceRange()
8273 << PreNarrowingType.getLocalUnqualifiedType()
8274 << EntityType.getLocalUnqualifiedType();
8275 break;
8276
8277 case NK_Constant_Narrowing:
8278 // A constant value was narrowed.
8279 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008280 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8281 ? diag::warn_init_list_constant_narrowing
8282 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008283 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00008284 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00008285 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008286 break;
8287
8288 case NK_Variable_Narrowing:
8289 // A variable's value may have been narrowed.
8290 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008291 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8292 ? diag::warn_init_list_variable_narrowing
8293 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008294 << PostInit->getSourceRange()
8295 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00008296 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008297 break;
8298 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008299
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008300 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008301 llvm::raw_svector_ostream OS(StaticCast);
8302 OS << "static_cast<";
8303 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8304 // It's important to use the typedef's name if there is one so that the
8305 // fixit doesn't break code using types like int64_t.
8306 //
8307 // FIXME: This will break if the typedef requires qualification. But
8308 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008309 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008310 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00008311 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008312 else {
8313 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8314 // with a broken cast.
8315 return;
8316 }
8317 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00008318 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008319 << PostInit->getSourceRange()
8320 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8321 << FixItHint::CreateInsertion(
8322 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008323}
8324
Douglas Gregore1314a62009-12-18 05:02:21 +00008325//===----------------------------------------------------------------------===//
8326// Initialization helper functions
8327//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00008328bool
8329Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8330 ExprResult Init) {
8331 if (Init.isInvalid())
8332 return false;
8333
8334 Expr *InitE = Init.get();
8335 assert(InitE && "No initialization expression");
8336
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00008337 InitializationKind Kind
8338 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008339 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00008340 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00008341}
8342
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008343ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00008344Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8345 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008346 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00008347 bool TopLevelOfInitList,
8348 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00008349 if (Init.isInvalid())
8350 return ExprError();
8351
John McCall1f425642010-11-11 03:21:53 +00008352 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00008353 assert(InitE && "No initialization expression?");
8354
8355 if (EqualLoc.isInvalid())
8356 EqualLoc = InitE->getLocStart();
8357
8358 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00008359 EqualLoc,
8360 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00008361 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008362
Alex Lorenzde69ff92017-05-16 10:23:58 +00008363 // Prevent infinite recursion when performing parameter copy-initialization.
8364 const bool ShouldTrackCopy =
8365 Entity.isParameterKind() && Seq.isConstructorInitialization();
8366 if (ShouldTrackCopy) {
8367 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
8368 CurrentParameterCopyTypes.end()) {
8369 Seq.SetOverloadFailure(
8370 InitializationSequence::FK_ConstructorOverloadFailed,
8371 OR_No_Viable_Function);
8372
8373 // Try to give a meaningful diagnostic note for the problematic
8374 // constructor.
8375 const auto LastStep = Seq.step_end() - 1;
8376 assert(LastStep->Kind ==
8377 InitializationSequence::SK_ConstructorInitialization);
8378 const FunctionDecl *Function = LastStep->Function.Function;
8379 auto Candidate =
8380 llvm::find_if(Seq.getFailedCandidateSet(),
8381 [Function](const OverloadCandidate &Candidate) -> bool {
8382 return Candidate.Viable &&
8383 Candidate.Function == Function &&
8384 Candidate.Conversions.size() > 0;
8385 });
8386 if (Candidate != Seq.getFailedCandidateSet().end() &&
8387 Function->getNumParams() > 0) {
8388 Candidate->Viable = false;
8389 Candidate->FailureKind = ovl_fail_bad_conversion;
8390 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
8391 InitE,
8392 Function->getParamDecl(0)->getType());
8393 }
8394 }
8395 CurrentParameterCopyTypes.push_back(Entity.getType());
8396 }
8397
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008398 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00008399
Alex Lorenzde69ff92017-05-16 10:23:58 +00008400 if (ShouldTrackCopy)
8401 CurrentParameterCopyTypes.pop_back();
8402
Richard Smith66e05fe2012-01-18 05:21:49 +00008403 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00008404}
Richard Smith60437622017-02-09 19:17:44 +00008405
Richard Smith1363e8f2017-09-07 07:22:36 +00008406/// Determine whether RD is, or is derived from, a specialization of CTD.
8407static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
8408 ClassTemplateDecl *CTD) {
8409 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
8410 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
8411 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
8412 };
8413 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
8414}
8415
Richard Smith60437622017-02-09 19:17:44 +00008416QualType Sema::DeduceTemplateSpecializationFromInitializer(
8417 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8418 const InitializationKind &Kind, MultiExprArg Inits) {
8419 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8420 TSInfo->getType()->getContainedDeducedType());
8421 assert(DeducedTST && "not a deduced template specialization type");
8422
8423 // We can only perform deduction for class templates.
8424 auto TemplateName = DeducedTST->getTemplateName();
8425 auto *Template =
8426 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8427 if (!Template) {
8428 Diag(Kind.getLocation(),
8429 diag::err_deduced_non_class_template_specialization_type)
8430 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8431 if (auto *TD = TemplateName.getAsTemplateDecl())
8432 Diag(TD->getLocation(), diag::note_template_decl_here);
8433 return QualType();
8434 }
8435
Richard Smith32918772017-02-14 00:25:28 +00008436 // Can't deduce from dependent arguments.
8437 if (Expr::hasAnyTypeDependentArguments(Inits))
8438 return Context.DependentTy;
8439
Richard Smith60437622017-02-09 19:17:44 +00008440 // FIXME: Perform "exact type" matching first, per CWG discussion?
8441 // Or implement this via an implied 'T(T) -> T' deduction guide?
8442
8443 // FIXME: Do we need/want a std::initializer_list<T> special case?
8444
Richard Smith32918772017-02-14 00:25:28 +00008445 // Look up deduction guides, including those synthesized from constructors.
8446 //
Richard Smith60437622017-02-09 19:17:44 +00008447 // C++1z [over.match.class.deduct]p1:
8448 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00008449 // - For each constructor of the class template designated by the
8450 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00008451 // - For each deduction-guide, a function or function template [...]
8452 DeclarationNameInfo NameInfo(
8453 Context.DeclarationNames.getCXXDeductionGuideName(Template),
8454 TSInfo->getTypeLoc().getEndLoc());
8455 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
8456 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00008457
8458 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
8459 // clear on this, but they're not found by name so access does not apply.
8460 Guides.suppressDiagnostics();
8461
8462 // Figure out if this is list-initialization.
8463 InitListExpr *ListInit =
8464 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
8465 ? dyn_cast<InitListExpr>(Inits[0])
8466 : nullptr;
8467
8468 // C++1z [over.match.class.deduct]p1:
8469 // Initialization and overload resolution are performed as described in
8470 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
8471 // (as appropriate for the type of initialization performed) for an object
8472 // of a hypothetical class type, where the selected functions and function
8473 // templates are considered to be the constructors of that class type
8474 //
8475 // Since we know we're initializing a class type of a type unrelated to that
8476 // of the initializer, this reduces to something fairly reasonable.
8477 OverloadCandidateSet Candidates(Kind.getLocation(),
8478 OverloadCandidateSet::CSK_Normal);
8479 OverloadCandidateSet::iterator Best;
8480 auto tryToResolveOverload =
8481 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00008482 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Richard Smith32918772017-02-14 00:25:28 +00008483 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
8484 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00008485 if (D->isInvalidDecl())
8486 continue;
8487
Richard Smithbc491202017-02-17 20:05:37 +00008488 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
8489 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
8490 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
8491 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00008492 continue;
8493
8494 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
8495 // For copy-initialization, the candidate functions are all the
8496 // converting constructors (12.3.1) of that class.
8497 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
8498 // The converting constructors of T are candidate functions.
8499 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00008500 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00008501 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00008502 continue;
Richard Smith60437622017-02-09 19:17:44 +00008503
8504 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00008505 // could never be called with one argument are not interesting to
8506 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00008507 if (GD->getMinRequiredArguments() > 1 ||
8508 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00008509 continue;
8510 }
8511
8512 // C++ [over.match.list]p1.1: (first phase list initialization)
8513 // Initially, the candidate functions are the initializer-list
8514 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00008515 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00008516 continue;
8517
8518 // C++ [over.match.list]p1.2: (second phase list initialization)
8519 // the candidate functions are all the constructors of the class T
8520 // C++ [over.match.ctor]p1: (all other cases)
8521 // the candidate functions are all the constructors of the class of
8522 // the object being initialized
8523
8524 // C++ [over.best.ics]p4:
8525 // When [...] the constructor [...] is a candidate by
8526 // - [over.match.copy] (in all cases)
8527 // FIXME: The "second phase of [over.match.list] case can also
8528 // theoretically happen here, but it's not clear whether we can
8529 // ever have a parameter of the right type.
8530 bool SuppressUserConversions = Kind.isCopyInit();
8531
Richard Smith60437622017-02-09 19:17:44 +00008532 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00008533 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
8534 Inits, Candidates,
8535 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00008536 else
Richard Smithbc491202017-02-17 20:05:37 +00008537 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00008538 SuppressUserConversions);
8539 }
8540 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
8541 };
8542
8543 OverloadingResult Result = OR_No_Viable_Function;
8544
8545 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
8546 // try initializer-list constructors.
8547 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00008548 bool TryListConstructors = true;
8549
8550 // Try list constructors unless the list is empty and the class has one or
8551 // more default constructors, in which case those constructors win.
8552 if (!ListInit->getNumInits()) {
8553 for (NamedDecl *D : Guides) {
8554 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
8555 if (FD && FD->getMinRequiredArguments() == 0) {
8556 TryListConstructors = false;
8557 break;
8558 }
8559 }
Richard Smith1363e8f2017-09-07 07:22:36 +00008560 } else if (ListInit->getNumInits() == 1) {
8561 // C++ [over.match.class.deduct]:
8562 // As an exception, the first phase in [over.match.list] (considering
8563 // initializer-list constructors) is omitted if the initializer list
8564 // consists of a single expression of type cv U, where U is a
8565 // specialization of C or a class derived from a specialization of C.
8566 Expr *E = ListInit->getInit(0);
8567 auto *RD = E->getType()->getAsCXXRecordDecl();
8568 if (!isa<InitListExpr>(E) && RD &&
8569 isOrIsDerivedFromSpecializationOf(RD, Template))
8570 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00008571 }
8572
8573 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00008574 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
8575 // Then unwrap the initializer list and try again considering all
8576 // constructors.
8577 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
8578 }
8579
8580 // If list-initialization fails, or if we're doing any other kind of
8581 // initialization, we (eventually) consider constructors.
8582 if (Result == OR_No_Viable_Function)
8583 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
8584
8585 switch (Result) {
8586 case OR_Ambiguous:
8587 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
8588 << TemplateName;
8589 // FIXME: For list-initialization candidates, it'd usually be better to
8590 // list why they were not viable when given the initializer list itself as
8591 // an argument.
8592 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
8593 return QualType();
8594
Richard Smith32918772017-02-14 00:25:28 +00008595 case OR_No_Viable_Function: {
8596 CXXRecordDecl *Primary =
8597 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
8598 bool Complete =
8599 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00008600 Diag(Kind.getLocation(),
8601 Complete ? diag::err_deduced_class_template_ctor_no_viable
8602 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00008603 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00008604 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
8605 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00008606 }
Richard Smith60437622017-02-09 19:17:44 +00008607
8608 case OR_Deleted: {
8609 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
8610 << TemplateName;
8611 NoteDeletedFunction(Best->Function);
8612 return QualType();
8613 }
8614
8615 case OR_Success:
8616 // C++ [over.match.list]p1:
8617 // In copy-list-initialization, if an explicit constructor is chosen, the
8618 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00008619 if (Kind.isCopyInit() && ListInit &&
8620 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00008621 bool IsDeductionGuide = !Best->Function->isImplicit();
8622 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
8623 << TemplateName << IsDeductionGuide;
8624 Diag(Best->Function->getLocation(),
8625 diag::note_explicit_ctor_deduction_guide_here)
8626 << IsDeductionGuide;
8627 return QualType();
8628 }
8629
8630 // Make sure we didn't select an unusable deduction guide, and mark it
8631 // as referenced.
8632 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
8633 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
8634 break;
8635 }
8636
8637 // C++ [dcl.type.class.deduct]p1:
8638 // The placeholder is replaced by the return type of the function selected
8639 // by overload resolution for class template deduction.
8640 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
8641}