blob: bd8522d597717be452f9bed111564272a2506512 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000029
Douglas Gregore4a0bb72009-01-22 00:58:24 +000030using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000031
Chris Lattner0cb78032009-02-24 22:27:37 +000032//===----------------------------------------------------------------------===//
33// Sema Initialization Checking
34//===----------------------------------------------------------------------===//
35
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000036/// \brief Check whether T is compatible with a wide character type (wchar_t,
37/// char16_t or char32_t).
38static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
39 if (Context.typesAreCompatible(Context.getWideCharType(), T))
40 return true;
41 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
42 return Context.typesAreCompatible(Context.Char16Ty, T) ||
43 Context.typesAreCompatible(Context.Char32Ty, T);
44 }
45 return false;
46}
47
48enum StringInitFailureKind {
49 SIF_None,
50 SIF_NarrowStringIntoWideChar,
51 SIF_WideStringIntoChar,
52 SIF_IncompatWideStringIntoWideChar,
53 SIF_Other
54};
55
56/// \brief Check whether the array of type AT can be initialized by the Init
57/// expression by means of string initialization. Returns SIF_None if so,
58/// otherwise returns a StringInitFailureKind that describes why the
59/// initialization would not work.
60static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
61 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000062 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000063 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000064
Chris Lattnera9196812009-02-26 23:26:43 +000065 // See if this is a string literal or @encode.
66 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattnera9196812009-02-26 23:26:43 +000068 // Handle @encode, which is a narrow string.
69 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000070 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000071
72 // Otherwise we can only handle string literals.
73 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000074 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000075 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000076
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000077 const QualType ElemTy =
78 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000079
80 switch (SL->getKind()) {
81 case StringLiteral::Ascii:
82 case StringLiteral::UTF8:
83 // char array can be initialized with a narrow string.
84 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000085 if (ElemTy->isCharType())
86 return SIF_None;
87 if (IsWideCharCompatible(ElemTy, Context))
88 return SIF_NarrowStringIntoWideChar;
89 return SIF_Other;
90 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
91 // "An array with element type compatible with a qualified or unqualified
92 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
93 // string literal with the corresponding encoding prefix (L, u, or U,
94 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +000095 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000096 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
97 return SIF_None;
98 if (ElemTy->isCharType())
99 return SIF_WideStringIntoChar;
100 if (IsWideCharCompatible(ElemTy, Context))
101 return SIF_IncompatWideStringIntoWideChar;
102 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000103 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000104 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
105 return SIF_None;
106 if (ElemTy->isCharType())
107 return SIF_WideStringIntoChar;
108 if (IsWideCharCompatible(ElemTy, Context))
109 return SIF_IncompatWideStringIntoWideChar;
110 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000111 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000112 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
113 return SIF_None;
114 if (ElemTy->isCharType())
115 return SIF_WideStringIntoChar;
116 if (IsWideCharCompatible(ElemTy, Context))
117 return SIF_IncompatWideStringIntoWideChar;
118 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Douglas Gregorfb65e592011-07-27 05:40:30 +0000121 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000122}
123
Hans Wennborg950f3182013-05-16 09:22:40 +0000124static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
125 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000126 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000127 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000128 return SIF_Other;
129 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000130}
131
Richard Smith430c23b2013-05-05 16:40:13 +0000132/// Update the type of a string literal, including any surrounding parentheses,
133/// to match the type of the object which it is initializing.
134static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000135 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000136 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000137 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
138 break;
139 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
140 E = PE->getSubExpr();
141 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
142 E = UO->getSubExpr();
143 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
144 E = GSE->getResultExpr();
145 else
146 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000147 }
Richard Smith430c23b2013-05-05 16:40:13 +0000148}
149
John McCall5decec92011-02-21 07:57:55 +0000150static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
151 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000152 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000153 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000154 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000155 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000156
Chris Lattner0cb78032009-02-24 22:27:37 +0000157 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000158 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000159 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000160 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000161 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000162 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
163 ConstVal,
164 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000165 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000166 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000167 }
Mike Stump11289f42009-09-09 15:08:12 +0000168
Eli Friedman893abe42009-05-29 18:22:49 +0000169 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000170
Eli Friedman554eba92011-04-11 00:23:45 +0000171 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000172 // the size may be smaller or larger than the string we are initializing.
173 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000174 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000175 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000176 // For Pascal strings it's OK to strip off the terminating null character,
177 // so the example below is valid:
178 //
179 // unsigned char a[2] = "\pa";
180 if (SL->isPascal())
181 StrLength--;
182 }
183
Eli Friedman554eba92011-04-11 00:23:45 +0000184 // [dcl.init.string]p2
185 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000186 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000187 diag::err_initializer_string_for_char_array_too_long)
188 << Str->getSourceRange();
189 } else {
190 // C99 6.7.8p14.
191 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000192 S.Diag(Str->getLocStart(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000193 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000194 << Str->getSourceRange();
195 }
Mike Stump11289f42009-09-09 15:08:12 +0000196
Eli Friedman893abe42009-05-29 18:22:49 +0000197 // Set the type to the actual size that we are initializing. If we have
198 // something like:
199 // char x[1] = "foo";
200 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000201 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000202}
203
Chris Lattner0cb78032009-02-24 22:27:37 +0000204//===----------------------------------------------------------------------===//
205// Semantic checking for initializer lists.
206//===----------------------------------------------------------------------===//
207
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000208namespace {
209
Douglas Gregorcde232f2009-01-29 01:05:33 +0000210/// @brief Semantic checking for initializer lists.
211///
212/// The InitListChecker class contains a set of routines that each
213/// handle the initialization of a certain kind of entity, e.g.,
214/// arrays, vectors, struct/union types, scalars, etc. The
215/// InitListChecker itself performs a recursive walk of the subobject
216/// structure of the type to be initialized, while stepping through
217/// the initializer list one element at a time. The IList and Index
218/// parameters to each of the Check* routines contain the active
219/// (syntactic) initializer list and the index into that initializer
220/// list that represents the current initializer. Each routine is
221/// responsible for moving that Index forward as it consumes elements.
222///
223/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000224/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000225/// initializer list and the index into that initializer list where we
226/// are copying initializers as we map them over to the semantic
227/// list. Once we have completed our recursive walk of the subobject
228/// structure, we will have constructed a full semantic initializer
229/// list.
230///
231/// C99 designators cause changes in the initializer list traversal,
232/// because they make the initialization "jump" into a specific
233/// subobject and then continue the initialization from that
234/// point. CheckDesignatedInitializer() recursively steps into the
235/// designated subobject and manages backing out the recursion to
236/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000237class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000238 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000239 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000240 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000241 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000242 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000244
Anders Carlsson6cabf312010-01-23 23:23:01 +0000245 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000246 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000247 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000248 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000249 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000250 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000251 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000252 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000253 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000254 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000255 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000256 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000257 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000258 unsigned &StructuredIndex,
259 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000260 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000261 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000262 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000263 InitListExpr *StructuredList,
264 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000265 void CheckComplexType(const InitializedEntity &Entity,
266 InitListExpr *IList, QualType DeclType,
267 unsigned &Index,
268 InitListExpr *StructuredList,
269 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000270 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000271 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000272 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000273 InitListExpr *StructuredList,
274 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000275 void CheckReferenceType(const InitializedEntity &Entity,
276 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000277 unsigned &Index,
278 InitListExpr *StructuredList,
279 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000280 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000281 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000282 InitListExpr *StructuredList,
283 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000284 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000285 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000286 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000287 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000288 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000289 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000290 unsigned &StructuredIndex,
291 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000292 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000293 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000294 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000295 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000296 InitListExpr *StructuredList,
297 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000298 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000299 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000300 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000301 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000302 RecordDecl::field_iterator *NextField,
303 llvm::APSInt *NextElementIndex,
304 unsigned &Index,
305 InitListExpr *StructuredList,
306 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000307 bool FinishSubobjectInit,
308 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000309 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
310 QualType CurrentObjectType,
311 InitListExpr *StructuredList,
312 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000313 SourceRange InitRange,
314 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000315 void UpdateStructuredListElement(InitListExpr *StructuredList,
316 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000317 Expr *expr);
318 int numArrayElements(QualType DeclType);
319 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000320
Richard Smith454a7cd2014-06-03 08:26:00 +0000321 static ExprResult PerformEmptyInit(Sema &SemaRef,
322 SourceLocation Loc,
323 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000324 bool VerifyOnly,
325 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000326
327 // Explanation on the "FillWithNoInit" mode:
328 //
329 // Assume we have the following definitions (Case#1):
330 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
331 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
332 //
333 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
334 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
335 //
336 // But if we have (Case#2):
337 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
338 //
339 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
340 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
341 //
342 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
343 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
344 // initializers but with special "NoInitExpr" place holders, which tells the
345 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000346 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
347 const InitializedEntity &ParentEntity,
348 InitListExpr *ILE, bool &RequiresSecondPass,
349 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000350 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000351 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000352 InitListExpr *ILE, bool &RequiresSecondPass,
353 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000354 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000355 InitListExpr *ILE, bool &RequiresSecondPass,
356 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000357 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
358 Expr *InitExpr, FieldDecl *Field,
359 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000360 void CheckEmptyInitializable(const InitializedEntity &Entity,
361 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000362
Douglas Gregor85df8d82009-01-29 00:45:39 +0000363public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000364 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000365 InitListExpr *IL, QualType &T, bool VerifyOnly,
366 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000367 bool HadError() { return hadError; }
368
369 // @brief Retrieves the fully-structured initializer list used for
370 // semantic analysis and code generation.
371 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
372};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000373
Chris Lattner9ececce2009-02-24 22:48:58 +0000374} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000375
Richard Smith454a7cd2014-06-03 08:26:00 +0000376ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
377 SourceLocation Loc,
378 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000379 bool VerifyOnly,
380 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000381 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
382 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000383 MultiExprArg SubInit;
384 Expr *InitExpr;
385 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
386
387 // C++ [dcl.init.aggr]p7:
388 // If there are fewer initializer-clauses in the list than there are
389 // members in the aggregate, then each member not explicitly initialized
390 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000391 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
392 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
393 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000394 // C++1y / DR1070:
395 // shall be initialized [...] from an empty initializer list.
396 //
397 // We apply the resolution of this DR to C++11 but not C++98, since C++98
398 // does not have useful semantics for initialization from an init list.
399 // We treat this as copy-initialization, because aggregate initialization
400 // always performs copy-initialization on its elements.
401 //
402 // Only do this if we're initializing a class type, to avoid filling in
403 // the initializer list where possible.
404 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
405 InitListExpr(SemaRef.Context, Loc, None, Loc);
406 InitExpr->setType(SemaRef.Context.VoidTy);
407 SubInit = InitExpr;
408 Kind = InitializationKind::CreateCopy(Loc, Loc);
409 } else {
410 // C++03:
411 // shall be value-initialized.
412 }
413
414 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000415 // libstdc++4.6 marks the vector default constructor as explicit in
416 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
417 // stlport does so too. Look for std::__debug for libstdc++, and for
418 // std:: for stlport. This is effectively a compiler-side implementation of
419 // LWG2193.
420 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
421 InitializationSequence::FK_ExplicitConstructor) {
422 OverloadCandidateSet::iterator Best;
423 OverloadingResult O =
424 InitSeq.getFailedCandidateSet()
425 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
426 (void)O;
427 assert(O == OR_Success && "Inconsistent overload resolution");
428 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
429 CXXRecordDecl *R = CtorDecl->getParent();
430
431 if (CtorDecl->getMinRequiredArguments() == 0 &&
432 CtorDecl->isExplicit() && R->getDeclName() &&
433 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000434 bool IsInStd = false;
435 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000436 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000437 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
438 IsInStd = true;
439 }
440
441 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
442 .Cases("basic_string", "deque", "forward_list", true)
443 .Cases("list", "map", "multimap", "multiset", true)
444 .Cases("priority_queue", "queue", "set", "stack", true)
445 .Cases("unordered_map", "unordered_set", "vector", true)
446 .Default(false)) {
447 InitSeq.InitializeFrom(
448 SemaRef, Entity,
449 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000450 MultiExprArg(), /*TopLevelOfInitList=*/false,
451 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000452 // Emit a warning for this. System header warnings aren't shown
453 // by default, but people working on system headers should see it.
454 if (!VerifyOnly) {
455 SemaRef.Diag(CtorDecl->getLocation(),
456 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000457 if (Entity.getKind() == InitializedEntity::EK_Member)
458 SemaRef.Diag(Entity.getDecl()->getLocation(),
459 diag::note_used_in_initialization_here);
460 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
461 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000462 }
463 }
464 }
465 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000466 if (!InitSeq) {
467 if (!VerifyOnly) {
468 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
469 if (Entity.getKind() == InitializedEntity::EK_Member)
470 SemaRef.Diag(Entity.getDecl()->getLocation(),
471 diag::note_in_omitted_aggregate_initializer)
472 << /*field*/1 << Entity.getDecl();
473 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
474 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
475 << /*array element*/0 << Entity.getElementIndex();
476 }
477 return ExprError();
478 }
479
480 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
481 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
482}
483
484void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
485 SourceLocation Loc) {
486 assert(VerifyOnly &&
487 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000488 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
489 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000490 hadError = true;
491}
492
Richard Smith872307e2016-03-08 22:17:41 +0000493void InitListChecker::FillInEmptyInitForBase(
494 unsigned Init, const CXXBaseSpecifier &Base,
495 const InitializedEntity &ParentEntity, InitListExpr *ILE,
496 bool &RequiresSecondPass, bool FillWithNoInit) {
497 assert(Init < ILE->getNumInits() && "should have been expanded");
498
499 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
500 SemaRef.Context, &Base, false, &ParentEntity);
501
502 if (!ILE->getInit(Init)) {
503 ExprResult BaseInit =
504 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
505 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
Manman Ren073db022016-03-10 18:53:19 +0000506 /*VerifyOnly*/ false,
507 TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000508 if (BaseInit.isInvalid()) {
509 hadError = true;
510 return;
511 }
512
513 ILE->setInit(Init, BaseInit.getAs<Expr>());
514 } else if (InitListExpr *InnerILE =
515 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
516 FillInEmptyInitializations(BaseEntity, InnerILE,
517 RequiresSecondPass, FillWithNoInit);
518 } else if (DesignatedInitUpdateExpr *InnerDIUE =
519 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
520 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
521 RequiresSecondPass, /*FillWithNoInit =*/true);
522 }
523}
524
Richard Smith454a7cd2014-06-03 08:26:00 +0000525void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000526 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000528 bool &RequiresSecondPass,
529 bool FillWithNoInit) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000530 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000531 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000532 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000533 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000534
535 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
536 if (!RType->getDecl()->isUnion())
537 assert(Init < NumInits && "This ILE should have been expanded");
538
Douglas Gregor2bb07652009-12-22 00:05:34 +0000539 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000540 if (FillWithNoInit) {
541 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
542 if (Init < NumInits)
543 ILE->setInit(Init, Filler);
544 else
545 ILE->updateInit(SemaRef.Context, Init, Filler);
546 return;
547 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000548 // C++1y [dcl.init.aggr]p7:
549 // If there are fewer initializer-clauses in the list than there are
550 // members in the aggregate, then each member not explicitly initialized
551 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000552 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000553 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
554 if (DIE.isInvalid()) {
555 hadError = true;
556 return;
557 }
Richard Smith852c9db2013-04-20 22:23:05 +0000558 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000559 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000560 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000561 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000562 RequiresSecondPass = true;
563 }
564 return;
565 }
566
Douglas Gregor2bb07652009-12-22 00:05:34 +0000567 if (Field->getType()->isReferenceType()) {
568 // C++ [dcl.init.aggr]p9:
569 // If an incomplete or empty initializer-list leaves a
570 // member of reference type uninitialized, the program is
571 // ill-formed.
572 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
573 << Field->getType()
574 << ILE->getSyntacticForm()->getSourceRange();
575 SemaRef.Diag(Field->getLocation(),
576 diag::note_uninit_reference_member);
577 hadError = true;
578 return;
579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Richard Smith454a7cd2014-06-03 08:26:00 +0000581 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000582 /*VerifyOnly*/false,
583 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000584 if (MemberInit.isInvalid()) {
585 hadError = true;
586 return;
587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588
Douglas Gregor2bb07652009-12-22 00:05:34 +0000589 if (hadError) {
590 // Do nothing
591 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000592 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000593 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
594 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000595 // extend the initializer list to include the constructor
596 // call and make a note that we'll need to take another pass
597 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000598 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000599 RequiresSecondPass = true;
600 }
601 } else if (InitListExpr *InnerILE
602 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000603 FillInEmptyInitializations(MemberEntity, InnerILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000604 RequiresSecondPass, FillWithNoInit);
605 else if (DesignatedInitUpdateExpr *InnerDIUE
606 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
607 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
608 RequiresSecondPass, /*FillWithNoInit =*/ true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000609}
610
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000611/// Recursively replaces NULL values within the given initializer list
612/// with expressions that perform value-initialization of the
613/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614void
Richard Smith454a7cd2014-06-03 08:26:00 +0000615InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000616 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000617 bool &RequiresSecondPass,
618 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000619 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000620 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000621
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000622 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000623 const RecordDecl *RDecl = RType->getDecl();
624 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000625 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000626 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000627 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
628 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000629 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000630 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000631 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
632 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000633 break;
634 }
635 }
636 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000637 // The fields beyond ILE->getNumInits() are default initialized, so in
638 // order to leave them uninitialized, the ILE is expanded and the extra
639 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000640 unsigned NumElems = numStructUnionElements(ILE->getType());
641 if (RDecl->hasFlexibleArrayMember())
642 ++NumElems;
643 if (ILE->getNumInits() < NumElems)
644 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000645
Douglas Gregor2bb07652009-12-22 00:05:34 +0000646 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000647
648 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
649 for (auto &Base : CXXRD->bases()) {
650 if (hadError)
651 return;
652
653 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
654 FillWithNoInit);
655 ++Init;
656 }
657 }
658
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000659 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000660 if (Field->isUnnamedBitfield())
661 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000662
Douglas Gregor2bb07652009-12-22 00:05:34 +0000663 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000664 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000665
Yunzhong Gaocb779302015-06-10 00:27:52 +0000666 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
667 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000668 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000669 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000670
Douglas Gregor2bb07652009-12-22 00:05:34 +0000671 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000672
Douglas Gregor2bb07652009-12-22 00:05:34 +0000673 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000674 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000675 break;
676 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000677 }
678
679 return;
Mike Stump11289f42009-09-09 15:08:12 +0000680 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000681
682 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000683
Douglas Gregor723796a2009-12-16 06:35:08 +0000684 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000685 unsigned NumInits = ILE->getNumInits();
686 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000687 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000688 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000689 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
690 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000692 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000693 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000694 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000695 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000697 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000698 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000699 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000700
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000701 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000702 if (hadError)
703 return;
704
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000705 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
706 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000707 ElementEntity.setElementIndex(Init);
708
Craig Topperc3ec1492014-05-26 06:22:03 +0000709 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000710 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
711 ILE->setInit(Init, ILE->getArrayFiller());
712 else if (!InitExpr && !ILE->hasArrayFiller()) {
713 Expr *Filler = nullptr;
714
715 if (FillWithNoInit)
716 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
717 else {
718 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
719 ElementEntity,
Manman Ren073db022016-03-10 18:53:19 +0000720 /*VerifyOnly*/false,
721 TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000722 if (ElementInit.isInvalid()) {
723 hadError = true;
724 return;
725 }
726
727 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000728 }
729
730 if (hadError) {
731 // Do nothing
732 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000733 // For arrays, just set the expression used for value-initialization
734 // of the "holes" in the array.
735 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000736 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000737 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000738 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000739 } else {
740 // For arrays, just set the expression used for value-initialization
741 // of the rest of elements and exit.
742 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000743 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000744 return;
745 }
746
Yunzhong Gaocb779302015-06-10 00:27:52 +0000747 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000748 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000749 // extend the initializer list to include the constructor
750 // call and make a note that we'll need to take another pass
751 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000752 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000753 RequiresSecondPass = true;
754 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000755 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000756 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000757 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000758 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
759 FillWithNoInit);
760 else if (DesignatedInitUpdateExpr *InnerDIUE
761 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
762 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
763 RequiresSecondPass, /*FillWithNoInit =*/ true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000764 }
765}
766
Douglas Gregor723796a2009-12-16 06:35:08 +0000767InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000768 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000769 bool VerifyOnly,
770 bool TreatUnavailableAsInvalid)
771 : SemaRef(S), VerifyOnly(VerifyOnly),
772 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000773 // FIXME: Check that IL isn't already the semantic form of some other
774 // InitListExpr. If it is, we'd create a broken AST.
775
Steve Narofff8ecff22008-05-01 22:18:59 +0000776 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000777
Richard Smith4e0d2e42013-09-20 20:10:22 +0000778 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000779 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000780 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000781 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000782
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000783 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000784 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000785 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000786 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000787 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000788 RequiresSecondPass);
789 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000790}
791
792int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000793 // FIXME: use a proper constant
794 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000795 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000796 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000797 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
798 }
799 return maxElements;
800}
801
802int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000803 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000804 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000805 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
806 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000807 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000808 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000809 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000810
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000811 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000812 return std::min(InitializableMembers, 1);
813 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000814}
815
Richard Smith4e0d2e42013-09-20 20:10:22 +0000816/// Check whether the range of the initializer \p ParentIList from element
817/// \p Index onwards can be used to initialize an object of type \p T. Update
818/// \p Index to indicate how many elements of the list were consumed.
819///
820/// This also fills in \p StructuredList, from element \p StructuredIndex
821/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000822void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000823 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000824 QualType T, unsigned &Index,
825 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000826 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000827 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000828
Steve Narofff8ecff22008-05-01 22:18:59 +0000829 if (T->isArrayType())
830 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000831 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000832 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000833 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000834 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000835 else
David Blaikie83d382b2011-09-23 05:06:16 +0000836 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000837
Eli Friedmane0f832b2008-05-25 13:49:22 +0000838 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000839 if (!VerifyOnly)
840 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
841 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000842 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000843 hadError = true;
844 return;
845 }
846
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000847 // Build a structured initializer list corresponding to this subobject.
848 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000849 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
850 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000851 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000852 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000853 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000854
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000855 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000856 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000858 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000859 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000860 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000861
Richard Smithde229232013-06-06 11:41:05 +0000862 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000863 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000864
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000865 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000866 // Update the structured sub-object initializer so that it's ending
867 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000868 if (EndIndex < ParentIList->getNumInits() &&
869 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000870 SourceLocation EndLoc
871 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
872 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000875 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000876 if (T->isArrayType() || T->isRecordType()) {
877 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000878 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000879 << StructuredSubobjectInitList->getSourceRange()
880 << FixItHint::CreateInsertion(
881 StructuredSubobjectInitList->getLocStart(), "{")
882 << FixItHint::CreateInsertion(
883 SemaRef.getLocForEndOfToken(
884 StructuredSubobjectInitList->getLocEnd()),
885 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000886 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000887 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000888}
889
Richard Smith420fa122015-02-12 01:50:05 +0000890/// Warn that \p Entity was of scalar type and was initialized by a
891/// single-element braced initializer list.
892static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
893 SourceRange Braces) {
894 // Don't warn during template instantiation. If the initialization was
895 // non-dependent, we warned during the initial parse; otherwise, the
896 // type might not be scalar in some uses of the template.
897 if (!S.ActiveTemplateInstantiations.empty())
898 return;
899
900 unsigned DiagID = 0;
901
902 switch (Entity.getKind()) {
903 case InitializedEntity::EK_VectorElement:
904 case InitializedEntity::EK_ComplexElement:
905 case InitializedEntity::EK_ArrayElement:
906 case InitializedEntity::EK_Parameter:
907 case InitializedEntity::EK_Parameter_CF_Audited:
908 case InitializedEntity::EK_Result:
909 // Extra braces here are suspicious.
910 DiagID = diag::warn_braces_around_scalar_init;
911 break;
912
913 case InitializedEntity::EK_Member:
914 // Warn on aggregate initialization but not on ctor init list or
915 // default member initializer.
916 if (Entity.getParent())
917 DiagID = diag::warn_braces_around_scalar_init;
918 break;
919
920 case InitializedEntity::EK_Variable:
921 case InitializedEntity::EK_LambdaCapture:
922 // No warning, might be direct-list-initialization.
923 // FIXME: Should we warn for copy-list-initialization in these cases?
924 break;
925
926 case InitializedEntity::EK_New:
927 case InitializedEntity::EK_Temporary:
928 case InitializedEntity::EK_CompoundLiteralInit:
929 // No warning, braces are part of the syntax of the underlying construct.
930 break;
931
932 case InitializedEntity::EK_RelatedResult:
933 // No warning, we already warned when initializing the result.
934 break;
935
936 case InitializedEntity::EK_Exception:
937 case InitializedEntity::EK_Base:
938 case InitializedEntity::EK_Delegating:
939 case InitializedEntity::EK_BlockElement:
940 llvm_unreachable("unexpected braced scalar init");
941 }
942
943 if (DiagID) {
944 S.Diag(Braces.getBegin(), DiagID)
945 << Braces
946 << FixItHint::CreateRemoval(Braces.getBegin())
947 << FixItHint::CreateRemoval(Braces.getEnd());
948 }
949}
950
Richard Smith4e0d2e42013-09-20 20:10:22 +0000951/// Check whether the initializer \p IList (that was written with explicit
952/// braces) can be used to initialize an object of type \p T.
953///
954/// This also fills in \p StructuredList with the fully-braced, desugared
955/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000956void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000957 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000958 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000959 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000960 if (!VerifyOnly) {
961 SyntacticToSemantic[IList] = StructuredList;
962 StructuredList->setSyntacticForm(IList);
963 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000964
965 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000966 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000967 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000968 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000969 QualType ExprTy = T;
970 if (!ExprTy->isArrayType())
971 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000972 IList->setType(ExprTy);
973 StructuredList->setType(ExprTy);
974 }
Eli Friedman85f54972008-05-25 13:22:35 +0000975 if (hadError)
976 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000977
Eli Friedman85f54972008-05-25 13:22:35 +0000978 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000979 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000980 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000981 if (SemaRef.getLangOpts().CPlusPlus ||
982 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000983 IList->getType()->isVectorType())) {
984 hadError = true;
985 }
986 return;
987 }
988
Eli Friedmanbd327452009-05-29 20:20:05 +0000989 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000990 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
991 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000992 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000993 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000994 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000995 hadError = true;
996 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000997 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000998 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000999 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001000 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001001 // Don't complain for incomplete types, since we'll get an error
1002 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001003 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001004 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001005 CurrentObjectType->isArrayType()? 0 :
1006 CurrentObjectType->isVectorType()? 1 :
1007 CurrentObjectType->isScalarType()? 2 :
1008 CurrentObjectType->isUnionType()? 3 :
1009 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001010
Richard Smith1b98ccc2014-07-19 01:39:17 +00001011 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001012 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001013 DK = diag::err_excess_initializers;
1014 hadError = true;
1015 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001016 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001017 DK = diag::err_excess_initializers;
1018 hadError = true;
1019 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001020
Chris Lattnerb0912a52009-02-24 22:50:46 +00001021 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001022 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001023 }
1024 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001025
Richard Smith420fa122015-02-12 01:50:05 +00001026 if (!VerifyOnly && T->isScalarType() &&
1027 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1028 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +00001029}
1030
Anders Carlsson6cabf312010-01-23 23:23:01 +00001031void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001032 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001033 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001034 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001035 unsigned &Index,
1036 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001037 unsigned &StructuredIndex,
1038 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001039 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1040 // Explicitly braced initializer for complex type can be real+imaginary
1041 // parts.
1042 CheckComplexType(Entity, IList, DeclType, Index,
1043 StructuredList, StructuredIndex);
1044 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001045 CheckScalarType(Entity, IList, DeclType, Index,
1046 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001047 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001049 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001050 } else if (DeclType->isRecordType()) {
1051 assert(DeclType->isAggregateType() &&
1052 "non-aggregate records should be handed in CheckSubElementType");
1053 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001054 auto Bases =
1055 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1056 CXXRecordDecl::base_class_iterator());
1057 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1058 Bases = CXXRD->bases();
1059 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1060 SubobjectIsDesignatorContext, Index, StructuredList,
1061 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001062 } else if (DeclType->isArrayType()) {
1063 llvm::APSInt Zero(
1064 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1065 false);
1066 CheckArrayType(Entity, IList, DeclType, Zero,
1067 SubobjectIsDesignatorContext, Index,
1068 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001069 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1070 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001071 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001072 if (!VerifyOnly)
1073 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1074 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001075 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001076 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001077 CheckReferenceType(Entity, IList, DeclType, Index,
1078 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001079 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001080 if (!VerifyOnly)
1081 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1082 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001083 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001084 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001085 if (!VerifyOnly)
1086 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1087 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001088 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001089 }
1090}
1091
Anders Carlsson6cabf312010-01-23 23:23:01 +00001092void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001093 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001094 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001095 unsigned &Index,
1096 InitListExpr *StructuredList,
1097 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001098 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001099
1100 if (ElemType->isReferenceType())
1101 return CheckReferenceType(Entity, IList, ElemType, Index,
1102 StructuredList, StructuredIndex);
1103
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001104 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001105 if (SubInitList->getNumInits() == 1 &&
1106 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1107 SIF_None) {
1108 expr = SubInitList->getInit(0);
1109 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001110 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001111 = getStructuredSubobjectInit(IList, Index, ElemType,
1112 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001113 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001114 CheckExplicitInitList(Entity, SubInitList, ElemType,
1115 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001116
1117 if (!hadError && !VerifyOnly) {
1118 bool RequiresSecondPass = false;
1119 FillInEmptyInitializations(Entity, InnerStructuredList,
1120 RequiresSecondPass);
1121 if (RequiresSecondPass && !hadError)
1122 FillInEmptyInitializations(Entity, InnerStructuredList,
1123 RequiresSecondPass);
1124 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001125 ++StructuredIndex;
1126 ++Index;
1127 return;
1128 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001129 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001130 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001131 // This happens during template instantiation when we see an InitListExpr
1132 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001133 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001134 "found implicit initialization for the wrong type");
1135 if (!VerifyOnly)
1136 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1137 ++Index;
1138 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001139 }
1140
Richard Smith3c567fc2015-02-12 01:55:09 +00001141 if (SemaRef.getLangOpts().CPlusPlus) {
1142 // C++ [dcl.init.aggr]p2:
1143 // Each member is copy-initialized from the corresponding
1144 // initializer-clause.
1145
1146 // FIXME: Better EqualLoc?
1147 InitializationKind Kind =
1148 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1149 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1150 /*TopLevelOfInitList*/ true);
1151
1152 // C++14 [dcl.init.aggr]p13:
1153 // If the assignment-expression can initialize a member, the member is
1154 // initialized. Otherwise [...] brace elision is assumed
1155 //
1156 // Brace elision is never performed if the element is not an
1157 // assignment-expression.
1158 if (Seq || isa<InitListExpr>(expr)) {
1159 if (!VerifyOnly) {
1160 ExprResult Result =
1161 Seq.Perform(SemaRef, Entity, Kind, expr);
1162 if (Result.isInvalid())
1163 hadError = true;
1164
1165 UpdateStructuredListElement(StructuredList, StructuredIndex,
1166 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001167 } else if (!Seq)
1168 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001169 ++Index;
1170 return;
1171 }
1172
1173 // Fall through for subaggregate initialization
1174 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1175 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001176 return CheckScalarType(Entity, IList, ElemType, Index,
1177 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001178 } else if (const ArrayType *arrayType =
1179 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001180 // arrayType can be incomplete if we're initializing a flexible
1181 // array member. There's nothing we can do with the completed
1182 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001184 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001185 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001186 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1187 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001188 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001189 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001190 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001191 }
John McCall5decec92011-02-21 07:57:55 +00001192
1193 // Fall through for subaggregate initialization.
1194
John McCall5decec92011-02-21 07:57:55 +00001195 } else {
Richard Smith3c567fc2015-02-12 01:55:09 +00001196 assert((ElemType->isRecordType() || ElemType->isVectorType()) &&
1197 "Unexpected type");
1198
John McCall5decec92011-02-21 07:57:55 +00001199 // C99 6.7.8p13:
1200 //
1201 // The initializer for a structure or union object that has
1202 // automatic storage duration shall be either an initializer
1203 // list as described below, or a single expression that has
1204 // compatible structure or union type. In the latter case, the
1205 // initial value of the object, including unnamed members, is
1206 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001207 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001208 if (SemaRef.CheckSingleAssignmentConstraints(
1209 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001210 if (ExprRes.isInvalid())
1211 hadError = true;
1212 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001213 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001214 if (ExprRes.isInvalid())
1215 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001216 }
1217 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001218 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001219 ++Index;
1220 return;
1221 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001222 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001223 // Fall through for subaggregate initialization
1224 }
1225
1226 // C++ [dcl.init.aggr]p12:
1227 //
1228 // [...] Otherwise, if the member is itself a non-empty
1229 // subaggregate, brace elision is assumed and the initializer is
1230 // considered for the initialization of the first member of
1231 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001232 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001233 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001234 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1235 StructuredIndex);
1236 ++StructuredIndex;
1237 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001238 if (!VerifyOnly) {
1239 // We cannot initialize this element, so let
1240 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001241 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001242 /*TopLevelOfInitList=*/true);
1243 }
John McCall5decec92011-02-21 07:57:55 +00001244 hadError = true;
1245 ++Index;
1246 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001247 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001248}
1249
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001250void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1251 InitListExpr *IList, QualType DeclType,
1252 unsigned &Index,
1253 InitListExpr *StructuredList,
1254 unsigned &StructuredIndex) {
1255 assert(Index == 0 && "Index in explicit init list must be zero");
1256
1257 // As an extension, clang supports complex initializers, which initialize
1258 // a complex number component-wise. When an explicit initializer list for
1259 // a complex number contains two two initializers, this extension kicks in:
1260 // it exepcts the initializer list to contain two elements convertible to
1261 // the element type of the complex type. The first element initializes
1262 // the real part, and the second element intitializes the imaginary part.
1263
1264 if (IList->getNumInits() != 2)
1265 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1266 StructuredIndex);
1267
1268 // This is an extension in C. (The builtin _Complex type does not exist
1269 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001270 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001271 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1272 << IList->getSourceRange();
1273
1274 // Initialize the complex number.
1275 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1276 InitializedEntity ElementEntity =
1277 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1278
1279 for (unsigned i = 0; i < 2; ++i) {
1280 ElementEntity.setElementIndex(Index);
1281 CheckSubElementType(ElementEntity, IList, elementType, Index,
1282 StructuredList, StructuredIndex);
1283 }
1284}
1285
Anders Carlsson6cabf312010-01-23 23:23:01 +00001286void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001287 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001288 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001289 InitListExpr *StructuredList,
1290 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001291 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001292 if (!VerifyOnly)
1293 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001294 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001295 diag::warn_cxx98_compat_empty_scalar_initializer :
1296 diag::err_empty_scalar_initializer)
1297 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001298 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001299 ++Index;
1300 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001301 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001302 }
John McCall643169b2010-11-11 00:46:36 +00001303
1304 Expr *expr = IList->getInit(Index);
1305 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001306 // FIXME: This is invalid, and accepting it causes overload resolution
1307 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001308 if (!VerifyOnly)
1309 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001310 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001311 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001312
1313 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1314 StructuredIndex);
1315 return;
1316 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001317 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001318 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001319 diag::err_designator_for_scalar_init)
1320 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001321 hadError = true;
1322 ++Index;
1323 ++StructuredIndex;
1324 return;
1325 }
1326
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001327 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001328 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001329 hadError = true;
1330 ++Index;
1331 return;
1332 }
1333
John McCall643169b2010-11-11 00:46:36 +00001334 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001335 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001336 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001337
Craig Topperc3ec1492014-05-26 06:22:03 +00001338 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001339
1340 if (Result.isInvalid())
1341 hadError = true; // types weren't compatible.
1342 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001343 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344
John McCall643169b2010-11-11 00:46:36 +00001345 if (ResultExpr != expr) {
1346 // The type was promoted, update initializer list.
1347 IList->setInit(Index, ResultExpr);
1348 }
1349 }
1350 if (hadError)
1351 ++StructuredIndex;
1352 else
1353 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1354 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001355}
1356
Anders Carlsson6cabf312010-01-23 23:23:01 +00001357void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1358 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001359 unsigned &Index,
1360 InitListExpr *StructuredList,
1361 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001362 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001363 // FIXME: It would be wonderful if we could point at the actual member. In
1364 // general, it would be useful to pass location information down the stack,
1365 // so that we know the location (or decl) of the "current object" being
1366 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001367 if (!VerifyOnly)
1368 SemaRef.Diag(IList->getLocStart(),
1369 diag::err_init_reference_member_uninitialized)
1370 << DeclType
1371 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001372 hadError = true;
1373 ++Index;
1374 ++StructuredIndex;
1375 return;
1376 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001377
1378 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001379 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001380 if (!VerifyOnly)
1381 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1382 << DeclType << IList->getSourceRange();
1383 hadError = true;
1384 ++Index;
1385 ++StructuredIndex;
1386 return;
1387 }
1388
1389 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001390 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001391 hadError = true;
1392 ++Index;
1393 return;
1394 }
1395
1396 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001397 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1398 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001399
1400 if (Result.isInvalid())
1401 hadError = true;
1402
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001403 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001404 IList->setInit(Index, expr);
1405
1406 if (hadError)
1407 ++StructuredIndex;
1408 else
1409 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1410 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001411}
1412
Anders Carlsson6cabf312010-01-23 23:23:01 +00001413void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001414 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001415 unsigned &Index,
1416 InitListExpr *StructuredList,
1417 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001418 const VectorType *VT = DeclType->getAs<VectorType>();
1419 unsigned maxElements = VT->getNumElements();
1420 unsigned numEltsInit = 0;
1421 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001422
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001423 if (Index >= IList->getNumInits()) {
1424 // Make sure the element type can be value-initialized.
1425 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001426 CheckEmptyInitializable(
1427 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1428 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001429 return;
1430 }
1431
David Blaikiebbafb8a2012-03-11 07:00:24 +00001432 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001433 // If the initializing element is a vector, try to copy-initialize
1434 // instead of breaking it apart (which is doomed to failure anyway).
1435 Expr *Init = IList->getInit(Index);
1436 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001437 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001438 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001439 hadError = true;
1440 ++Index;
1441 return;
1442 }
1443
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001444 ExprResult Result =
1445 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1446 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001447
Craig Topperc3ec1492014-05-26 06:22:03 +00001448 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001449 if (Result.isInvalid())
1450 hadError = true; // types weren't compatible.
1451 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001452 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001453
John McCall6a16b2f2010-10-30 00:11:39 +00001454 if (ResultExpr != Init) {
1455 // The type was promoted, update initializer list.
1456 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001457 }
1458 }
John McCall6a16b2f2010-10-30 00:11:39 +00001459 if (hadError)
1460 ++StructuredIndex;
1461 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001462 UpdateStructuredListElement(StructuredList, StructuredIndex,
1463 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001464 ++Index;
1465 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001466 }
Mike Stump11289f42009-09-09 15:08:12 +00001467
John McCall6a16b2f2010-10-30 00:11:39 +00001468 InitializedEntity ElementEntity =
1469 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470
John McCall6a16b2f2010-10-30 00:11:39 +00001471 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1472 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001473 if (Index >= IList->getNumInits()) {
1474 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001475 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001476 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001477 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478
John McCall6a16b2f2010-10-30 00:11:39 +00001479 ElementEntity.setElementIndex(Index);
1480 CheckSubElementType(ElementEntity, IList, elementType, Index,
1481 StructuredList, StructuredIndex);
1482 }
James Molloy9eef2652014-06-20 14:35:13 +00001483
1484 if (VerifyOnly)
1485 return;
1486
1487 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1488 const VectorType *T = Entity.getType()->getAs<VectorType>();
1489 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1490 T->getVectorKind() == VectorType::NeonPolyVector)) {
1491 // The ability to use vector initializer lists is a GNU vector extension
1492 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1493 // endian machines it works fine, however on big endian machines it
1494 // exhibits surprising behaviour:
1495 //
1496 // uint32x2_t x = {42, 64};
1497 // return vget_lane_u32(x, 0); // Will return 64.
1498 //
1499 // Because of this, explicitly call out that it is non-portable.
1500 //
1501 SemaRef.Diag(IList->getLocStart(),
1502 diag::warn_neon_vector_initializer_non_portable);
1503
1504 const char *typeCode;
1505 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1506
1507 if (elementType->isFloatingType())
1508 typeCode = "f";
1509 else if (elementType->isSignedIntegerType())
1510 typeCode = "s";
1511 else if (elementType->isUnsignedIntegerType())
1512 typeCode = "u";
1513 else
1514 llvm_unreachable("Invalid element type!");
1515
1516 SemaRef.Diag(IList->getLocStart(),
1517 SemaRef.Context.getTypeSize(VT) > 64 ?
1518 diag::note_neon_vector_initializer_non_portable_q :
1519 diag::note_neon_vector_initializer_non_portable)
1520 << typeCode << typeSize;
1521 }
1522
John McCall6a16b2f2010-10-30 00:11:39 +00001523 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001524 }
John McCall6a16b2f2010-10-30 00:11:39 +00001525
1526 InitializedEntity ElementEntity =
1527 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001528
John McCall6a16b2f2010-10-30 00:11:39 +00001529 // OpenCL initializers allows vectors to be constructed from vectors.
1530 for (unsigned i = 0; i < maxElements; ++i) {
1531 // Don't attempt to go past the end of the init list
1532 if (Index >= IList->getNumInits())
1533 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534
John McCall6a16b2f2010-10-30 00:11:39 +00001535 ElementEntity.setElementIndex(Index);
1536
1537 QualType IType = IList->getInit(Index)->getType();
1538 if (!IType->isVectorType()) {
1539 CheckSubElementType(ElementEntity, IList, elementType, Index,
1540 StructuredList, StructuredIndex);
1541 ++numEltsInit;
1542 } else {
1543 QualType VecType;
1544 const VectorType *IVT = IType->getAs<VectorType>();
1545 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001546
John McCall6a16b2f2010-10-30 00:11:39 +00001547 if (IType->isExtVectorType())
1548 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1549 else
1550 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001551 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001552 CheckSubElementType(ElementEntity, IList, VecType, Index,
1553 StructuredList, StructuredIndex);
1554 numEltsInit += numIElts;
1555 }
1556 }
1557
1558 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001559 if (numEltsInit != maxElements) {
1560 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001561 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001562 diag::err_vector_incorrect_num_initializers)
1563 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1564 hadError = true;
1565 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001566}
1567
Anders Carlsson6cabf312010-01-23 23:23:01 +00001568void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001569 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001570 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001571 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001572 unsigned &Index,
1573 InitListExpr *StructuredList,
1574 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001575 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1576
Steve Narofff8ecff22008-05-01 22:18:59 +00001577 // Check for the special-case of initializing an array with a string.
1578 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001579 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1580 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001581 // We place the string literal directly into the resulting
1582 // initializer list. This is the only place where the structure
1583 // of the structured initializer list doesn't match exactly,
1584 // because doing so would involve allocating one character
1585 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001586 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001587 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1588 UpdateStructuredListElement(StructuredList, StructuredIndex,
1589 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001590 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1591 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001592 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001593 return;
1594 }
1595 }
John McCall66884dd2011-02-21 07:22:22 +00001596 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001597 // Check for VLAs; in standard C it would be possible to check this
1598 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1599 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001600 if (!VerifyOnly)
1601 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1602 diag::err_variable_object_no_init)
1603 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001604 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001605 ++Index;
1606 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001607 return;
1608 }
1609
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001610 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001611 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1612 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001613 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001614 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001615 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001616 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001617 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001618 maxElementsKnown = true;
1619 }
1620
John McCall66884dd2011-02-21 07:22:22 +00001621 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001622 while (Index < IList->getNumInits()) {
1623 Expr *Init = IList->getInit(Index);
1624 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001625 // If we're not the subobject that matches up with the '{' for
1626 // the designator, we shouldn't be handling the
1627 // designator. Return immediately.
1628 if (!SubobjectIsDesignatorContext)
1629 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001630
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001631 // Handle this designated initializer. elementIndex will be
1632 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001633 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001634 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001635 StructuredList, StructuredIndex, true,
1636 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001637 hadError = true;
1638 continue;
1639 }
1640
Douglas Gregor033d1252009-01-23 16:54:12 +00001641 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001642 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001643 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001644 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001645 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001646
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001647 // If the array is of incomplete type, keep track of the number of
1648 // elements in the initializer.
1649 if (!maxElementsKnown && elementIndex > maxElements)
1650 maxElements = elementIndex;
1651
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001652 continue;
1653 }
1654
1655 // If we know the maximum number of elements, and we've already
1656 // hit it, stop consuming elements in the initializer list.
1657 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001658 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001659
Anders Carlsson6cabf312010-01-23 23:23:01 +00001660 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001661 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001662 Entity);
1663 // Check this element.
1664 CheckSubElementType(ElementEntity, IList, elementType, Index,
1665 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001666 ++elementIndex;
1667
1668 // If the array is of incomplete type, keep track of the number of
1669 // elements in the initializer.
1670 if (!maxElementsKnown && elementIndex > maxElements)
1671 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001672 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001673 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001674 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001675 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001676 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001677 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001678 // Sizing an array implicitly to zero is not allowed by ISO C,
1679 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001680 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001681 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001682 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001683
Mike Stump11289f42009-09-09 15:08:12 +00001684 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001685 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001686 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001687 if (!hadError && VerifyOnly) {
1688 // Check if there are any members of the array that get value-initialized.
1689 // If so, check if doing that is possible.
1690 // FIXME: This needs to detect holes left by designated initializers too.
1691 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001692 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1693 SemaRef.Context, 0, Entity),
1694 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001695 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001696}
1697
Eli Friedman3fa64df2011-08-23 22:24:57 +00001698bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1699 Expr *InitExpr,
1700 FieldDecl *Field,
1701 bool TopLevelObject) {
1702 // Handle GNU flexible array initializers.
1703 unsigned FlexArrayDiag;
1704 if (isa<InitListExpr>(InitExpr) &&
1705 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1706 // Empty flexible array init always allowed as an extension
1707 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001708 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001709 // Disallow flexible array init in C++; it is not required for gcc
1710 // compatibility, and it needs work to IRGen correctly in general.
1711 FlexArrayDiag = diag::err_flexible_array_init;
1712 } else if (!TopLevelObject) {
1713 // Disallow flexible array init on non-top-level object
1714 FlexArrayDiag = diag::err_flexible_array_init;
1715 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1716 // Disallow flexible array init on anything which is not a variable.
1717 FlexArrayDiag = diag::err_flexible_array_init;
1718 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1719 // Disallow flexible array init on local variables.
1720 FlexArrayDiag = diag::err_flexible_array_init;
1721 } else {
1722 // Allow other cases.
1723 FlexArrayDiag = diag::ext_flexible_array_init;
1724 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001725
1726 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001727 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001728 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001729 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001730 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1731 << Field;
1732 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001733
1734 return FlexArrayDiag != diag::ext_flexible_array_init;
1735}
1736
Richard Smith872307e2016-03-08 22:17:41 +00001737void InitListChecker::CheckStructUnionTypes(
1738 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1739 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1740 bool SubobjectIsDesignatorContext, unsigned &Index,
1741 InitListExpr *StructuredList, unsigned &StructuredIndex,
1742 bool TopLevelObject) {
1743 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001744
Eli Friedman23a9e312008-05-19 19:16:24 +00001745 // If the record is invalid, some of it's members are invalid. To avoid
1746 // confusion, we forgo checking the intializer for the entire record.
1747 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001748 // Assume it was supposed to consume a single initializer.
1749 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001750 hadError = true;
1751 return;
Mike Stump11289f42009-09-09 15:08:12 +00001752 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001753
1754 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001755 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001756
1757 // If there's a default initializer, use it.
1758 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1759 if (VerifyOnly)
1760 return;
1761 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1762 Field != FieldEnd; ++Field) {
1763 if (Field->hasInClassInitializer()) {
1764 StructuredList->setInitializedFieldInUnion(*Field);
1765 // FIXME: Actually build a CXXDefaultInitExpr?
1766 return;
1767 }
1768 }
1769 }
1770
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001771 // Value-initialize the first member of the union that isn't an unnamed
1772 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001773 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1774 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001775 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001776 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001777 CheckEmptyInitializable(
1778 InitializedEntity::InitializeMember(*Field, &Entity),
1779 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001780 else
David Blaikie40ed2972012-06-06 20:45:41 +00001781 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001782 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001783 }
1784 }
1785 return;
1786 }
1787
Richard Smith872307e2016-03-08 22:17:41 +00001788 bool InitializedSomething = false;
1789
1790 // If we have any base classes, they are initialized prior to the fields.
1791 for (auto &Base : Bases) {
1792 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1793 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1794
1795 // Designated inits always initialize fields, so if we see one, all
1796 // remaining base classes have no explicit initializer.
1797 if (Init && isa<DesignatedInitExpr>(Init))
1798 Init = nullptr;
1799
1800 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1801 SemaRef.Context, &Base, false, &Entity);
1802 if (Init) {
1803 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1804 StructuredList, StructuredIndex);
1805 InitializedSomething = true;
1806 } else if (VerifyOnly) {
1807 CheckEmptyInitializable(BaseEntity, InitLoc);
1808 }
1809 }
1810
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001811 // If structDecl is a forward declaration, this loop won't do
1812 // anything except look at designated initializers; That's okay,
1813 // because an error should get printed out elsewhere. It might be
1814 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001815 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001816 RecordDecl::field_iterator FieldEnd = RD->field_end();
John McCalle40b58e2010-03-11 19:32:38 +00001817 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001818 while (Index < IList->getNumInits()) {
1819 Expr *Init = IList->getInit(Index);
1820
1821 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001822 // If we're not the subobject that matches up with the '{' for
1823 // the designator, we shouldn't be handling the
1824 // designator. Return immediately.
1825 if (!SubobjectIsDesignatorContext)
1826 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001827
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001828 // Handle this designated initializer. Field will be updated to
1829 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001830 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001831 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001832 StructuredList, StructuredIndex,
1833 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001834 hadError = true;
1835
Douglas Gregora9add4e2009-02-12 19:00:39 +00001836 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001837
1838 // Disable check for missing fields when designators are used.
1839 // This matches gcc behaviour.
1840 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001841 continue;
1842 }
1843
1844 if (Field == FieldEnd) {
1845 // We've run out of fields. We're done.
1846 break;
1847 }
1848
Douglas Gregora9add4e2009-02-12 19:00:39 +00001849 // We've already initialized a member of a union. We're done.
1850 if (InitializedSomething && DeclType->isUnionType())
1851 break;
1852
Douglas Gregor91f84212008-12-11 16:49:14 +00001853 // If we've hit the flexible array member at the end, we're done.
1854 if (Field->getType()->isIncompleteArrayType())
1855 break;
1856
Douglas Gregor51695702009-01-29 16:53:55 +00001857 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001858 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001859 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001860 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001861 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001862
Douglas Gregora82064c2011-06-29 21:51:31 +00001863 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001864 bool InvalidUse;
1865 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00001866 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001867 else
David Blaikie40ed2972012-06-06 20:45:41 +00001868 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001869 IList->getInit(Index)->getLocStart());
1870 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001871 ++Index;
1872 ++Field;
1873 hadError = true;
1874 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001875 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001876
Anders Carlsson6cabf312010-01-23 23:23:01 +00001877 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001878 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001879 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1880 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001881 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001882
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001883 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001884 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001885 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001886 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001887
1888 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001889 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001890
John McCalle40b58e2010-03-11 19:32:38 +00001891 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001892 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1893 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1894 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001895 // It is possible we have one or more unnamed bitfields remaining.
1896 // Find first (if any) named field and emit warning.
1897 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1898 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001899 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001900 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001901 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001902 break;
1903 }
1904 }
1905 }
1906
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001907 // Check that any remaining fields can be value-initialized.
1908 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1909 !Field->getType()->isIncompleteArrayType()) {
1910 // FIXME: Should check for holes left by designated initializers too.
1911 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001912 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001913 CheckEmptyInitializable(
1914 InitializedEntity::InitializeMember(*Field, &Entity),
1915 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001916 }
1917 }
1918
Mike Stump11289f42009-09-09 15:08:12 +00001919 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001920 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001921 return;
1922
David Blaikie40ed2972012-06-06 20:45:41 +00001923 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001924 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001925 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001926 ++Index;
1927 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001928 }
1929
Anders Carlsson6cabf312010-01-23 23:23:01 +00001930 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001931 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Anders Carlsson6cabf312010-01-23 23:23:01 +00001933 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001934 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001935 StructuredList, StructuredIndex);
1936 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001938 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001939}
Steve Narofff8ecff22008-05-01 22:18:59 +00001940
Douglas Gregord5846a12009-04-15 06:41:24 +00001941/// \brief Expand a field designator that refers to a member of an
1942/// anonymous struct or union into a series of field designators that
1943/// refers to the field within the appropriate subobject.
1944///
Douglas Gregord5846a12009-04-15 06:41:24 +00001945static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001946 DesignatedInitExpr *DIE,
1947 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001948 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001949 typedef DesignatedInitExpr::Designator Designator;
1950
Douglas Gregord5846a12009-04-15 06:41:24 +00001951 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001952 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001953 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1954 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1955 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001956 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001957 DIE->getDesignator(DesigIdx)->getDotLoc(),
1958 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1959 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001960 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1961 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001962 assert(isa<FieldDecl>(*PI));
1963 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001964 }
1965
1966 // Expand the current designator into the set of replacement
1967 // designators, so we have a full subobject path down to where the
1968 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001969 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001970 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001971}
Mike Stump11289f42009-09-09 15:08:12 +00001972
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001973static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1974 DesignatedInitExpr *DIE) {
1975 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1976 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1977 for (unsigned I = 0; I < NumIndexExprs; ++I)
1978 IndexExprs[I] = DIE->getSubExpr(I + 1);
1979 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001980 DIE->size(), IndexExprs,
1981 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001982 DIE->usesGNUSyntax(), DIE->getInit());
1983}
1984
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001985namespace {
1986
1987// Callback to only accept typo corrections that are for field members of
1988// the given struct or union.
1989class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1990 public:
1991 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1992 : Record(RD) {}
1993
Craig Toppere14c0f82014-03-12 04:55:44 +00001994 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001995 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1996 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1997 }
1998
1999 private:
2000 RecordDecl *Record;
2001};
2002
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002003} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002004
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002005/// @brief Check the well-formedness of a C99 designated initializer.
2006///
2007/// Determines whether the designated initializer @p DIE, which
2008/// resides at the given @p Index within the initializer list @p
2009/// IList, is well-formed for a current object of type @p DeclType
2010/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002011/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002012/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002013///
2014/// @param IList The initializer list in which this designated
2015/// initializer occurs.
2016///
Douglas Gregora5324162009-04-15 04:56:10 +00002017/// @param DIE The designated initializer expression.
2018///
2019/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002020///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002021/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002022/// into which the designation in @p DIE should refer.
2023///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002024/// @param NextField If non-NULL and the first designator in @p DIE is
2025/// a field, this will be set to the field declaration corresponding
2026/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002027///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002028/// @param NextElementIndex If non-NULL and the first designator in @p
2029/// DIE is an array designator or GNU array-range designator, this
2030/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002031///
2032/// @param Index Index into @p IList where the designated initializer
2033/// @p DIE occurs.
2034///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002035/// @param StructuredList The initializer list expression that
2036/// describes all of the subobject initializers in the order they'll
2037/// actually be initialized.
2038///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002039/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002040bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002041InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002042 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002043 DesignatedInitExpr *DIE,
2044 unsigned DesigIdx,
2045 QualType &CurrentObjectType,
2046 RecordDecl::field_iterator *NextField,
2047 llvm::APSInt *NextElementIndex,
2048 unsigned &Index,
2049 InitListExpr *StructuredList,
2050 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002051 bool FinishSubobjectInit,
2052 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002053 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002054 // Check the actual initialization for the designated object type.
2055 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002056
2057 // Temporarily remove the designator expression from the
2058 // initializer list that the child calls see, so that we don't try
2059 // to re-process the designator.
2060 unsigned OldIndex = Index;
2061 IList->setInit(OldIndex, DIE->getInit());
2062
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002063 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002064 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002065
2066 // Restore the designated initializer expression in the syntactic
2067 // form of the initializer list.
2068 if (IList->getInit(OldIndex) != DIE->getInit())
2069 DIE->setInit(IList->getInit(OldIndex));
2070 IList->setInit(OldIndex, DIE);
2071
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002072 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002073 }
2074
Douglas Gregora5324162009-04-15 04:56:10 +00002075 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002076 bool IsFirstDesignator = (DesigIdx == 0);
2077 if (!VerifyOnly) {
2078 assert((IsFirstDesignator || StructuredList) &&
2079 "Need a non-designated initializer list to start from");
2080
2081 // Determine the structural initializer list that corresponds to the
2082 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002083 if (IsFirstDesignator)
2084 StructuredList = SyntacticToSemantic.lookup(IList);
2085 else {
2086 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2087 StructuredList->getInit(StructuredIndex) : nullptr;
2088 if (!ExistingInit && StructuredList->hasArrayFiller())
2089 ExistingInit = StructuredList->getArrayFiller();
2090
2091 if (!ExistingInit)
2092 StructuredList =
2093 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2094 StructuredList, StructuredIndex,
2095 SourceRange(D->getLocStart(),
2096 DIE->getLocEnd()));
2097 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2098 StructuredList = Result;
2099 else {
2100 if (DesignatedInitUpdateExpr *E =
2101 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2102 StructuredList = E->getUpdater();
2103 else {
2104 DesignatedInitUpdateExpr *DIUE =
2105 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2106 D->getLocStart(), ExistingInit,
2107 DIE->getLocEnd());
2108 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2109 StructuredList = DIUE->getUpdater();
2110 }
2111
2112 // We need to check on source range validity because the previous
2113 // initializer does not have to be an explicit initializer. e.g.,
2114 //
2115 // struct P { int a, b; };
2116 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2117 //
2118 // There is an overwrite taking place because the first braced initializer
2119 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2120 if (ExistingInit->getSourceRange().isValid()) {
2121 // We are creating an initializer list that initializes the
2122 // subobjects of the current object, but there was already an
2123 // initialization that completely initialized the current
2124 // subobject, e.g., by a compound literal:
2125 //
2126 // struct X { int a, b; };
2127 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2128 //
2129 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2130 // designated initializer re-initializes the whole
2131 // subobject [0], overwriting previous initializers.
2132 SemaRef.Diag(D->getLocStart(),
2133 diag::warn_subobject_initializer_overrides)
2134 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2135
2136 SemaRef.Diag(ExistingInit->getLocStart(),
2137 diag::note_previous_initializer)
2138 << /*FIXME:has side effects=*/0
2139 << ExistingInit->getSourceRange();
2140 }
2141 }
2142 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002143 assert(StructuredList && "Expected a structured initializer list");
2144 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002145
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002146 if (D->isFieldDesignator()) {
2147 // C99 6.7.8p7:
2148 //
2149 // If a designator has the form
2150 //
2151 // . identifier
2152 //
2153 // then the current object (defined below) shall have
2154 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002155 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002156 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002157 if (!RT) {
2158 SourceLocation Loc = D->getDotLoc();
2159 if (Loc.isInvalid())
2160 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002161 if (!VerifyOnly)
2162 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002163 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002164 ++Index;
2165 return true;
2166 }
2167
Douglas Gregord5846a12009-04-15 06:41:24 +00002168 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002169 if (!KnownField) {
2170 IdentifierInfo *FieldName = D->getFieldName();
2171 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2172 for (NamedDecl *ND : Lookup) {
2173 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2174 KnownField = FD;
2175 break;
2176 }
2177 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002178 // In verify mode, don't modify the original.
2179 if (VerifyOnly)
2180 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002181 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002182 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002183 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002184 break;
2185 }
2186 }
David Majnemer36ef8982014-08-11 18:33:59 +00002187 if (!KnownField) {
2188 if (VerifyOnly) {
2189 ++Index;
2190 return true; // No typo correction when just trying this out.
2191 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002192
David Majnemer36ef8982014-08-11 18:33:59 +00002193 // Name lookup found something, but it wasn't a field.
2194 if (!Lookup.empty()) {
2195 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2196 << FieldName;
2197 SemaRef.Diag(Lookup.front()->getLocation(),
2198 diag::note_field_designator_found);
2199 ++Index;
2200 return true;
2201 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002202
David Majnemer36ef8982014-08-11 18:33:59 +00002203 // Name lookup didn't find anything.
2204 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002205 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2206 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002207 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002208 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2209 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002210 SemaRef.diagnoseTypo(
2211 Corrected,
2212 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002213 << FieldName << CurrentObjectType);
2214 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002215 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002216 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002217 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002218 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2219 << FieldName << CurrentObjectType;
2220 ++Index;
2221 return true;
2222 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002223 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002224 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002225
David Majnemer58e4ea92014-08-23 01:48:50 +00002226 unsigned FieldIndex = 0;
2227 for (auto *FI : RT->getDecl()->fields()) {
2228 if (FI->isUnnamedBitfield())
2229 continue;
2230 if (KnownField == FI)
2231 break;
2232 ++FieldIndex;
2233 }
2234
David Majnemer36ef8982014-08-11 18:33:59 +00002235 RecordDecl::field_iterator Field =
2236 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2237
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002238 // All of the fields of a union are located at the same place in
2239 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002240 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002241 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002242 if (!VerifyOnly) {
2243 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2244 if (CurrentField && CurrentField != *Field) {
2245 assert(StructuredList->getNumInits() == 1
2246 && "A union should never have more than one initializer!");
2247
2248 // we're about to throw away an initializer, emit warning
2249 SemaRef.Diag(D->getFieldLoc(),
2250 diag::warn_initializer_overrides)
2251 << D->getSourceRange();
2252 Expr *ExistingInit = StructuredList->getInit(0);
2253 SemaRef.Diag(ExistingInit->getLocStart(),
2254 diag::note_previous_initializer)
2255 << /*FIXME:has side effects=*/0
2256 << ExistingInit->getSourceRange();
2257
2258 // remove existing initializer
2259 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002260 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002261 }
2262
David Blaikie40ed2972012-06-06 20:45:41 +00002263 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002264 }
Douglas Gregor51695702009-01-29 16:53:55 +00002265 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002266
Douglas Gregora82064c2011-06-29 21:51:31 +00002267 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002268 bool InvalidUse;
2269 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002270 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002271 else
David Blaikie40ed2972012-06-06 20:45:41 +00002272 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002273 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002274 ++Index;
2275 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002276 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002277
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002278 if (!VerifyOnly) {
2279 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002280 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002281
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002282 // Make sure that our non-designated initializer list has space
2283 // for a subobject corresponding to this field.
2284 if (FieldIndex >= StructuredList->getNumInits())
2285 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2286 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002287
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002288 // This designator names a flexible array member.
2289 if (Field->getType()->isIncompleteArrayType()) {
2290 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002291 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002292 // We can't designate an object within the flexible array
2293 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002294 if (!VerifyOnly) {
2295 DesignatedInitExpr::Designator *NextD
2296 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002297 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002298 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002299 << SourceRange(NextD->getLocStart(),
2300 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002301 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002302 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002303 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002304 Invalid = true;
2305 }
2306
Chris Lattner001b29c2010-10-10 17:49:49 +00002307 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2308 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002309 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002310 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002311 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002312 diag::err_flexible_array_init_needs_braces)
2313 << DIE->getInit()->getSourceRange();
2314 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002315 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002316 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002317 Invalid = true;
2318 }
2319
Eli Friedman3fa64df2011-08-23 22:24:57 +00002320 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002321 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002322 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002323 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002324
2325 if (Invalid) {
2326 ++Index;
2327 return true;
2328 }
2329
2330 // Initialize the array.
2331 bool prevHadError = hadError;
2332 unsigned newStructuredIndex = FieldIndex;
2333 unsigned OldIndex = Index;
2334 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002335
2336 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002337 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002338 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002339 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002340
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002341 IList->setInit(OldIndex, DIE);
2342 if (hadError && !prevHadError) {
2343 ++Field;
2344 ++FieldIndex;
2345 if (NextField)
2346 *NextField = Field;
2347 StructuredIndex = FieldIndex;
2348 return true;
2349 }
2350 } else {
2351 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002352 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002353 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002354
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002355 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002356 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002357 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002358 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002359 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002360 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002361 return true;
2362 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002363
2364 // Find the position of the next field to be initialized in this
2365 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002366 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002367 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002368
2369 // If this the first designator, our caller will continue checking
2370 // the rest of this struct/class/union subobject.
2371 if (IsFirstDesignator) {
2372 if (NextField)
2373 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002374 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002375 return false;
2376 }
2377
Douglas Gregor17bd0942009-01-28 23:36:17 +00002378 if (!FinishSubobjectInit)
2379 return false;
2380
Douglas Gregord5846a12009-04-15 06:41:24 +00002381 // We've already initialized something in the union; we're done.
2382 if (RT->getDecl()->isUnion())
2383 return hadError;
2384
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002385 // Check the remaining fields within this class/struct/union subobject.
2386 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387
Richard Smith872307e2016-03-08 22:17:41 +00002388 auto NoBases =
2389 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2390 CXXRecordDecl::base_class_iterator());
2391 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2392 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002393 return hadError && !prevHadError;
2394 }
2395
2396 // C99 6.7.8p6:
2397 //
2398 // If a designator has the form
2399 //
2400 // [ constant-expression ]
2401 //
2402 // then the current object (defined below) shall have array
2403 // type and the expression shall be an integer constant
2404 // expression. If the array is of unknown size, any
2405 // nonnegative value is valid.
2406 //
2407 // Additionally, cope with the GNU extension that permits
2408 // designators of the form
2409 //
2410 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002411 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002412 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002413 if (!VerifyOnly)
2414 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2415 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002416 ++Index;
2417 return true;
2418 }
2419
Craig Topperc3ec1492014-05-26 06:22:03 +00002420 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002421 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2422 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002423 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002424 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002425 DesignatedEndIndex = DesignatedStartIndex;
2426 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002427 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002428
Mike Stump11289f42009-09-09 15:08:12 +00002429 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002430 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002431 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002432 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002433 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002434
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002435 // Codegen can't handle evaluating array range designators that have side
2436 // effects, because we replicate the AST value for each initialized element.
2437 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2438 // elements with something that has a side effect, so codegen can emit an
2439 // "error unsupported" error instead of miscompiling the app.
2440 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002441 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002442 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002443 }
2444
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002445 if (isa<ConstantArrayType>(AT)) {
2446 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002447 DesignatedStartIndex
2448 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002449 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002450 DesignatedEndIndex
2451 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002452 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2453 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002454 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002455 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002456 diag::err_array_designator_too_large)
2457 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2458 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002459 ++Index;
2460 return true;
2461 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002462 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002463 unsigned DesignatedIndexBitWidth =
2464 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2465 DesignatedStartIndex =
2466 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2467 DesignatedEndIndex =
2468 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002469 DesignatedStartIndex.setIsUnsigned(true);
2470 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002471 }
Mike Stump11289f42009-09-09 15:08:12 +00002472
Eli Friedman1f16b742013-06-11 21:48:11 +00002473 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2474 // We're modifying a string literal init; we have to decompose the string
2475 // so we can modify the individual characters.
2476 ASTContext &Context = SemaRef.Context;
2477 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2478
2479 // Compute the character type
2480 QualType CharTy = AT->getElementType();
2481
2482 // Compute the type of the integer literals.
2483 QualType PromotedCharTy = CharTy;
2484 if (CharTy->isPromotableIntegerType())
2485 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2486 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2487
2488 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2489 // Get the length of the string.
2490 uint64_t StrLen = SL->getLength();
2491 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2492 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2493 StructuredList->resizeInits(Context, StrLen);
2494
2495 // Build a literal for each character in the string, and put them into
2496 // the init list.
2497 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2498 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2499 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002500 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002501 if (CharTy != PromotedCharTy)
2502 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002503 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002504 StructuredList->updateInit(Context, i, Init);
2505 }
2506 } else {
2507 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2508 std::string Str;
2509 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2510
2511 // Get the length of the string.
2512 uint64_t StrLen = Str.size();
2513 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2514 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2515 StructuredList->resizeInits(Context, StrLen);
2516
2517 // Build a literal for each character in the string, and put them into
2518 // the init list.
2519 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2520 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2521 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002522 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002523 if (CharTy != PromotedCharTy)
2524 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002525 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002526 StructuredList->updateInit(Context, i, Init);
2527 }
2528 }
2529 }
2530
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002531 // Make sure that our non-designated initializer list has space
2532 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002533 if (!VerifyOnly &&
2534 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002535 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002536 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002537
Douglas Gregor17bd0942009-01-28 23:36:17 +00002538 // Repeatedly perform subobject initializations in the range
2539 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002540
Douglas Gregor17bd0942009-01-28 23:36:17 +00002541 // Move to the next designator
2542 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2543 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002545 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002546 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002547
Douglas Gregor17bd0942009-01-28 23:36:17 +00002548 while (DesignatedStartIndex <= DesignatedEndIndex) {
2549 // Recurse to check later designated subobjects.
2550 QualType ElementType = AT->getElementType();
2551 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002553 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002554 if (CheckDesignatedInitializer(
2555 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2556 nullptr, Index, StructuredList, ElementIndex,
2557 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2558 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002559 return true;
2560
2561 // Move to the next index in the array that we'll be initializing.
2562 ++DesignatedStartIndex;
2563 ElementIndex = DesignatedStartIndex.getZExtValue();
2564 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002565
2566 // If this the first designator, our caller will continue checking
2567 // the rest of this array subobject.
2568 if (IsFirstDesignator) {
2569 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002570 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002571 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002572 return false;
2573 }
Mike Stump11289f42009-09-09 15:08:12 +00002574
Douglas Gregor17bd0942009-01-28 23:36:17 +00002575 if (!FinishSubobjectInit)
2576 return false;
2577
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002578 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002579 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002581 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002582 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002583 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002584}
2585
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002586// Get the structured initializer list for a subobject of type
2587// @p CurrentObjectType.
2588InitListExpr *
2589InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2590 QualType CurrentObjectType,
2591 InitListExpr *StructuredList,
2592 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002593 SourceRange InitRange,
2594 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002595 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002596 return nullptr; // No structured list in verification-only mode.
2597 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002598 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002599 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002600 else if (StructuredIndex < StructuredList->getNumInits())
2601 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002602
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002603 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002604 // There might have already been initializers for subobjects of the current
2605 // object, but a subsequent initializer list will overwrite the entirety
2606 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2607 //
2608 // struct P { char x[6]; };
2609 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2610 //
2611 // The first designated initializer is ignored, and l.x is just "f".
2612 if (!IsFullyOverwritten)
2613 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002614
2615 if (ExistingInit) {
2616 // We are creating an initializer list that initializes the
2617 // subobjects of the current object, but there was already an
2618 // initialization that completely initialized the current
2619 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002620 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002621 // struct X { int a, b; };
2622 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002623 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002624 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2625 // designated initializer re-initializes the whole
2626 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002627 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002628 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002629 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002630 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002631 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002632 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002633 << ExistingInit->getSourceRange();
2634 }
2635
Mike Stump11289f42009-09-09 15:08:12 +00002636 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002637 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002638 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002639 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002640
Eli Friedman91f5ae52012-02-23 02:25:10 +00002641 QualType ResultType = CurrentObjectType;
2642 if (!ResultType->isArrayType())
2643 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2644 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002645
Douglas Gregor6d00c992009-03-20 23:58:33 +00002646 // Pre-allocate storage for the structured initializer list.
2647 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002648 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002649 bool GotNumInits = false;
2650 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002651 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002652 GotNumInits = true;
2653 } else if (Index < IList->getNumInits()) {
2654 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002655 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002656 GotNumInits = true;
2657 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002658 }
2659
Mike Stump11289f42009-09-09 15:08:12 +00002660 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002661 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2662 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2663 NumElements = CAType->getSize().getZExtValue();
2664 // Simple heuristic so that we don't allocate a very large
2665 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002666 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002667 NumElements = 0;
2668 }
John McCall9dd450b2009-09-21 23:43:11 +00002669 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002670 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002671 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002672 RecordDecl *RDecl = RType->getDecl();
2673 if (RDecl->isUnion())
2674 NumElements = 1;
2675 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002676 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002677 }
2678
Ted Kremenekac034612010-04-13 23:39:13 +00002679 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002680
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002681 // Link this new initializer list into the structured initializer
2682 // lists.
2683 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002684 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002685 else {
2686 Result->setSyntacticForm(IList);
2687 SyntacticToSemantic[IList] = Result;
2688 }
2689
2690 return Result;
2691}
2692
2693/// Update the initializer at index @p StructuredIndex within the
2694/// structured initializer list to the value @p expr.
2695void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2696 unsigned &StructuredIndex,
2697 Expr *expr) {
2698 // No structured initializer list to update
2699 if (!StructuredList)
2700 return;
2701
Ted Kremenekac034612010-04-13 23:39:13 +00002702 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2703 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002704 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002705 // We need to check on source range validity because the previous
2706 // initializer does not have to be an explicit initializer.
2707 // struct P { int a, b; };
2708 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2709 // There is an overwrite taking place because the first braced initializer
2710 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2711 if (PrevInit->getSourceRange().isValid()) {
2712 SemaRef.Diag(expr->getLocStart(),
2713 diag::warn_initializer_overrides)
2714 << expr->getSourceRange();
2715
2716 SemaRef.Diag(PrevInit->getLocStart(),
2717 diag::note_previous_initializer)
2718 << /*FIXME:has side effects=*/0
2719 << PrevInit->getSourceRange();
2720 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002721 }
Mike Stump11289f42009-09-09 15:08:12 +00002722
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002723 ++StructuredIndex;
2724}
2725
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002726/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002727/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002728/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002729/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002730/// failure. Returns the index expression, possibly with an implicit cast
2731/// added, on success. If everything went okay, Value will receive the
2732/// value of the constant expression.
2733static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002734CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002735 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002736
2737 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002738 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2739 if (Result.isInvalid())
2740 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002741
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002742 if (Value.isSigned() && Value.isNegative())
2743 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002744 << Value.toString(10) << Index->getSourceRange();
2745
Douglas Gregor51650d32009-01-23 21:04:18 +00002746 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002747 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002748}
2749
John McCalldadc5752010-08-24 06:29:42 +00002750ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002751 SourceLocation Loc,
2752 bool GNUSyntax,
2753 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002754 typedef DesignatedInitExpr::Designator ASTDesignator;
2755
2756 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002757 SmallVector<ASTDesignator, 32> Designators;
2758 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002759
2760 // Build designators and check array designator expressions.
2761 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2762 const Designator &D = Desig.getDesignator(Idx);
2763 switch (D.getKind()) {
2764 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002765 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002766 D.getFieldLoc()));
2767 break;
2768
2769 case Designator::ArrayDesignator: {
2770 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2771 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002772 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002773 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002774 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002775 Invalid = true;
2776 else {
2777 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002778 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002779 D.getRBracketLoc()));
2780 InitExpressions.push_back(Index);
2781 }
2782 break;
2783 }
2784
2785 case Designator::ArrayRangeDesignator: {
2786 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2787 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2788 llvm::APSInt StartValue;
2789 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002790 bool StartDependent = StartIndex->isTypeDependent() ||
2791 StartIndex->isValueDependent();
2792 bool EndDependent = EndIndex->isTypeDependent() ||
2793 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002794 if (!StartDependent)
2795 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002796 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002797 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002798 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002799
2800 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002801 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002802 else {
2803 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002804 if (StartDependent || EndDependent) {
2805 // Nothing to compute.
2806 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002807 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002808 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002809 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002810
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002811 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002812 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002813 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002814 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2815 Invalid = true;
2816 } else {
2817 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002818 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002819 D.getEllipsisLoc(),
2820 D.getRBracketLoc()));
2821 InitExpressions.push_back(StartIndex);
2822 InitExpressions.push_back(EndIndex);
2823 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002824 }
2825 break;
2826 }
2827 }
2828 }
2829
2830 if (Invalid || Init.isInvalid())
2831 return ExprError();
2832
2833 // Clear out the expressions within the designation.
2834 Desig.ClearExprs(*this);
2835
2836 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002837 = DesignatedInitExpr::Create(Context,
2838 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002839 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002840 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841
David Blaikiebbafb8a2012-03-11 07:00:24 +00002842 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002843 Diag(DIE->getLocStart(), diag::ext_designated_init)
2844 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002845
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002846 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002847}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002848
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002849//===----------------------------------------------------------------------===//
2850// Initialization entity
2851//===----------------------------------------------------------------------===//
2852
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002854 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002856{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002857 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2858 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002859 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002860 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002861 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002862 Type = VT->getElementType();
2863 } else {
2864 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2865 assert(CT && "Unexpected type");
2866 Kind = EK_ComplexElement;
2867 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002868 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002869}
2870
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002871InitializedEntity
2872InitializedEntity::InitializeBase(ASTContext &Context,
2873 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00002874 bool IsInheritedVirtualBase,
2875 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002876 InitializedEntity Result;
2877 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00002878 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002879 Result.Base = reinterpret_cast<uintptr_t>(Base);
2880 if (IsInheritedVirtualBase)
2881 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002882
Douglas Gregor1b303932009-12-22 15:35:07 +00002883 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002884 return Result;
2885}
2886
Douglas Gregor85dabae2009-12-16 01:38:02 +00002887DeclarationName InitializedEntity::getName() const {
2888 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002889 case EK_Parameter:
2890 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002891 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2892 return (D ? D->getDeclName() : DeclarationName());
2893 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002894
2895 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002896 case EK_Member:
2897 return VariableOrMember->getDeclName();
2898
Douglas Gregor19666fb2012-02-15 16:57:26 +00002899 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002900 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002901
Douglas Gregor85dabae2009-12-16 01:38:02 +00002902 case EK_Result:
2903 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002904 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002905 case EK_Temporary:
2906 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002907 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002908 case EK_ArrayElement:
2909 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002910 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002911 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002912 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002913 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002914 return DeclarationName();
2915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916
David Blaikie8a40f702012-01-17 06:56:22 +00002917 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002918}
2919
Douglas Gregora4b592a2009-12-19 03:01:41 +00002920DeclaratorDecl *InitializedEntity::getDecl() const {
2921 switch (getKind()) {
2922 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002923 case EK_Member:
2924 return VariableOrMember;
2925
John McCall31168b02011-06-15 23:02:42 +00002926 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002927 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002928 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2929
Douglas Gregora4b592a2009-12-19 03:01:41 +00002930 case EK_Result:
2931 case EK_Exception:
2932 case EK_New:
2933 case EK_Temporary:
2934 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002935 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002936 case EK_ArrayElement:
2937 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002938 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002939 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002940 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002941 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002942 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002943 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002944 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945
David Blaikie8a40f702012-01-17 06:56:22 +00002946 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002947}
2948
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002949bool InitializedEntity::allowsNRVO() const {
2950 switch (getKind()) {
2951 case EK_Result:
2952 case EK_Exception:
2953 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002955 case EK_Variable:
2956 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002957 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002958 case EK_Member:
2959 case EK_New:
2960 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002961 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002962 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002963 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002964 case EK_ArrayElement:
2965 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002966 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002967 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002968 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002969 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002970 break;
2971 }
2972
2973 return false;
2974}
2975
Richard Smithe6c01442013-06-05 00:46:14 +00002976unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002977 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002978 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2979 for (unsigned I = 0; I != Depth; ++I)
2980 OS << "`-";
2981
2982 switch (getKind()) {
2983 case EK_Variable: OS << "Variable"; break;
2984 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002985 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2986 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002987 case EK_Result: OS << "Result"; break;
2988 case EK_Exception: OS << "Exception"; break;
2989 case EK_Member: OS << "Member"; break;
2990 case EK_New: OS << "New"; break;
2991 case EK_Temporary: OS << "Temporary"; break;
2992 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002993 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002994 case EK_Base: OS << "Base"; break;
2995 case EK_Delegating: OS << "Delegating"; break;
2996 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2997 case EK_VectorElement: OS << "VectorElement " << Index; break;
2998 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2999 case EK_BlockElement: OS << "Block"; break;
3000 case EK_LambdaCapture:
3001 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003002 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003003 break;
3004 }
3005
3006 if (Decl *D = getDecl()) {
3007 OS << " ";
3008 cast<NamedDecl>(D)->printQualifiedName(OS);
3009 }
3010
3011 OS << " '" << getType().getAsString() << "'\n";
3012
3013 return Depth + 1;
3014}
3015
Yaron Kerencdae9412016-01-29 19:38:18 +00003016LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003017 dumpImpl(llvm::errs());
3018}
3019
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003020//===----------------------------------------------------------------------===//
3021// Initialization sequence
3022//===----------------------------------------------------------------------===//
3023
3024void InitializationSequence::Step::Destroy() {
3025 switch (Kind) {
3026 case SK_ResolveAddressOfOverloadedFunction:
3027 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003028 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003029 case SK_CastDerivedToBaseLValue:
3030 case SK_BindReference:
3031 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003032 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003033 case SK_UserConversion:
3034 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003035 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003036 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003037 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003038 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003039 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003040 case SK_UnwrapInitList:
3041 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003042 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003043 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003044 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003045 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003046 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003047 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003048 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003049 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003050 case SK_PassByIndirectCopyRestore:
3051 case SK_PassByIndirectRestore:
3052 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003053 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003054 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003055 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003056 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003057 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003059 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003060 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003061 delete ICS;
3062 }
3063}
3064
Douglas Gregor838fcc32010-03-26 20:14:36 +00003065bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00003066 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003067}
3068
3069bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003070 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003071 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003072
Douglas Gregor838fcc32010-03-26 20:14:36 +00003073 switch (getFailureKind()) {
3074 case FK_TooManyInitsForReference:
3075 case FK_ArrayNeedsInitList:
3076 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003077 case FK_ArrayNeedsInitListOrWideStringLiteral:
3078 case FK_NarrowStringIntoWideCharArray:
3079 case FK_WideStringIntoCharArray:
3080 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003081 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3082 case FK_NonConstLValueReferenceBindingToTemporary:
3083 case FK_NonConstLValueReferenceBindingToUnrelated:
3084 case FK_RValueReferenceBindingToLValue:
3085 case FK_ReferenceInitDropsQualifiers:
3086 case FK_ReferenceInitFailed:
3087 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003088 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003089 case FK_TooManyInitsForScalar:
3090 case FK_ReferenceBindingToInitList:
3091 case FK_InitListBadDestinationType:
3092 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003093 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003094 case FK_ArrayTypeMismatch:
3095 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003096 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003097 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003098 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003099 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003100 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003101 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003102
Douglas Gregor838fcc32010-03-26 20:14:36 +00003103 case FK_ReferenceInitOverloadFailed:
3104 case FK_UserConversionOverloadFailed:
3105 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003106 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003107 return FailedOverloadResult == OR_Ambiguous;
3108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003109
David Blaikie8a40f702012-01-17 06:56:22 +00003110 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003111}
3112
Douglas Gregorb33eed02010-04-16 22:09:46 +00003113bool InitializationSequence::isConstructorInitialization() const {
3114 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3115}
3116
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003117void
3118InitializationSequence
3119::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3120 DeclAccessPair Found,
3121 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003122 Step S;
3123 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3124 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003125 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003126 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003127 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003128 Steps.push_back(S);
3129}
3130
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003132 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003133 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003134 switch (VK) {
3135 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3136 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3137 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003138 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003139 S.Type = BaseType;
3140 Steps.push_back(S);
3141}
3142
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003144 bool BindingTemporary) {
3145 Step S;
3146 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3147 S.Type = T;
3148 Steps.push_back(S);
3149}
3150
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003151void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3152 Step S;
3153 S.Kind = SK_ExtraneousCopyToTemporary;
3154 S.Type = T;
3155 Steps.push_back(S);
3156}
3157
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003158void
3159InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3160 DeclAccessPair FoundDecl,
3161 QualType T,
3162 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003163 Step S;
3164 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003165 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003166 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003167 S.Function.Function = Function;
3168 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003169 Steps.push_back(S);
3170}
3171
3172void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003173 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003174 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003175 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003176 switch (VK) {
3177 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003178 S.Kind = SK_QualificationConversionRValue;
3179 break;
John McCall2536c6d2010-08-25 10:28:54 +00003180 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003181 S.Kind = SK_QualificationConversionXValue;
3182 break;
John McCall2536c6d2010-08-25 10:28:54 +00003183 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003184 S.Kind = SK_QualificationConversionLValue;
3185 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003186 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003187 S.Type = Ty;
3188 Steps.push_back(S);
3189}
3190
Richard Smith77be48a2014-07-31 06:31:19 +00003191void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3192 Step S;
3193 S.Kind = SK_AtomicConversion;
3194 S.Type = Ty;
3195 Steps.push_back(S);
3196}
3197
Jordan Roseb1312a52013-04-11 00:58:58 +00003198void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3199 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3200
3201 Step S;
3202 S.Kind = SK_LValueToRValue;
3203 S.Type = Ty;
3204 Steps.push_back(S);
3205}
3206
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003207void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003208 const ImplicitConversionSequence &ICS, QualType T,
3209 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003210 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003211 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3212 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003213 S.Type = T;
3214 S.ICS = new ImplicitConversionSequence(ICS);
3215 Steps.push_back(S);
3216}
3217
Douglas Gregor51e77d52009-12-10 17:56:55 +00003218void InitializationSequence::AddListInitializationStep(QualType T) {
3219 Step S;
3220 S.Kind = SK_ListInitialization;
3221 S.Type = T;
3222 Steps.push_back(S);
3223}
3224
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003226InitializationSequence
3227::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
3228 AccessSpecifier Access,
3229 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00003230 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003231 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003232 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003233 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003234 : SK_ConstructorInitializationFromList
3235 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003236 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003237 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003238 S.Function.Function = Constructor;
3239 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003240 Steps.push_back(S);
3241}
3242
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003243void InitializationSequence::AddZeroInitializationStep(QualType T) {
3244 Step S;
3245 S.Kind = SK_ZeroInitialization;
3246 S.Type = T;
3247 Steps.push_back(S);
3248}
3249
Douglas Gregore1314a62009-12-18 05:02:21 +00003250void InitializationSequence::AddCAssignmentStep(QualType T) {
3251 Step S;
3252 S.Kind = SK_CAssignment;
3253 S.Type = T;
3254 Steps.push_back(S);
3255}
3256
Eli Friedman78275202009-12-19 08:11:05 +00003257void InitializationSequence::AddStringInitStep(QualType T) {
3258 Step S;
3259 S.Kind = SK_StringInit;
3260 S.Type = T;
3261 Steps.push_back(S);
3262}
3263
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003264void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3265 Step S;
3266 S.Kind = SK_ObjCObjectConversion;
3267 S.Type = T;
3268 Steps.push_back(S);
3269}
3270
Douglas Gregore2f943b2011-02-22 18:29:51 +00003271void InitializationSequence::AddArrayInitStep(QualType T) {
3272 Step S;
3273 S.Kind = SK_ArrayInit;
3274 S.Type = T;
3275 Steps.push_back(S);
3276}
3277
Richard Smithebeed412012-02-15 22:38:09 +00003278void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3279 Step S;
3280 S.Kind = SK_ParenthesizedArrayInit;
3281 S.Type = T;
3282 Steps.push_back(S);
3283}
3284
John McCall31168b02011-06-15 23:02:42 +00003285void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3286 bool shouldCopy) {
3287 Step s;
3288 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3289 : SK_PassByIndirectRestore);
3290 s.Type = type;
3291 Steps.push_back(s);
3292}
3293
3294void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3295 Step S;
3296 S.Kind = SK_ProduceObjCObject;
3297 S.Type = T;
3298 Steps.push_back(S);
3299}
3300
Sebastian Redlc1839b12012-01-17 22:49:42 +00003301void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3302 Step S;
3303 S.Kind = SK_StdInitializerList;
3304 S.Type = T;
3305 Steps.push_back(S);
3306}
3307
Guy Benyei61054192013-02-07 10:55:47 +00003308void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3309 Step S;
3310 S.Kind = SK_OCLSamplerInit;
3311 S.Type = T;
3312 Steps.push_back(S);
3313}
3314
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003315void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3316 Step S;
3317 S.Kind = SK_OCLZeroEvent;
3318 S.Type = T;
3319 Steps.push_back(S);
3320}
3321
Sebastian Redl29526f02011-11-27 16:50:07 +00003322void InitializationSequence::RewrapReferenceInitList(QualType T,
3323 InitListExpr *Syntactic) {
3324 assert(Syntactic->getNumInits() == 1 &&
3325 "Can only rewrap trivial init lists.");
3326 Step S;
3327 S.Kind = SK_UnwrapInitList;
3328 S.Type = Syntactic->getInit(0)->getType();
3329 Steps.insert(Steps.begin(), S);
3330
3331 S.Kind = SK_RewrapInitList;
3332 S.Type = T;
3333 S.WrappingSyntacticList = Syntactic;
3334 Steps.push_back(S);
3335}
3336
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003338 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003339 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003340 this->Failure = Failure;
3341 this->FailedOverloadResult = Result;
3342}
3343
3344//===----------------------------------------------------------------------===//
3345// Attempt initialization
3346//===----------------------------------------------------------------------===//
3347
Nico Weber337d5aa2015-04-17 08:32:38 +00003348/// Tries to add a zero initializer. Returns true if that worked.
3349static bool
3350maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3351 const InitializedEntity &Entity) {
3352 if (Entity.getKind() != InitializedEntity::EK_Variable)
3353 return false;
3354
3355 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3356 if (VD->getInit() || VD->getLocEnd().isMacroID())
3357 return false;
3358
3359 QualType VariableTy = VD->getType().getCanonicalType();
3360 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3361 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3362 if (!Init.empty()) {
3363 Sequence.AddZeroInitializationStep(Entity.getType());
3364 Sequence.SetZeroInitializationFixit(Init, Loc);
3365 return true;
3366 }
3367 return false;
3368}
3369
John McCall31168b02011-06-15 23:02:42 +00003370static void MaybeProduceObjCObject(Sema &S,
3371 InitializationSequence &Sequence,
3372 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003373 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003374
3375 /// When initializing a parameter, produce the value if it's marked
3376 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003377 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003378 if (!Entity.isParameterConsumed())
3379 return;
3380
3381 assert(Entity.getType()->isObjCRetainableType() &&
3382 "consuming an object of unretainable type?");
3383 Sequence.AddProduceObjCObjectStep(Entity.getType());
3384
3385 /// When initializing a return value, if the return type is a
3386 /// retainable type, then returns need to immediately retain the
3387 /// object. If an autorelease is required, it will be done at the
3388 /// last instant.
3389 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3390 if (!Entity.getType()->isObjCRetainableType())
3391 return;
3392
3393 Sequence.AddProduceObjCObjectStep(Entity.getType());
3394 }
3395}
3396
Richard Smithcc1b96d2013-06-12 22:31:48 +00003397static void TryListInitialization(Sema &S,
3398 const InitializedEntity &Entity,
3399 const InitializationKind &Kind,
3400 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003401 InitializationSequence &Sequence,
3402 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003403
Richard Smithd86812d2012-07-05 08:39:21 +00003404/// \brief When initializing from init list via constructor, handle
3405/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003406///
Richard Smithd86812d2012-07-05 08:39:21 +00003407/// \return true if we have handled initialization of an object of type
3408/// std::initializer_list<T>, false otherwise.
3409static bool TryInitializerListConstruction(Sema &S,
3410 InitListExpr *List,
3411 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003412 InitializationSequence &Sequence,
3413 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003414 QualType E;
3415 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003416 return false;
3417
Richard Smithdb0ac552015-12-18 22:40:25 +00003418 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003419 Sequence.setIncompleteTypeFailure(E);
3420 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003421 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003422
3423 // Try initializing a temporary array from the init list.
3424 QualType ArrayType = S.Context.getConstantArrayType(
3425 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3426 List->getNumInits()),
3427 clang::ArrayType::Normal, 0);
3428 InitializedEntity HiddenArray =
3429 InitializedEntity::InitializeTemporary(ArrayType);
3430 InitializationKind Kind =
3431 InitializationKind::CreateDirectList(List->getExprLoc());
Manman Ren073db022016-03-10 18:53:19 +00003432 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3433 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003434 if (Sequence)
3435 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003436 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003437}
3438
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003439static OverloadingResult
3440ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003441 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003442 OverloadCandidateSet &CandidateSet,
Richard Smith40c78062015-02-21 02:31:57 +00003443 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003444 OverloadCandidateSet::iterator &Best,
3445 bool CopyInitializing, bool AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003446 bool OnlyListConstructors, bool IsListInit) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003447 CandidateSet.clear();
3448
Richard Smith40c78062015-02-21 02:31:57 +00003449 for (NamedDecl *D : Ctors) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003450 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3451 bool SuppressUserConversions = false;
3452
3453 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003454 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003455 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3456 if (ConstructorTmpl)
3457 Constructor = cast<CXXConstructorDecl>(
3458 ConstructorTmpl->getTemplatedDecl());
3459 else {
3460 Constructor = cast<CXXConstructorDecl>(D);
3461
Richard Smith6c6ddab2013-09-21 21:23:47 +00003462 // C++11 [over.best.ics]p4:
Larisse Voufo19d08672015-01-27 18:47:05 +00003463 // ... and the constructor or user-defined conversion function is a
3464 // candidate by
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003465 // - 13.3.1.3, when the argument is the temporary in the second step
Larisse Voufo19d08672015-01-27 18:47:05 +00003466 // of a class copy-initialization, or
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003467 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
Larisse Voufo19d08672015-01-27 18:47:05 +00003468 // user-defined conversion sequences are not considered.
Larisse Voufobcf327a2015-02-10 02:20:14 +00003469 // FIXME: This breaks backward compatibility, e.g. PR12117. As a
3470 // temporary fix, let's re-instate the third bullet above until
3471 // there is a resolution in the standard, i.e.,
3472 // - 13.3.1.7 when the initializer list has exactly one element that is
3473 // itself an initializer list and a conversion to some class X or
3474 // reference to (possibly cv-qualified) X is considered for the first
3475 // parameter of a constructor of X.
3476 if ((CopyInitializing ||
3477 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3478 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003479 SuppressUserConversions = true;
3480 }
3481
3482 if (!Constructor->isInvalidDecl() &&
3483 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003484 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003485 if (ConstructorTmpl)
3486 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003487 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003488 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003489 else {
3490 // C++ [over.match.copy]p1:
3491 // - When initializing a temporary to be bound to the first parameter
3492 // of a constructor that takes a reference to possibly cv-qualified
3493 // T as its first argument, called with a single argument in the
3494 // context of direct-initialization, explicit conversion functions
3495 // are also considered.
3496 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003497 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003498 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003499 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003500 SuppressUserConversions,
3501 /*PartialOverloading=*/false,
3502 /*AllowExplicit=*/AllowExplicitConv);
3503 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003504 }
3505 }
3506
3507 // Perform overload resolution and return the result.
3508 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3509}
3510
Sebastian Redled2e5322011-12-22 14:44:04 +00003511/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3512/// enumerates the constructors of the initialized entity and performs overload
3513/// resolution to select the best.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003514/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003515/// \param IsInitListCopy Is this non-list-initialization resulting from a
3516/// list-initialization from {x} where x is the same
3517/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003518static void TryConstructorInitialization(Sema &S,
3519 const InitializedEntity &Entity,
3520 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003521 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003522 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003523 bool IsListInit = false,
3524 bool IsInitListCopy = false) {
3525 assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3526 "IsListInit must come with a single initializer list argument.");
Sebastian Redl88e4d492012-02-04 21:27:33 +00003527
Sebastian Redled2e5322011-12-22 14:44:04 +00003528 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003529 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003530 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003531 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003532 }
3533
3534 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3535 assert(DestRecordType && "Constructor initialization requires record type");
3536 CXXRecordDecl *DestRecordDecl
3537 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3538
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003539 // Build the candidate set directly in the initialization sequence
3540 // structure, so that it will persist if we fail.
3541 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3542
3543 // Determine whether we are allowed to call explicit constructors or
3544 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003545 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003546 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003547
Sebastian Redled2e5322011-12-22 14:44:04 +00003548 // - Otherwise, if T is a class type, constructors are considered. The
3549 // applicable constructors are enumerated, and the best one is chosen
3550 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003551 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003552
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003553 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003554 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003555 bool AsInitializerList = false;
3556
Larisse Voufo19d08672015-01-27 18:47:05 +00003557 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003558 // When objects of non-aggregate type T are list-initialized, such that
3559 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3560 // according to the rules in this section, overload resolution selects
3561 // the constructor in two phases:
3562 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003563 // - Initially, the candidate functions are the initializer-list
3564 // constructors of the class T and the argument list consists of the
3565 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003566 if (IsListInit) {
Richard Smithd86812d2012-07-05 08:39:21 +00003567 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003568 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003569
3570 // If the initializer list has no elements and T has a default constructor,
3571 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003572 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003573 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003574 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003575 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003576 /*OnlyListConstructor=*/true,
3577 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003578
3579 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003580 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003581 }
3582
3583 // C++11 [over.match.list]p1:
3584 // - If no viable initializer-list constructor is found, overload resolution
3585 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003586 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003587 // elements of the initializer list.
3588 if (Result == OR_No_Viable_Function) {
3589 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003590 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003591 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003592 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003593 /*OnlyListConstructors=*/false,
3594 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003595 }
3596 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003597 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003598 InitializationSequence::FK_ListConstructorOverloadFailed :
3599 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003600 Result);
3601 return;
3602 }
3603
Richard Smithd86812d2012-07-05 08:39:21 +00003604 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003605 // If a program calls for the default initialization of an object
3606 // of a const-qualified type T, T shall be a class type with a
3607 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003608 // C++ core issue 253 proposal:
3609 // If the implicit default constructor initializes all subobjects, no
3610 // initializer should be required.
3611 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3612 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003613 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003614 Entity.getType().isConstQualified()) {
3615 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3616 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3617 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3618 return;
3619 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003620 }
3621
Sebastian Redl048a6d72012-04-01 19:54:59 +00003622 // C++11 [over.match.list]p1:
3623 // In copy-list-initialization, if an explicit constructor is chosen, the
3624 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003625 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003626 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3627 return;
3628 }
3629
Sebastian Redled2e5322011-12-22 14:44:04 +00003630 // Add the constructor initialization step. Any cv-qualification conversion is
3631 // subsumed by the initialization.
3632 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithed83ebd2015-02-05 07:02:11 +00003633 Sequence.AddConstructorInitializationStep(
3634 CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
3635 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003636}
3637
Sebastian Redl29526f02011-11-27 16:50:07 +00003638static bool
3639ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3640 Expr *Initializer,
3641 QualType &SourceType,
3642 QualType &UnqualifiedSourceType,
3643 QualType UnqualifiedTargetType,
3644 InitializationSequence &Sequence) {
3645 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3646 S.Context.OverloadTy) {
3647 DeclAccessPair Found;
3648 bool HadMultipleCandidates = false;
3649 if (FunctionDecl *Fn
3650 = S.ResolveAddressOfOverloadedFunction(Initializer,
3651 UnqualifiedTargetType,
3652 false, Found,
3653 &HadMultipleCandidates)) {
3654 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3655 HadMultipleCandidates);
3656 SourceType = Fn->getType();
3657 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3658 } else if (!UnqualifiedTargetType->isRecordType()) {
3659 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3660 return true;
3661 }
3662 }
3663 return false;
3664}
3665
3666static void TryReferenceInitializationCore(Sema &S,
3667 const InitializedEntity &Entity,
3668 const InitializationKind &Kind,
3669 Expr *Initializer,
3670 QualType cv1T1, QualType T1,
3671 Qualifiers T1Quals,
3672 QualType cv2T2, QualType T2,
3673 Qualifiers T2Quals,
3674 InitializationSequence &Sequence);
3675
Richard Smithd86812d2012-07-05 08:39:21 +00003676static void TryValueInitialization(Sema &S,
3677 const InitializedEntity &Entity,
3678 const InitializationKind &Kind,
3679 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003680 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003681
Sebastian Redl29526f02011-11-27 16:50:07 +00003682/// \brief Attempt list initialization of a reference.
3683static void TryReferenceListInitialization(Sema &S,
3684 const InitializedEntity &Entity,
3685 const InitializationKind &Kind,
3686 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003687 InitializationSequence &Sequence,
3688 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003689 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003690 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003691 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3692 return;
3693 }
David Majnemer9370dc22015-04-26 07:35:03 +00003694 // Can't reference initialize a compound literal.
3695 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3696 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3697 return;
3698 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003699
3700 QualType DestType = Entity.getType();
3701 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3702 Qualifiers T1Quals;
3703 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3704
3705 // Reference initialization via an initializer list works thus:
3706 // If the initializer list consists of a single element that is
3707 // reference-related to the referenced type, bind directly to that element
3708 // (possibly creating temporaries).
3709 // Otherwise, initialize a temporary with the initializer list and
3710 // bind to that.
3711 if (InitList->getNumInits() == 1) {
3712 Expr *Initializer = InitList->getInit(0);
3713 QualType cv2T2 = Initializer->getType();
3714 Qualifiers T2Quals;
3715 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3716
3717 // If this fails, creating a temporary wouldn't work either.
3718 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3719 T1, Sequence))
3720 return;
3721
3722 SourceLocation DeclLoc = Initializer->getLocStart();
3723 bool dummy1, dummy2, dummy3;
3724 Sema::ReferenceCompareResult RefRelationship
3725 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3726 dummy2, dummy3);
3727 if (RefRelationship >= Sema::Ref_Related) {
3728 // Try to bind the reference here.
3729 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3730 T1Quals, cv2T2, T2, T2Quals, Sequence);
3731 if (Sequence)
3732 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3733 return;
3734 }
Richard Smith03d93932013-01-15 07:58:29 +00003735
3736 // Update the initializer if we've resolved an overloaded function.
3737 if (Sequence.step_begin() != Sequence.step_end())
3738 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003739 }
3740
3741 // Not reference-related. Create a temporary and bind to that.
3742 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3743
Manman Ren073db022016-03-10 18:53:19 +00003744 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3745 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00003746 if (Sequence) {
3747 if (DestType->isRValueReferenceType() ||
3748 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3749 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3750 else
3751 Sequence.SetFailed(
3752 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3753 }
3754}
3755
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003756/// \brief Attempt list initialization (C++0x [dcl.init.list])
3757static void TryListInitialization(Sema &S,
3758 const InitializedEntity &Entity,
3759 const InitializationKind &Kind,
3760 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003761 InitializationSequence &Sequence,
3762 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003763 QualType DestType = Entity.getType();
3764
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003765 // C++ doesn't allow scalar initialization with more than one argument.
3766 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003767 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003768 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3769 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3770 return;
3771 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003772 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00003773 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
3774 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003775 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003776 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003777
Larisse Voufod2010992015-01-24 23:09:54 +00003778 if (DestType->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00003779 !S.isCompleteType(InitList->getLocStart(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00003780 Sequence.setIncompleteTypeFailure(DestType);
3781 return;
3782 }
Richard Smithd86812d2012-07-05 08:39:21 +00003783
Larisse Voufo19d08672015-01-27 18:47:05 +00003784 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003785 // - If T is a class type and the initializer list has a single element of
3786 // type cv U, where U is T or a class derived from T, the object is
3787 // initialized from that element (by copy-initialization for
3788 // copy-list-initialization, or by direct-initialization for
3789 // direct-list-initialization).
3790 // - Otherwise, if T is a character array and the initializer list has a
3791 // single element that is an appropriately-typed string literal
3792 // (8.5.2 [dcl.init.string]), initialization is performed as described
3793 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003794 // - Otherwise, if T is an aggregate, [...] (continue below).
3795 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003796 if (DestType->isRecordType()) {
3797 QualType InitType = InitList->getInit(0)->getType();
3798 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00003799 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003800 Expr *InitAsExpr = InitList->getInit(0);
3801 TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
3802 Sequence, /*InitListSyntax*/ false,
3803 /*IsInitListCopy*/ true);
Larisse Voufod2010992015-01-24 23:09:54 +00003804 return;
3805 }
3806 }
3807 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3808 Expr *SubInit[1] = {InitList->getInit(0)};
3809 if (!isa<VariableArrayType>(DestAT) &&
3810 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3811 InitializationKind SubKind =
3812 Kind.getKind() == InitializationKind::IK_DirectList
3813 ? InitializationKind::CreateDirect(Kind.getLocation(),
3814 InitList->getLBraceLoc(),
3815 InitList->getRBraceLoc())
3816 : Kind;
3817 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00003818 /*TopLevelOfInitList*/ true,
3819 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00003820
3821 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3822 // the element is not an appropriately-typed string literal, in which
3823 // case we should proceed as in C++11 (below).
3824 if (Sequence) {
3825 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3826 return;
3827 }
3828 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003829 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003830 }
Larisse Voufod2010992015-01-24 23:09:54 +00003831
3832 // C++11 [dcl.init.list]p3:
3833 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00003834 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
3835 (S.getLangOpts().CPlusPlus11 &&
3836 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00003837 if (S.getLangOpts().CPlusPlus11) {
3838 // - Otherwise, if the initializer list has no elements and T is a
3839 // class type with a default constructor, the object is
3840 // value-initialized.
3841 if (InitList->getNumInits() == 0) {
3842 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3843 if (RD->hasDefaultConstructor()) {
3844 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3845 return;
3846 }
3847 }
3848
3849 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3850 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00003851 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
3852 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00003853 return;
3854
3855 // - Otherwise, if T is a class type, constructors are considered.
3856 Expr *InitListAsExpr = InitList;
3857 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3858 Sequence, /*InitListSyntax*/ true);
3859 } else
3860 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3861 return;
3862 }
3863
Richard Smith089c3162013-09-21 21:55:46 +00003864 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00003865 InitList->getNumInits() == 1) {
3866 Expr *E = InitList->getInit(0);
3867
3868 // - Otherwise, if T is an enumeration with a fixed underlying type,
3869 // the initializer-list has a single element v, and the initialization
3870 // is direct-list-initialization, the object is initialized with the
3871 // value T(v); if a narrowing conversion is required to convert v to
3872 // the underlying type of T, the program is ill-formed.
3873 auto *ET = DestType->getAs<EnumType>();
3874 if (S.getLangOpts().CPlusPlus1z &&
3875 Kind.getKind() == InitializationKind::IK_DirectList &&
3876 ET && ET->getDecl()->isFixed() &&
3877 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
3878 (E->getType()->isIntegralOrEnumerationType() ||
3879 E->getType()->isFloatingType())) {
3880 // There are two ways that T(v) can work when T is an enumeration type.
3881 // If there is either an implicit conversion sequence from v to T or
3882 // a conversion function that can convert from v to T, then we use that.
3883 // Otherwise, if v is of integral, enumeration, or floating-point type,
3884 // it is converted to the enumeration type via its underlying type.
3885 // There is no overlap possible between these two cases (except when the
3886 // source value is already of the destination type), and the first
3887 // case is handled by the general case for single-element lists below.
3888 ImplicitConversionSequence ICS;
3889 ICS.setStandard();
3890 ICS.Standard.setAsIdentityConversion();
3891 // If E is of a floating-point type, then the conversion is ill-formed
3892 // due to narrowing, but go through the motions in order to produce the
3893 // right diagnostic.
3894 ICS.Standard.Second = E->getType()->isFloatingType()
3895 ? ICK_Floating_Integral
3896 : ICK_Integral_Conversion;
3897 ICS.Standard.setFromType(E->getType());
3898 ICS.Standard.setToType(0, E->getType());
3899 ICS.Standard.setToType(1, DestType);
3900 ICS.Standard.setToType(2, DestType);
3901 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
3902 /*TopLevelOfInitList*/true);
3903 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3904 return;
3905 }
3906
Richard Smith089c3162013-09-21 21:55:46 +00003907 // - Otherwise, if the initializer list has a single element of type E
3908 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00003909 // initialized from that element (by copy-initialization for
3910 // copy-list-initialization, or by direct-initialization for
3911 // direct-list-initialization); if a narrowing conversion is required
3912 // to convert the element to T, the program is ill-formed.
3913 //
Richard Smith089c3162013-09-21 21:55:46 +00003914 // Per core-24034, this is direct-initialization if we were performing
3915 // direct-list-initialization and copy-initialization otherwise.
3916 // We can't use InitListChecker for this, because it always performs
3917 // copy-initialization. This only matters if we might use an 'explicit'
3918 // conversion operator, so we only need to handle the cases where the source
3919 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00003920 if (InitList->getInit(0)->getType()->isRecordType()) {
3921 InitializationKind SubKind =
3922 Kind.getKind() == InitializationKind::IK_DirectList
3923 ? InitializationKind::CreateDirect(Kind.getLocation(),
3924 InitList->getLBraceLoc(),
3925 InitList->getRBraceLoc())
3926 : Kind;
3927 Expr *SubInit[1] = { InitList->getInit(0) };
3928 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3929 /*TopLevelOfInitList*/true,
3930 TreatUnavailableAsInvalid);
3931 if (Sequence)
3932 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3933 return;
3934 }
Richard Smith089c3162013-09-21 21:55:46 +00003935 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003936
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003937 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00003938 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003939 if (CheckInitList.HadError()) {
3940 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3941 return;
3942 }
3943
3944 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003945 Sequence.AddListInitializationStep(DestType);
3946}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003947
3948/// \brief Try a reference initialization that involves calling a conversion
3949/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003950static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3951 const InitializedEntity &Entity,
3952 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003953 Expr *Initializer,
3954 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003955 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003956 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003957 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3958 QualType T1 = cv1T1.getUnqualifiedType();
3959 QualType cv2T2 = Initializer->getType();
3960 QualType T2 = cv2T2.getUnqualifiedType();
3961
3962 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003963 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003964 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003966 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003967 ObjCConversion,
3968 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003969 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003970 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003971 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003972 (void)ObjCLifetimeConversion;
3973
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003974 // Build the candidate set directly in the initialization sequence
3975 // structure, so that it will persist if we fail.
3976 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3977 CandidateSet.clear();
3978
3979 // Determine whether we are allowed to call explicit constructors or
3980 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003981 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003982 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3983
Craig Topperc3ec1492014-05-26 06:22:03 +00003984 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003985 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00003986 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003987 // The type we're converting to is a class type. Enumerate its constructors
3988 // to see if there is a suitable conversion.
3989 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003990
Richard Smith40c78062015-02-21 02:31:57 +00003991 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00003992 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3993
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003994 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003995 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003996 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003997 if (ConstructorTmpl)
3998 Constructor = cast<CXXConstructorDecl>(
3999 ConstructorTmpl->getTemplatedDecl());
4000 else
John McCalla0296f72010-03-19 07:35:19 +00004001 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004003 if (!Constructor->isInvalidDecl() &&
4004 Constructor->isConvertingConstructor(AllowExplicit)) {
4005 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00004006 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004007 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004008 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004009 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004010 else
John McCalla0296f72010-03-19 07:35:19 +00004011 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004012 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004013 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004015 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004016 }
John McCall3696dcb2010-08-17 07:23:57 +00004017 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4018 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019
Craig Topperc3ec1492014-05-26 06:22:03 +00004020 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004021 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004022 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004023 // The type we're converting from is a class type, enumerate its conversion
4024 // functions.
4025 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4026
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004027 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4028 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004029 NamedDecl *D = *I;
4030 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4031 if (isa<UsingShadowDecl>(D))
4032 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004034 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4035 CXXConversionDecl *Conv;
4036 if (ConvTemplate)
4037 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4038 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004039 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004041 // If the conversion function doesn't return a reference type,
4042 // it can't be considered for this conversion unless we're allowed to
4043 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044 // FIXME: Do we need to make sure that we only consider conversion
4045 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004046 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004047 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004048 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4049 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004050 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004051 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004052 DestType, CandidateSet,
4053 /*AllowObjCConversionOnExplicit=*/
4054 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004055 else
John McCalla0296f72010-03-19 07:35:19 +00004056 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004057 Initializer, DestType, CandidateSet,
4058 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004059 }
4060 }
4061 }
John McCall3696dcb2010-08-17 07:23:57 +00004062 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4063 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004064
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004065 SourceLocation DeclLoc = Initializer->getLocStart();
4066
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004068 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004070 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004071 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004072
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004073 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004074 // This is the overload that will be used for this initialization step if we
4075 // use this initialization. Mark it as referenced.
4076 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004077
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004078 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004079 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00004080 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004081 else
4082 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004083
4084 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004085 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00004086 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004087 T2.getNonLValueExprType(S.Context),
4088 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004089
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004091 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00004092 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004093 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00004094 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004095 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00004096 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004097
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004098 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004099 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004100 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004101 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004103 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00004104 NewDerivedToBase, NewObjCConversion,
4105 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004106 if (NewRefRelationship == Sema::Ref_Incompatible) {
4107 // If the type we've converted to is not reference-related to the
4108 // type we're looking for, then there is another conversion step
4109 // we need to perform to produce a temporary of the right type
4110 // that we'll be binding to.
4111 ImplicitConversionSequence ICS;
4112 ICS.setStandard();
4113 ICS.Standard = Best->FinalConversion;
4114 T2 = ICS.Standard.getToType(2);
4115 Sequence.AddConversionSequenceStep(ICS, T2);
4116 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004117 Sequence.AddDerivedToBaseCastStep(
4118 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00004120 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004121 else if (NewObjCConversion)
4122 Sequence.AddObjCObjectConversionStep(
4123 S.Context.getQualifiedType(T1,
4124 T2.getNonReferenceType().getQualifiers()));
4125
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004126 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00004127 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004129 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
4130 return OR_Success;
4131}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132
Richard Smithc620f552011-10-19 16:55:56 +00004133static void CheckCXX98CompatAccessibleCopy(Sema &S,
4134 const InitializedEntity &Entity,
4135 Expr *CurInitExpr);
4136
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4138static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004139 const InitializedEntity &Entity,
4140 const InitializationKind &Kind,
4141 Expr *Initializer,
4142 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004143 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004144 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004145 Qualifiers T1Quals;
4146 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004147 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004148 Qualifiers T2Quals;
4149 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004150
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004151 // If the initializer is the address of an overloaded function, try
4152 // to resolve the overloaded function. If all goes well, T2 is the
4153 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004154 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4155 T1, Sequence))
4156 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004157
Sebastian Redl29526f02011-11-27 16:50:07 +00004158 // Delegate everything else to a subfunction.
4159 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4160 T1Quals, cv2T2, T2, T2Quals, Sequence);
4161}
4162
Jordan Roseb1312a52013-04-11 00:58:58 +00004163/// Converts the target of reference initialization so that it has the
4164/// appropriate qualifiers and value kind.
4165///
4166/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
4167/// \code
4168/// int x;
4169/// const int &r = x;
4170/// \endcode
4171///
4172/// In this case the reference is binding to a bitfield lvalue, which isn't
4173/// valid. Perform a load to create a lifetime-extended temporary instead.
4174/// \code
4175/// const int &r = someStruct.bitfield;
4176/// \endcode
4177static ExprValueKind
4178convertQualifiersAndValueKindIfNecessary(Sema &S,
4179 InitializationSequence &Sequence,
4180 Expr *Initializer,
4181 QualType cv1T1,
4182 Qualifiers T1Quals,
4183 Qualifiers T2Quals,
4184 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00004185 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00004186 Initializer->refersToVectorElement();
4187
4188 if (IsNonAddressableType) {
4189 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
4190 // lvalue reference to a non-volatile const type, or the reference shall be
4191 // an rvalue reference.
4192 //
4193 // If not, we can't make a temporary and bind to that. Give up and allow the
4194 // error to be diagnosed later.
4195 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
4196 assert(Initializer->isGLValue());
4197 return Initializer->getValueKind();
4198 }
4199
4200 // Force a load so we can materialize a temporary.
4201 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
4202 return VK_RValue;
4203 }
4204
4205 if (T1Quals != T2Quals) {
4206 Sequence.AddQualificationConversionStep(cv1T1,
4207 Initializer->getValueKind());
4208 }
4209
4210 return Initializer->getValueKind();
4211}
4212
Sebastian Redl29526f02011-11-27 16:50:07 +00004213/// \brief Reference initialization without resolving overloaded functions.
4214static void TryReferenceInitializationCore(Sema &S,
4215 const InitializedEntity &Entity,
4216 const InitializationKind &Kind,
4217 Expr *Initializer,
4218 QualType cv1T1, QualType T1,
4219 Qualifiers T1Quals,
4220 QualType cv2T2, QualType T2,
4221 Qualifiers T2Quals,
4222 InitializationSequence &Sequence) {
4223 QualType DestType = Entity.getType();
4224 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004225 // Compute some basic properties of the types and the initializer.
4226 bool isLValueRef = DestType->isLValueReferenceType();
4227 bool isRValueRef = !isLValueRef;
4228 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004229 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004230 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004231 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004232 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004233 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004234 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004235
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004236 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004238 // "cv2 T2" as follows:
4239 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004241 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004242 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004243 // there are no function rvalues in C++, rvalue refs to functions are treated
4244 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004245 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004246 bool T1Function = T1->isFunctionType();
4247 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004249 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004251 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004253 // reference-compatible with "cv2 T2," or
4254 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004256 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004257 // can occur. However, we do pay attention to whether it is a bit-field
4258 // to decide whether we're actually binding to a temporary created from
4259 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004260 if (DerivedToBase)
4261 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00004263 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004264 else if (ObjCConversion)
4265 Sequence.AddObjCObjectConversionStep(
4266 S.Context.getQualifiedType(T1, T2Quals));
4267
Jordan Roseb1312a52013-04-11 00:58:58 +00004268 ExprValueKind ValueKind =
4269 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
4270 cv1T1, T1Quals, T2Quals,
4271 isLValueRef);
4272 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273 return;
4274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
4276 // - has a class type (i.e., T2 is a class type), where T1 is not
4277 // reference-related to T2, and can be implicitly converted to an
4278 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4279 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004280 // applicable conversion functions (13.3.1.6) and choosing the best
4281 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004282 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004283 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004284 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4285 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004286 ConvOvlResult = TryRefInitWithConversionFunction(
4287 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004288 if (ConvOvlResult == OR_Success)
4289 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004290 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004291 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004292 InitializationSequence::FK_ReferenceInitOverloadFailed,
4293 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004294 }
4295 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004296
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004299 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004300 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004301 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4302 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4303 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004304 Sequence.SetOverloadFailure(
4305 InitializationSequence::FK_ReferenceInitOverloadFailed,
4306 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004307 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004308 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004309 ? (RefRelationship == Sema::Ref_Related
4310 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
4311 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
4312 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00004313
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004314 return;
4315 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004316
Douglas Gregor92e460e2011-01-20 16:44:54 +00004317 // - If the initializer expression
4318 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
4319 // "cv1 T1" is reference-compatible with "cv2 T2"
4320 // Note: functions are handled below.
4321 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00004322 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004324 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00004325 (InitCategory.isXValue() ||
4326 (InitCategory.isPRValue() && T2->isRecordType()) ||
4327 (InitCategory.isPRValue() && T2->isArrayType()))) {
4328 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
4329 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004330 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4331 // compiler the freedom to perform a copy here or bind to the
4332 // object, while C++0x requires that we bind directly to the
4333 // object. Hence, we always bind to the object without making an
4334 // extra copy. However, in C++03 requires that we check for the
4335 // presence of a suitable copy constructor:
4336 //
4337 // The constructor that would be used to make the copy shall
4338 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004339 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004340 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004341 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004342 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Douglas Gregor92e460e2011-01-20 16:44:54 +00004345 if (DerivedToBase)
4346 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
4347 ValueKind);
4348 else if (ObjCConversion)
4349 Sequence.AddObjCObjectConversionStep(
4350 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Jordan Roseb1312a52013-04-11 00:58:58 +00004352 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
4353 Initializer, cv1T1,
4354 T1Quals, T2Quals,
4355 isLValueRef);
4356
4357 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360
4361 // - has a class type (i.e., T2 is a class type), where T1 is not
4362 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004363 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4364 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004365 //
4366 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004367 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004368 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004369 ConvOvlResult = TryRefInitWithConversionFunction(
4370 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004371 if (ConvOvlResult)
4372 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004373 InitializationSequence::FK_ReferenceInitOverloadFailed,
4374 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004376 return;
4377 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004379 if ((RefRelationship == Sema::Ref_Compatible ||
4380 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
4381 isRValueRef && InitCategory.isLValue()) {
4382 Sequence.SetFailed(
4383 InitializationSequence::FK_RValueReferenceBindingToLValue);
4384 return;
4385 }
4386
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004387 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4388 return;
4389 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004390
4391 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004392 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004393 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004394 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004395
John McCallec6f4e92010-06-04 02:29:22 +00004396 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4397
Richard Smith2eabf782013-06-13 00:57:57 +00004398 // FIXME: Why do we use an implicit conversion here rather than trying
4399 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004400 ImplicitConversionSequence ICS
4401 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004402 /*SuppressUserConversions=*/false,
4403 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004404 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004405 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4406 /*AllowObjCWritebackConversion=*/false);
4407
4408 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004409 // FIXME: Use the conversion function set stored in ICS to turn
4410 // this into an overloading ambiguity diagnostic. However, we need
4411 // to keep that set as an OverloadCandidateSet rather than as some
4412 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004413 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4414 Sequence.SetOverloadFailure(
4415 InitializationSequence::FK_ReferenceInitOverloadFailed,
4416 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004417 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4418 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004419 else
4420 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004421 return;
John McCall31168b02011-06-15 23:02:42 +00004422 } else {
4423 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004424 }
4425
4426 // [...] If T1 is reference-related to T2, cv1 must be the
4427 // same cv-qualification as, or greater cv-qualification
4428 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004429 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4430 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004432 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004433 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4434 return;
4435 }
4436
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004438 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004440 InitCategory.isLValue()) {
4441 Sequence.SetFailed(
4442 InitializationSequence::FK_RValueReferenceBindingToLValue);
4443 return;
4444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004446 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004447}
4448
4449/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450/// (C++ [dcl.init.string], C99 6.7.8).
4451static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004452 const InitializedEntity &Entity,
4453 const InitializationKind &Kind,
4454 Expr *Initializer,
4455 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004456 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004457}
4458
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004459/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004461 const InitializedEntity &Entity,
4462 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004463 InitializationSequence &Sequence,
4464 InitListExpr *InitList) {
4465 assert((!InitList || InitList->getNumInits() == 0) &&
4466 "Shouldn't use value-init for non-empty init lists");
4467
Richard Smith1bfe0682012-02-14 21:14:13 +00004468 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004469 //
4470 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004471 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004473 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004474 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004476 if (const RecordType *RT = T->getAs<RecordType>()) {
4477 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004478 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004479 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004480 // C++98:
4481 // -- if T is a class type (clause 9) with a user-declared constructor
4482 // (12.1), then the default constructor for T is called (and the
4483 // initialization is ill-formed if T has no accessible default
4484 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004485 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004486 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004487 } else {
4488 // C++11:
4489 // -- if T is a class type (clause 9) with either no default constructor
4490 // (12.1 [class.ctor]) or a default constructor that is user-provided
4491 // or deleted, then the object is default-initialized;
4492 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4493 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004494 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496
Richard Smith1bfe0682012-02-14 21:14:13 +00004497 // -- if T is a (possibly cv-qualified) non-union class type without a
4498 // user-provided or deleted default constructor, then the object is
4499 // zero-initialized and, if T has a non-trivial default constructor,
4500 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004501 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4502 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004503 if (NeedZeroInitialization)
4504 Sequence.AddZeroInitializationStep(Entity.getType());
4505
Richard Smith593f9932012-12-08 02:01:17 +00004506 // C++03:
4507 // -- if T is a non-union class type without a user-declared constructor,
4508 // then every non-static data member and base class component of T is
4509 // value-initialized;
4510 // [...] A program that calls for [...] value-initialization of an
4511 // entity of reference type is ill-formed.
4512 //
4513 // C++11 doesn't need this handling, because value-initialization does not
4514 // occur recursively there, and the implicit default constructor is
4515 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004516 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004517 ClassDecl->hasUninitializedReferenceMember()) {
4518 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4519 return;
4520 }
4521
Richard Smithd86812d2012-07-05 08:39:21 +00004522 // If this is list-value-initialization, pass the empty init list on when
4523 // building the constructor call. This affects the semantics of a few
4524 // things (such as whether an explicit default constructor can be called).
4525 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004526 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004527 bool InitListSyntax = InitList;
4528
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004529 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4530 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004531 }
4532 }
4533
Douglas Gregor1b303932009-12-22 15:35:07 +00004534 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004535}
4536
Douglas Gregor85dabae2009-12-16 01:38:02 +00004537/// \brief Attempt default initialization (C++ [dcl.init]p6).
4538static void TryDefaultInitialization(Sema &S,
4539 const InitializedEntity &Entity,
4540 const InitializationKind &Kind,
4541 InitializationSequence &Sequence) {
4542 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543
Douglas Gregor85dabae2009-12-16 01:38:02 +00004544 // C++ [dcl.init]p6:
4545 // To default-initialize an object of type T means:
4546 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004547 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4548
Douglas Gregor85dabae2009-12-16 01:38:02 +00004549 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4550 // constructor for T is called (and the initialization is ill-formed if
4551 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004552 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004553 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004554 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556
Douglas Gregor85dabae2009-12-16 01:38:02 +00004557 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558
Douglas Gregor85dabae2009-12-16 01:38:02 +00004559 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004560 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004561 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004562 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004563 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4564 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004565 return;
4566 }
4567
4568 // If the destination type has a lifetime property, zero-initialize it.
4569 if (DestType.getQualifiers().hasObjCLifetime()) {
4570 Sequence.AddZeroInitializationStep(Entity.getType());
4571 return;
4572 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004573}
4574
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004575/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4576/// which enumerates all conversion functions and performs overload resolution
4577/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004579 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004580 const InitializationKind &Kind,
4581 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004582 InitializationSequence &Sequence,
4583 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004584 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4585 QualType SourceType = Initializer->getType();
4586 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4587 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004588
Douglas Gregor540c3b02009-12-14 17:27:33 +00004589 // Build the candidate set directly in the initialization sequence
4590 // structure, so that it will persist if we fail.
4591 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4592 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593
Douglas Gregor540c3b02009-12-14 17:27:33 +00004594 // Determine whether we are allowed to call explicit constructors or
4595 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004596 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597
Douglas Gregor540c3b02009-12-14 17:27:33 +00004598 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4599 // The type we're converting to is a class type. Enumerate its constructors
4600 // to see if there is a suitable conversion.
4601 CXXRecordDecl *DestRecordDecl
4602 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603
Douglas Gregord9848152010-04-26 14:36:57 +00004604 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004605 if (S.isCompleteType(Kind.getLocation(), DestType)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004606 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004607 // The container holding the constructors can under certain conditions
4608 // be changed while iterating. To be safe we copy the lookup results
4609 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004610 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004611 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004612 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004613 Con != ConEnd; ++Con) {
4614 NamedDecl *D = *Con;
4615 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
Douglas Gregord9848152010-04-26 14:36:57 +00004617 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004618 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004619 FunctionTemplateDecl *ConstructorTmpl
4620 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004621 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004622 Constructor = cast<CXXConstructorDecl>(
4623 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004624 else
Douglas Gregord9848152010-04-26 14:36:57 +00004625 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
Douglas Gregord9848152010-04-26 14:36:57 +00004627 if (!Constructor->isInvalidDecl() &&
4628 Constructor->isConvertingConstructor(AllowExplicit)) {
4629 if (ConstructorTmpl)
4630 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004631 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004632 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004633 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004634 else
4635 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004636 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004637 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639 }
Douglas Gregord9848152010-04-26 14:36:57 +00004640 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004641 }
Eli Friedman78275202009-12-19 08:11:05 +00004642
4643 SourceLocation DeclLoc = Initializer->getLocStart();
4644
Douglas Gregor540c3b02009-12-14 17:27:33 +00004645 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4646 // The type we're converting from is a class type, enumerate its conversion
4647 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004648
Eli Friedman4afe9a32009-12-20 22:12:03 +00004649 // We can only enumerate the conversion functions for a complete type; if
4650 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004651 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004652 CXXRecordDecl *SourceRecordDecl
4653 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004655 const auto &Conversions =
4656 SourceRecordDecl->getVisibleConversionFunctions();
4657 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004658 NamedDecl *D = *I;
4659 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4660 if (isa<UsingShadowDecl>(D))
4661 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662
Eli Friedman4afe9a32009-12-20 22:12:03 +00004663 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4664 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004665 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004666 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004667 else
John McCallda4458e2010-03-31 01:36:47 +00004668 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004669
Eli Friedman4afe9a32009-12-20 22:12:03 +00004670 if (AllowExplicit || !Conv->isExplicit()) {
4671 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004672 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004673 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004674 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004675 else
John McCalla0296f72010-03-19 07:35:19 +00004676 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004677 Initializer, DestType, CandidateSet,
4678 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004679 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004680 }
4681 }
4682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
4684 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004685 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004686 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004687 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004688 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004690 Result);
4691 return;
4692 }
John McCall0d1da222010-01-12 00:44:57 +00004693
Douglas Gregor540c3b02009-12-14 17:27:33 +00004694 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004695 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004696 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004697
Douglas Gregor540c3b02009-12-14 17:27:33 +00004698 if (isa<CXXConstructorDecl>(Function)) {
4699 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004700 // subsumed by the initialization. Per DR5, the created temporary is of the
4701 // cv-unqualified type of the destination.
4702 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4703 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004704 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004705 return;
4706 }
4707
4708 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004709 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004710 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004711 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004712 // the resulting temporary object (possible to create an object of
4713 // a base class type). That copy is not a separate conversion, so
4714 // we just make a note of the actual destination type (possibly a
4715 // base class of the type returned by the conversion function) and
4716 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004717 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4718 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004719 return;
4720 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004721
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004722 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4723 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724
Douglas Gregor5ab11652010-04-17 22:01:05 +00004725 // If the conversion following the call to the conversion function
4726 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004727 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4728 Best->FinalConversion.Third) {
4729 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004730 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004731 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004732 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004733 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004734}
4735
Richard Smithf032001b2013-06-20 02:18:31 +00004736/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4737/// a function with a pointer return type contains a 'return false;' statement.
4738/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4739/// code using that header.
4740///
4741/// Work around this by treating 'return false;' as zero-initializing the result
4742/// if it's used in a pointer-returning function in a system header.
4743static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4744 const InitializedEntity &Entity,
4745 const Expr *Init) {
4746 return S.getLangOpts().CPlusPlus11 &&
4747 Entity.getKind() == InitializedEntity::EK_Result &&
4748 Entity.getType()->isPointerType() &&
4749 isa<CXXBoolLiteralExpr>(Init) &&
4750 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4751 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4752}
4753
John McCall31168b02011-06-15 23:02:42 +00004754/// The non-zero enum values here are indexes into diagnostic alternatives.
4755enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4756
4757/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004758static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004759 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004760 // Skip parens.
4761 e = e->IgnoreParens();
4762
4763 // Skip address-of nodes.
4764 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4765 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004766 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4767 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004768
4769 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004770 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4771 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004772 case CK_Dependent:
4773 case CK_BitCast:
4774 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004775 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004776 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004777
4778 case CK_ArrayToPointerDecay:
4779 return IIK_nonscalar;
4780
4781 case CK_NullToPointer:
4782 return IIK_okay;
4783
4784 default:
4785 break;
4786 }
4787
4788 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004789 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004790 // set isWeakAccess to true, to mean that there will be an implicit
4791 // load which requires a cleanup.
4792 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4793 isWeakAccess = true;
4794
John McCall63f84442011-06-27 23:59:58 +00004795 if (!isAddressOf) return IIK_nonlocal;
4796
John McCall113bee02012-03-10 09:33:50 +00004797 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4798 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004799
4800 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004801
4802 // If we have a conditional operator, check both sides.
4803 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004804 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4805 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004806 return iik;
4807
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004808 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004809
4810 // These are never scalar.
4811 } else if (isa<ArraySubscriptExpr>(e)) {
4812 return IIK_nonscalar;
4813
4814 // Otherwise, it needs to be a null pointer constant.
4815 } else {
4816 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4817 ? IIK_okay : IIK_nonlocal);
4818 }
4819
4820 return IIK_nonlocal;
4821}
4822
4823/// Check whether the given expression is a valid operand for an
4824/// indirect copy/restore.
4825static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4826 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004827 bool isWeakAccess = false;
4828 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4829 // If isWeakAccess to true, there will be an implicit
4830 // load which requires a cleanup.
4831 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4832 S.ExprNeedsCleanups = true;
4833
John McCall31168b02011-06-15 23:02:42 +00004834 if (iik == IIK_okay) return;
4835
4836 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4837 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4838 << src->getSourceRange();
4839}
4840
Douglas Gregore2f943b2011-02-22 18:29:51 +00004841/// \brief Determine whether we have compatible array types for the
4842/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00004843static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00004844 const ArrayType *Source) {
4845 // If the source and destination array types are equivalent, we're
4846 // done.
4847 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4848 return true;
4849
4850 // Make sure that the element types are the same.
4851 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4852 return false;
4853
4854 // The only mismatch we allow is when the destination is an
4855 // incomplete array type and the source is a constant array type.
4856 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4857}
4858
John McCall31168b02011-06-15 23:02:42 +00004859static bool tryObjCWritebackConversion(Sema &S,
4860 InitializationSequence &Sequence,
4861 const InitializedEntity &Entity,
4862 Expr *Initializer) {
4863 bool ArrayDecay = false;
4864 QualType ArgType = Initializer->getType();
4865 QualType ArgPointee;
4866 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4867 ArrayDecay = true;
4868 ArgPointee = ArgArrayType->getElementType();
4869 ArgType = S.Context.getPointerType(ArgPointee);
4870 }
4871
4872 // Handle write-back conversion.
4873 QualType ConvertedArgType;
4874 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4875 ConvertedArgType))
4876 return false;
4877
4878 // We should copy unless we're passing to an argument explicitly
4879 // marked 'out'.
4880 bool ShouldCopy = true;
4881 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4882 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4883
4884 // Do we need an lvalue conversion?
4885 if (ArrayDecay || Initializer->isGLValue()) {
4886 ImplicitConversionSequence ICS;
4887 ICS.setStandard();
4888 ICS.Standard.setAsIdentityConversion();
4889
4890 QualType ResultType;
4891 if (ArrayDecay) {
4892 ICS.Standard.First = ICK_Array_To_Pointer;
4893 ResultType = S.Context.getPointerType(ArgPointee);
4894 } else {
4895 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4896 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4897 }
4898
4899 Sequence.AddConversionSequenceStep(ICS, ResultType);
4900 }
4901
4902 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4903 return true;
4904}
4905
Guy Benyei61054192013-02-07 10:55:47 +00004906static bool TryOCLSamplerInitialization(Sema &S,
4907 InitializationSequence &Sequence,
4908 QualType DestType,
4909 Expr *Initializer) {
4910 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4911 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4912 return false;
4913
4914 Sequence.AddOCLSamplerInitStep(DestType);
4915 return true;
4916}
4917
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004918//
4919// OpenCL 1.2 spec, s6.12.10
4920//
4921// The event argument can also be used to associate the
4922// async_work_group_copy with a previous async copy allowing
4923// an event to be shared by multiple async copies; otherwise
4924// event should be zero.
4925//
4926static bool TryOCLZeroEventInitialization(Sema &S,
4927 InitializationSequence &Sequence,
4928 QualType DestType,
4929 Expr *Initializer) {
4930 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4931 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4932 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4933 return false;
4934
4935 Sequence.AddOCLZeroEventStep(DestType);
4936 return true;
4937}
4938
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004939InitializationSequence::InitializationSequence(Sema &S,
4940 const InitializedEntity &Entity,
4941 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004942 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00004943 bool TopLevelOfInitList,
4944 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00004945 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00004946 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
4947 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00004948}
4949
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004950/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
4951/// address of that function, this returns true. Otherwise, it returns false.
4952static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
4953 auto *DRE = dyn_cast<DeclRefExpr>(E);
4954 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
4955 return false;
4956
4957 return !S.checkAddressOfFunctionIsAvailable(
4958 cast<FunctionDecl>(DRE->getDecl()));
4959}
4960
Richard Smith089c3162013-09-21 21:55:46 +00004961void InitializationSequence::InitializeFrom(Sema &S,
4962 const InitializedEntity &Entity,
4963 const InitializationKind &Kind,
4964 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00004965 bool TopLevelOfInitList,
4966 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004967 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968
John McCall5e77d762013-04-16 07:28:30 +00004969 // Eliminate non-overload placeholder types in the arguments. We
4970 // need to do this before checking whether types are dependent
4971 // because lowering a pseudo-object expression might well give us
4972 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004973 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004974 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4975 // FIXME: should we be doing this here?
4976 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4977 if (result.isInvalid()) {
4978 SetFailed(FK_PlaceholderType);
4979 return;
4980 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004981 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004982 }
4983
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004984 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985 // The semantics of initializers are as follows. The destination type is
4986 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004987 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004989 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004990 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004991
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004992 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004993 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004994 SequenceKind = DependentSequence;
4995 return;
4996 }
4997
Sebastian Redld201edf2011-06-05 13:59:11 +00004998 // Almost everything is a normal sequence.
4999 setSequenceKind(NormalSequence);
5000
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005001 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005002 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005003 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005004 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005005 if (S.getLangOpts().ObjC1) {
5006 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5007 DestType, Initializer->getType(),
5008 Initializer) ||
5009 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5010 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005011 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005012 if (!isa<InitListExpr>(Initializer))
5013 SourceType = Initializer->getType();
5014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015
Sebastian Redl0501c632012-02-12 16:37:36 +00005016 // - If the initializer is a (non-parenthesized) braced-init-list, the
5017 // object is list-initialized (8.5.4).
5018 if (Kind.getKind() != InitializationKind::IK_Direct) {
5019 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005020 TryListInitialization(S, Entity, Kind, InitList, *this,
5021 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005022 return;
5023 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005026 // - If the destination type is a reference type, see 8.5.3.
5027 if (DestType->isReferenceType()) {
5028 // C++0x [dcl.init.ref]p1:
5029 // A variable declared to be a T& or T&&, that is, "reference to type T"
5030 // (8.3.2), shall be initialized by an object, or function, of type T or
5031 // by an object that can be converted into a T.
5032 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005033 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005034 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005035 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005036 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005037 return;
5038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005040 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005041 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005042 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005043 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005044 return;
5045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005046
Douglas Gregor85dabae2009-12-16 01:38:02 +00005047 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005048 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005049 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005050 return;
5051 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005052
John McCall66884dd2011-02-21 07:22:22 +00005053 // - If the destination type is an array of characters, an array of
5054 // char16_t, an array of char32_t, or an array of wchar_t, and the
5055 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005057 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005058 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005059 if (Initializer && isa<VariableArrayType>(DestAT)) {
5060 SetFailed(FK_VariableLengthArrayHasInitializer);
5061 return;
5062 }
5063
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005064 if (Initializer) {
5065 switch (IsStringInit(Initializer, DestAT, Context)) {
5066 case SIF_None:
5067 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5068 return;
5069 case SIF_NarrowStringIntoWideChar:
5070 SetFailed(FK_NarrowStringIntoWideCharArray);
5071 return;
5072 case SIF_WideStringIntoChar:
5073 SetFailed(FK_WideStringIntoCharArray);
5074 return;
5075 case SIF_IncompatWideStringIntoWideChar:
5076 SetFailed(FK_IncompatWideStringIntoWideChar);
5077 return;
5078 case SIF_Other:
5079 break;
5080 }
John McCall66884dd2011-02-21 07:22:22 +00005081 }
5082
Douglas Gregore2f943b2011-02-22 18:29:51 +00005083 // Note: as an GNU C extension, we allow initialization of an
5084 // array from a compound literal that creates an array of the same
5085 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005086 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005087 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5088 Initializer->getType()->isArrayType()) {
5089 const ArrayType *SourceAT
5090 = Context.getAsArrayType(Initializer->getType());
5091 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005092 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005093 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005094 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005095 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005096 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005097 }
Richard Smithebeed412012-02-15 22:38:09 +00005098 }
Richard Smithd86812d2012-07-05 08:39:21 +00005099 // Note: as a GNU C++ extension, we allow list-initialization of a
5100 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005101 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005102 Entity.getKind() == InitializedEntity::EK_Member &&
5103 Initializer && isa<InitListExpr>(Initializer)) {
5104 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005105 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005106 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005107 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005108 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005109 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5110 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005111 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005112 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005114 return;
5115 }
Eli Friedman78275202009-12-19 08:11:05 +00005116
Larisse Voufod2010992015-01-24 23:09:54 +00005117 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005118 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005119 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005120 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005121
5122 // We're at the end of the line for C: it's either a write-back conversion
5123 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005124 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005125 // If allowed, check whether this is an Objective-C writeback conversion.
5126 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005127 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005128 return;
5129 }
Guy Benyei61054192013-02-07 10:55:47 +00005130
5131 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5132 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005133
5134 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5135 return;
5136
John McCall31168b02011-06-15 23:02:42 +00005137 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005138 AddCAssignmentStep(DestType);
5139 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005140 return;
5141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005142
David Blaikiebbafb8a2012-03-11 07:00:24 +00005143 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005144
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005145 // - If the destination type is a (possibly cv-qualified) class type:
5146 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147 // - If the initialization is direct-initialization, or if it is
5148 // copy-initialization where the cv-unqualified version of the
5149 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005150 // class of the destination, constructors are considered. [...]
5151 if (Kind.getKind() == InitializationKind::IK_Direct ||
5152 (Kind.getKind() == InitializationKind::IK_Copy &&
5153 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005154 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005155 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith77be48a2014-07-31 06:31:19 +00005156 DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005158 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005159 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005160 // used) to a derived class thereof are enumerated as described in
5161 // 13.3.1.4, and the best one is chosen through overload resolution
5162 // (13.3).
5163 else
Richard Smith77be48a2014-07-31 06:31:19 +00005164 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005165 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005166 return;
5167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005169 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005170 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005171 return;
5172 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005173 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005174
5175 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005176 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005177 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005178 // For a conversion to _Atomic(T) from either T or a class type derived
5179 // from T, initialize the T object then convert to _Atomic type.
5180 bool NeedAtomicConversion = false;
5181 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5182 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005183 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5184 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005185 DestType = Atomic->getValueType();
5186 NeedAtomicConversion = true;
5187 }
5188 }
5189
5190 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005191 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005192 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005193 if (!Failed() && NeedAtomicConversion)
5194 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005195 return;
5196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005198 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005199 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005200 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005201 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005202 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005203
John McCall31168b02011-06-15 23:02:42 +00005204 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005205 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005206 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005207 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005208 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005209 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5210 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005211
5212 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005213 ICS.Standard.Second == ICK_Writeback_Conversion) {
5214 // Objective-C ARC writeback conversion.
5215
5216 // We should copy unless we're passing to an argument explicitly
5217 // marked 'out'.
5218 bool ShouldCopy = true;
5219 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5220 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5221
5222 // If there was an lvalue adjustment, add it as a separate conversion.
5223 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5224 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5225 ImplicitConversionSequence LvalueICS;
5226 LvalueICS.setStandard();
5227 LvalueICS.Standard.setAsIdentityConversion();
5228 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5229 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005230 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005231 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005232
Richard Smith77be48a2014-07-31 06:31:19 +00005233 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005234 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005235 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005236 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5237 AddZeroInitializationStep(Entity.getType());
5238 } else if (Initializer->getType() == Context.OverloadTy &&
5239 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5240 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005241 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005242 else if (Initializer->getType()->isFunctionType() &&
5243 isExprAnUnaddressableFunction(S, Initializer))
5244 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005245 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005246 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005247 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005248 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005249
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005250 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005251 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005252}
5253
5254InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005255 for (auto &S : Steps)
5256 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005257}
5258
5259//===----------------------------------------------------------------------===//
5260// Perform initialization
5261//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005262static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005263getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005264 switch(Entity.getKind()) {
5265 case InitializedEntity::EK_Variable:
5266 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005267 case InitializedEntity::EK_Exception:
5268 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005269 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005270 return Sema::AA_Initializing;
5271
5272 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005273 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005274 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5275 return Sema::AA_Sending;
5276
Douglas Gregore1314a62009-12-18 05:02:21 +00005277 return Sema::AA_Passing;
5278
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005279 case InitializedEntity::EK_Parameter_CF_Audited:
5280 if (Entity.getDecl() &&
5281 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5282 return Sema::AA_Sending;
5283
5284 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5285
Douglas Gregore1314a62009-12-18 05:02:21 +00005286 case InitializedEntity::EK_Result:
5287 return Sema::AA_Returning;
5288
Douglas Gregore1314a62009-12-18 05:02:21 +00005289 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005290 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005291 // FIXME: Can we tell apart casting vs. converting?
5292 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005293
Douglas Gregore1314a62009-12-18 05:02:21 +00005294 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005295 case InitializedEntity::EK_ArrayElement:
5296 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005297 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005298 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005299 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005300 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005301 return Sema::AA_Initializing;
5302 }
5303
David Blaikie8a40f702012-01-17 06:56:22 +00005304 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005305}
5306
Richard Smith27874d62013-01-08 00:08:23 +00005307/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005308/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005309static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005310 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005311 case InitializedEntity::EK_ArrayElement:
5312 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005313 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00005314 case InitializedEntity::EK_New:
5315 case InitializedEntity::EK_Variable:
5316 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005317 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005318 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005319 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005320 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005321 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005322 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005323 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005324 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005325
Douglas Gregore1314a62009-12-18 05:02:21 +00005326 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005327 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005328 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005329 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005330 return true;
5331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332
Douglas Gregore1314a62009-12-18 05:02:21 +00005333 llvm_unreachable("missed an InitializedEntity kind?");
5334}
5335
Douglas Gregor95562572010-04-24 23:45:46 +00005336/// \brief Whether the given entity, when initialized with an object
5337/// created for that initialization, requires destruction.
5338static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
5339 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005340 case InitializedEntity::EK_Result:
5341 case InitializedEntity::EK_New:
5342 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005343 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005344 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005345 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005346 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005347 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005348 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349
Richard Smith27874d62013-01-08 00:08:23 +00005350 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00005351 case InitializedEntity::EK_Variable:
5352 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005353 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005354 case InitializedEntity::EK_Temporary:
5355 case InitializedEntity::EK_ArrayElement:
5356 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005357 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005358 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005359 return true;
5360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005361
5362 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005363}
5364
Richard Smithc620f552011-10-19 16:55:56 +00005365/// \brief Look for copy and move constructors and constructor templates, for
5366/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
5367static void LookupCopyAndMoveConstructors(Sema &S,
5368 OverloadCandidateSet &CandidateSet,
5369 CXXRecordDecl *Class,
5370 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00005371 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005372 // The container holding the constructors can under certain conditions
5373 // be changed while iterating (e.g. because of deserialization).
5374 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00005375 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00005376 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005377 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
5378 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00005379 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00005380
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005381 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00005382 // Handle copy/moveconstructors, only.
5383 if (!Constructor || Constructor->isInvalidDecl() ||
5384 !Constructor->isCopyOrMoveConstructor() ||
5385 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5386 continue;
5387
5388 DeclAccessPair FoundDecl
5389 = DeclAccessPair::make(Constructor, Constructor->getAccess());
5390 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005391 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00005392 continue;
5393 }
5394
5395 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005396 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00005397 if (ConstructorTmpl->isInvalidDecl())
5398 continue;
5399
5400 Constructor = cast<CXXConstructorDecl>(
5401 ConstructorTmpl->getTemplatedDecl());
5402 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5403 continue;
5404
5405 // FIXME: Do we need to limit this to copy-constructor-like
5406 // candidates?
5407 DeclAccessPair FoundDecl
5408 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00005409 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005410 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00005411 }
5412}
5413
5414/// \brief Get the location at which initialization diagnostics should appear.
5415static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5416 Expr *Initializer) {
5417 switch (Entity.getKind()) {
5418 case InitializedEntity::EK_Result:
5419 return Entity.getReturnLoc();
5420
5421 case InitializedEntity::EK_Exception:
5422 return Entity.getThrowLoc();
5423
5424 case InitializedEntity::EK_Variable:
5425 return Entity.getDecl()->getLocation();
5426
Douglas Gregor19666fb2012-02-15 16:57:26 +00005427 case InitializedEntity::EK_LambdaCapture:
5428 return Entity.getCaptureLoc();
5429
Richard Smithc620f552011-10-19 16:55:56 +00005430 case InitializedEntity::EK_ArrayElement:
5431 case InitializedEntity::EK_Member:
5432 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005433 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005434 case InitializedEntity::EK_Temporary:
5435 case InitializedEntity::EK_New:
5436 case InitializedEntity::EK_Base:
5437 case InitializedEntity::EK_Delegating:
5438 case InitializedEntity::EK_VectorElement:
5439 case InitializedEntity::EK_ComplexElement:
5440 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005441 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005442 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005443 return Initializer->getLocStart();
5444 }
5445 llvm_unreachable("missed an InitializedEntity kind?");
5446}
5447
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005448/// \brief Make a (potentially elidable) temporary copy of the object
5449/// provided by the given initializer by calling the appropriate copy
5450/// constructor.
5451///
5452/// \param S The Sema object used for type-checking.
5453///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005454/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005455/// the type of the initializer expression or a superclass thereof.
5456///
James Dennett634962f2012-06-14 21:40:34 +00005457/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005458///
5459/// \param CurInit The initializer expression.
5460///
5461/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5462/// is permitted in C++03 (but not C++0x) when binding a reference to
5463/// an rvalue.
5464///
5465/// \returns An expression that copies the initializer expression into
5466/// a temporary object, or an error expression if a copy could not be
5467/// created.
John McCalldadc5752010-08-24 06:29:42 +00005468static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005469 QualType T,
5470 const InitializedEntity &Entity,
5471 ExprResult CurInit,
5472 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005473 if (CurInit.isInvalid())
5474 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005475 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005476 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005477 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005478 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005479 Class = cast<CXXRecordDecl>(Record->getDecl());
5480 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005481 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005482
Douglas Gregor5d369002011-01-21 18:05:27 +00005483 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005484 // When certain criteria are met, an implementation is allowed to
5485 // omit the copy/move construction of a class object, even if the
5486 // copy/move constructor and/or destructor for the object have
5487 // side effects. [...]
5488 // - when a temporary class object that has not been bound to a
5489 // reference (12.2) would be copied/moved to a class object
5490 // with the same cv-unqualified type, the copy/move operation
5491 // can be omitted by constructing the temporary object
5492 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005493 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005494 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005495 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005496 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005497 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005498 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005499 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005500
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005502 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005503 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005504
Douglas Gregorf282a762011-01-21 19:38:21 +00005505 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005506 // Only consider constructors and constructor templates. Per
5507 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5508 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005509 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005510 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005511
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005512 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5513
Douglas Gregore1314a62009-12-18 05:02:21 +00005514 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005515 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005516 case OR_Success:
5517 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518
Douglas Gregore1314a62009-12-18 05:02:21 +00005519 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005520 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5521 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5522 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005523 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005524 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005525 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005526 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005527 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005528 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005529
Douglas Gregore1314a62009-12-18 05:02:21 +00005530 case OR_Ambiguous:
5531 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005532 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005533 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005534 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005535 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005536
Douglas Gregore1314a62009-12-18 05:02:21 +00005537 case OR_Deleted:
5538 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005539 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005540 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005541 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005542 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005543 }
5544
Douglas Gregor5ab11652010-04-17 22:01:05 +00005545 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005546 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005547 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005548
Anders Carlssona01874b2010-04-21 18:47:17 +00005549 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005550 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005551
5552 if (IsExtraneousCopy) {
5553 // If this is a totally extraneous copy for C++03 reference
5554 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005555 // expression. We don't generate an (elided) copy operation here
5556 // because doing so would require us to pass down a flag to avoid
5557 // infinite recursion, where each step adds another extraneous,
5558 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005559
Douglas Gregor30b52772010-04-18 07:57:34 +00005560 // Instantiate the default arguments of any extra parameters in
5561 // the selected copy constructor, as if we were going to create a
5562 // proper call to the copy constructor.
5563 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5564 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5565 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005566 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005567 break;
5568
5569 // Build the default argument expression; we don't actually care
5570 // if this succeeds or not, because this routine will complain
5571 // if there was a problem.
5572 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5573 }
5574
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005575 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
Douglas Gregor5ab11652010-04-17 22:01:05 +00005578 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005579 // constructor call (we might have derived-to-base conversions, or
5580 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005581 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005582 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005583
Douglas Gregord0ace022010-04-25 00:55:24 +00005584 // Actually perform the constructor call.
5585 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005586 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005587 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005588 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005589 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005590 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005591 CXXConstructExpr::CK_Complete,
5592 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005593
Douglas Gregord0ace022010-04-25 00:55:24 +00005594 // If we're supposed to bind temporaries, do so.
5595 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005596 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005597 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005598}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005599
Richard Smithc620f552011-10-19 16:55:56 +00005600/// \brief Check whether elidable copy construction for binding a reference to
5601/// a temporary would have succeeded if we were building in C++98 mode, for
5602/// -Wc++98-compat.
5603static void CheckCXX98CompatAccessibleCopy(Sema &S,
5604 const InitializedEntity &Entity,
5605 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005606 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005607
5608 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5609 if (!Record)
5610 return;
5611
5612 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005613 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005614 return;
5615
5616 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005617 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005618 LookupCopyAndMoveConstructors(
5619 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5620
5621 // Perform overload resolution.
5622 OverloadCandidateSet::iterator Best;
5623 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5624
5625 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5626 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5627 << CurInitExpr->getSourceRange();
5628
5629 switch (OR) {
5630 case OR_Success:
5631 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005632 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005633 // FIXME: Check default arguments as far as that's possible.
5634 break;
5635
5636 case OR_No_Viable_Function:
5637 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005638 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005639 break;
5640
5641 case OR_Ambiguous:
5642 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005643 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005644 break;
5645
5646 case OR_Deleted:
5647 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005648 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005649 break;
5650 }
5651}
5652
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005653void InitializationSequence::PrintInitLocationNote(Sema &S,
5654 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005655 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005656 if (Entity.getDecl()->getLocation().isInvalid())
5657 return;
5658
5659 if (Entity.getDecl()->getDeclName())
5660 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5661 << Entity.getDecl()->getDeclName();
5662 else
5663 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5664 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005665 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5666 Entity.getMethodDecl())
5667 S.Diag(Entity.getMethodDecl()->getLocation(),
5668 diag::note_method_return_type_change)
5669 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005670}
5671
Sebastian Redl112aa822011-07-14 19:07:55 +00005672static bool isReferenceBinding(const InitializationSequence::Step &s) {
5673 return s.Kind == InitializationSequence::SK_BindReference ||
5674 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5675}
5676
Jordan Rose6c0505e2013-05-06 16:48:12 +00005677/// Returns true if the parameters describe a constructor initialization of
5678/// an explicit temporary object, e.g. "Point(x, y)".
5679static bool isExplicitTemporary(const InitializedEntity &Entity,
5680 const InitializationKind &Kind,
5681 unsigned NumArgs) {
5682 switch (Entity.getKind()) {
5683 case InitializedEntity::EK_Temporary:
5684 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005685 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005686 break;
5687 default:
5688 return false;
5689 }
5690
5691 switch (Kind.getKind()) {
5692 case InitializationKind::IK_DirectList:
5693 return true;
5694 // FIXME: Hack to work around cast weirdness.
5695 case InitializationKind::IK_Direct:
5696 case InitializationKind::IK_Value:
5697 return NumArgs != 1;
5698 default:
5699 return false;
5700 }
5701}
5702
Sebastian Redled2e5322011-12-22 14:44:04 +00005703static ExprResult
5704PerformConstructorInitialization(Sema &S,
5705 const InitializedEntity &Entity,
5706 const InitializationKind &Kind,
5707 MultiExprArg Args,
5708 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005709 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005710 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005711 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005712 SourceLocation LBraceLoc,
5713 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005714 unsigned NumArgs = Args.size();
5715 CXXConstructorDecl *Constructor
5716 = cast<CXXConstructorDecl>(Step.Function.Function);
5717 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5718
5719 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005720 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005721 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5722 ? Kind.getEqualLoc()
5723 : Kind.getLocation();
5724
5725 if (Kind.getKind() == InitializationKind::IK_Default) {
5726 // Force even a trivial, implicit default constructor to be
5727 // semantically checked. We do this explicitly because we don't build
5728 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005729 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005730 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005731 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005732 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5733 }
5734
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005735 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005736
Douglas Gregor6073dca2012-02-24 23:56:31 +00005737 // C++ [over.match.copy]p1:
5738 // - When initializing a temporary to be bound to the first parameter
5739 // of a constructor that takes a reference to possibly cv-qualified
5740 // T as its first argument, called with a single argument in the
5741 // context of direct-initialization, explicit conversion functions
5742 // are also considered.
5743 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5744 Args.size() == 1 &&
5745 Constructor->isCopyOrMoveConstructor();
5746
Sebastian Redled2e5322011-12-22 14:44:04 +00005747 // Determine the arguments required to actually perform the constructor
5748 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005749 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005750 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005751 AllowExplicitConv,
5752 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005753 return ExprError();
5754
5755
Jordan Rose6c0505e2013-05-06 16:48:12 +00005756 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005757 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005758 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005759 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5760 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005761
5762 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5763 if (!TSInfo)
5764 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005765 SourceRange ParenOrBraceRange =
5766 (Kind.getKind() == InitializationKind::IK_DirectList)
5767 ? SourceRange(LBraceLoc, RBraceLoc)
5768 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005769
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005770 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5771 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5772 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005773 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005774 } else {
5775 CXXConstructExpr::ConstructionKind ConstructKind =
5776 CXXConstructExpr::CK_Complete;
5777
5778 if (Entity.getKind() == InitializedEntity::EK_Base) {
5779 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5780 CXXConstructExpr::CK_VirtualBase :
5781 CXXConstructExpr::CK_NonVirtualBase;
5782 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5783 ConstructKind = CXXConstructExpr::CK_Delegating;
5784 }
5785
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005786 // Only get the parenthesis or brace range if it is a list initialization or
5787 // direct construction.
5788 SourceRange ParenOrBraceRange;
5789 if (IsListInitialization)
5790 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5791 else if (Kind.getKind() == InitializationKind::IK_Direct)
5792 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005793
5794 // If the entity allows NRVO, mark the construction as elidable
5795 // unconditionally.
5796 if (Entity.allowsNRVO())
5797 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5798 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005799 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005800 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005801 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005802 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005803 ConstructorInitRequiresZeroInit,
5804 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005805 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005806 else
5807 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5808 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005809 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005810 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005811 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005812 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005813 ConstructorInitRequiresZeroInit,
5814 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005815 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005816 }
5817 if (CurInit.isInvalid())
5818 return ExprError();
5819
5820 // Only check access if all of that succeeded.
5821 S.CheckConstructorAccess(Loc, Constructor, Entity,
5822 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005823 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5824 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005825
5826 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005827 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005828
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005829 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005830}
5831
Richard Smitheb3cad52012-06-04 22:27:30 +00005832/// Determine whether the specified InitializedEntity definitely has a lifetime
5833/// longer than the current full-expression. Conservatively returns false if
5834/// it's unclear.
5835static bool
5836InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5837 const InitializedEntity *Top = &Entity;
5838 while (Top->getParent())
5839 Top = Top->getParent();
5840
5841 switch (Top->getKind()) {
5842 case InitializedEntity::EK_Variable:
5843 case InitializedEntity::EK_Result:
5844 case InitializedEntity::EK_Exception:
5845 case InitializedEntity::EK_Member:
5846 case InitializedEntity::EK_New:
5847 case InitializedEntity::EK_Base:
5848 case InitializedEntity::EK_Delegating:
5849 return true;
5850
5851 case InitializedEntity::EK_ArrayElement:
5852 case InitializedEntity::EK_VectorElement:
5853 case InitializedEntity::EK_BlockElement:
5854 case InitializedEntity::EK_ComplexElement:
5855 // Could not determine what the full initialization is. Assume it might not
5856 // outlive the full-expression.
5857 return false;
5858
5859 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005860 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005861 case InitializedEntity::EK_Temporary:
5862 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005863 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005864 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005865 // The entity being initialized might not outlive the full-expression.
5866 return false;
5867 }
5868
5869 llvm_unreachable("unknown entity kind");
5870}
5871
Richard Smithe6c01442013-06-05 00:46:14 +00005872/// Determine the declaration which an initialized entity ultimately refers to,
5873/// for the purpose of lifetime-extending a temporary bound to a reference in
5874/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005875static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5876 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005877 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005878 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005879 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005880 case InitializedEntity::EK_Variable:
5881 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005882 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005883
5884 case InitializedEntity::EK_Member:
5885 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005886 if (Entity->getParent())
5887 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5888 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005889
5890 // except:
5891 // -- A temporary bound to a reference member in a constructor's
5892 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005893 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005894
5895 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005896 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005897 // -- A temporary bound to a reference parameter in a function call
5898 // persists until the completion of the full-expression containing
5899 // the call.
5900 case InitializedEntity::EK_Result:
5901 // -- The lifetime of a temporary bound to the returned value in a
5902 // function return statement is not extended; the temporary is
5903 // destroyed at the end of the full-expression in the return statement.
5904 case InitializedEntity::EK_New:
5905 // -- A temporary bound to a reference in a new-initializer persists
5906 // until the completion of the full-expression containing the
5907 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005908 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005909
5910 case InitializedEntity::EK_Temporary:
5911 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005912 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005913 // We don't yet know the storage duration of the surrounding temporary.
5914 // Assume it's got full-expression duration for now, it will patch up our
5915 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005916 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005917
5918 case InitializedEntity::EK_ArrayElement:
5919 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005920 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5921 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005922
5923 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00005924 // For subobjects, we look at the complete object.
5925 if (Entity->getParent())
5926 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5927 Entity);
5928 // Fall through.
Richard Smithe6c01442013-06-05 00:46:14 +00005929 case InitializedEntity::EK_Delegating:
5930 // We can reach this case for aggregate initialization in a constructor:
5931 // struct A { int &&r; };
5932 // struct B : A { B() : A{0} {} };
5933 // In this case, use the innermost field decl as the context.
5934 return FallbackDecl;
5935
5936 case InitializedEntity::EK_BlockElement:
5937 case InitializedEntity::EK_LambdaCapture:
5938 case InitializedEntity::EK_Exception:
5939 case InitializedEntity::EK_VectorElement:
5940 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005941 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005942 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005943 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005944}
5945
David Majnemerdaff3702014-05-01 17:50:17 +00005946static void performLifetimeExtension(Expr *Init,
5947 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005948
5949/// Update a glvalue expression that is used as the initializer of a reference
5950/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005951/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005952static bool
5953performReferenceExtension(Expr *Init,
5954 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005955 // Walk past any constructs which we can lifetime-extend across.
5956 Expr *Old;
5957 do {
5958 Old = Init;
5959
Richard Smithdbc82492015-01-10 01:28:13 +00005960 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5961 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5962 // This is just redundant braces around an initializer. Step over it.
5963 Init = ILE->getInit(0);
5964 }
5965 }
5966
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005967 // Step over any subobject adjustments; we may have a materialized
5968 // temporary inside them.
5969 SmallVector<const Expr *, 2> CommaLHSs;
5970 SmallVector<SubobjectAdjustment, 2> Adjustments;
5971 Init = const_cast<Expr *>(
5972 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5973
5974 // Per current approach for DR1376, look through casts to reference type
5975 // when performing lifetime extension.
5976 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5977 if (CE->getSubExpr()->isGLValue())
5978 Init = CE->getSubExpr();
5979
5980 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5981 // It's unclear if binding a reference to that xvalue extends the array
5982 // temporary.
5983 } while (Init != Old);
5984
Richard Smithe6c01442013-06-05 00:46:14 +00005985 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5986 // Update the storage duration of the materialized temporary.
5987 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005988 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5989 ExtendingEntity->allocateManglingNumber());
5990 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005991 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005992 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005993
5994 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005995}
5996
5997/// Update a prvalue expression that is going to be materialized as a
5998/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005999static void performLifetimeExtension(Expr *Init,
6000 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00006001 // Dig out the expression which constructs the extended temporary.
6002 SmallVector<const Expr *, 2> CommaLHSs;
6003 SmallVector<SubobjectAdjustment, 2> Adjustments;
6004 Init = const_cast<Expr *>(
6005 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
6006
Richard Smith736a9472013-06-12 20:42:33 +00006007 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6008 Init = BTE->getSubExpr();
6009
Richard Smithcc1b96d2013-06-12 22:31:48 +00006010 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006011 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00006012 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006013 return;
6014 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006015
Richard Smithe6c01442013-06-05 00:46:14 +00006016 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006017 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006018 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00006019 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006020 return;
6021 }
6022
Richard Smithcc1b96d2013-06-12 22:31:48 +00006023 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006024 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6025
6026 // If we lifetime-extend a braced initializer which is initializing an
6027 // aggregate, and that aggregate contains reference members which are
6028 // bound to temporaries, those temporaries are also lifetime-extended.
6029 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6030 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006031 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006032 else {
6033 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006034 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006035 if (Index >= ILE->getNumInits())
6036 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006037 if (I->isUnnamedBitfield())
6038 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006039 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006040 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006041 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00006042 else if (isa<InitListExpr>(SubInit) ||
6043 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00006044 // This may be either aggregate-initialization of a member or
6045 // initialization of a std::initializer_list object. Either way,
6046 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006047 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006048 ++Index;
6049 }
6050 }
6051 }
6052 }
6053}
6054
Richard Smithcc1b96d2013-06-12 22:31:48 +00006055static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6056 const Expr *Init, bool IsInitializerList,
6057 const ValueDecl *ExtendingDecl) {
6058 // Warn if a field lifetime-extends a temporary.
6059 if (isa<FieldDecl>(ExtendingDecl)) {
6060 if (IsInitializerList) {
6061 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6062 << /*at end of constructor*/true;
6063 return;
6064 }
6065
6066 bool IsSubobjectMember = false;
6067 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6068 Ent = Ent->getParent()) {
6069 if (Ent->getKind() != InitializedEntity::EK_Base) {
6070 IsSubobjectMember = true;
6071 break;
6072 }
6073 }
6074 S.Diag(Init->getExprLoc(),
6075 diag::warn_bind_ref_member_to_temporary)
6076 << ExtendingDecl << Init->getSourceRange()
6077 << IsSubobjectMember << IsInitializerList;
6078 if (IsSubobjectMember)
6079 S.Diag(ExtendingDecl->getLocation(),
6080 diag::note_ref_subobject_of_member_declared_here);
6081 else
6082 S.Diag(ExtendingDecl->getLocation(),
6083 diag::note_ref_or_ptr_member_declared_here)
6084 << /*is pointer*/false;
6085 }
6086}
6087
Richard Smithaaa0ec42013-09-21 21:19:19 +00006088static void DiagnoseNarrowingInInitList(Sema &S,
6089 const ImplicitConversionSequence &ICS,
6090 QualType PreNarrowingType,
6091 QualType EntityType,
6092 const Expr *PostInit);
6093
Richard Trieuac3eca52015-04-29 01:52:17 +00006094/// Provide warnings when std::move is used on construction.
6095static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6096 bool IsReturnStmt) {
6097 if (!InitExpr)
6098 return;
6099
Richard Trieu6093d142015-07-29 17:03:34 +00006100 if (!S.ActiveTemplateInstantiations.empty())
6101 return;
6102
Richard Trieuac3eca52015-04-29 01:52:17 +00006103 QualType DestType = InitExpr->getType();
6104 if (!DestType->isRecordType())
6105 return;
6106
6107 unsigned DiagID = 0;
6108 if (IsReturnStmt) {
6109 const CXXConstructExpr *CCE =
6110 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6111 if (!CCE || CCE->getNumArgs() != 1)
6112 return;
6113
6114 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6115 return;
6116
6117 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00006118 }
6119
6120 // Find the std::move call and get the argument.
6121 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6122 if (!CE || CE->getNumArgs() != 1)
6123 return;
6124
6125 const FunctionDecl *MoveFunction = CE->getDirectCallee();
6126 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6127 !MoveFunction->getIdentifier() ||
6128 !MoveFunction->getIdentifier()->isStr("move"))
6129 return;
6130
6131 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6132
6133 if (IsReturnStmt) {
6134 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6135 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6136 return;
6137
6138 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6139 if (!VD || !VD->hasLocalStorage())
6140 return;
6141
Richard Trieu8d4006a2015-07-28 19:06:16 +00006142 QualType SourceType = VD->getType();
6143 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00006144 return;
6145
Richard Trieu8d4006a2015-07-28 19:06:16 +00006146 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00006147 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00006148 }
6149
Davide Italiano7842c3f2015-07-18 01:15:19 +00006150 // If we're returning a function parameter, copy elision
6151 // is not possible.
6152 if (isa<ParmVarDecl>(VD))
6153 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00006154 else
6155 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00006156 } else {
6157 DiagID = diag::warn_pessimizing_move_on_initialization;
6158 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6159 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6160 return;
6161 }
6162
6163 S.Diag(CE->getLocStart(), DiagID);
6164
6165 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6166 // is within a macro.
6167 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6168 if (CallBegin.isMacroID())
6169 return;
6170 SourceLocation RParen = CE->getRParenLoc();
6171 if (RParen.isMacroID())
6172 return;
6173 SourceLocation LParen;
6174 SourceLocation ArgLoc = Arg->getLocStart();
6175
6176 // Special testing for the argument location. Since the fix-it needs the
6177 // location right before the argument, the argument location can be in a
6178 // macro only if it is at the beginning of the macro.
6179 while (ArgLoc.isMacroID() &&
6180 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
6181 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6182 }
6183
6184 if (LParen.isMacroID())
6185 return;
6186
6187 LParen = ArgLoc.getLocWithOffset(-1);
6188
6189 S.Diag(CE->getLocStart(), diag::note_remove_move)
6190 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6191 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6192}
6193
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006194ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006195InitializationSequence::Perform(Sema &S,
6196 const InitializedEntity &Entity,
6197 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00006198 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006199 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006200 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006201 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00006202 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006203 }
Nico Weber337d5aa2015-04-17 08:32:38 +00006204 if (!ZeroInitializationFixit.empty()) {
6205 unsigned DiagID = diag::err_default_init_const;
6206 if (Decl *D = Entity.getDecl())
6207 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6208 DiagID = diag::ext_default_init_const;
6209
6210 // The initialization would have succeeded with this fixit. Since the fixit
6211 // is on the error, we need to build a valid AST in this case, so this isn't
6212 // handled in the Failed() branch above.
6213 QualType DestType = Entity.getType();
6214 S.Diag(Kind.getLocation(), DiagID)
6215 << DestType << (bool)DestType->getAs<RecordType>()
6216 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6217 ZeroInitializationFixit);
6218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006219
Sebastian Redld201edf2011-06-05 13:59:11 +00006220 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006221 // If the declaration is a non-dependent, incomplete array type
6222 // that has an initializer, then its type will be completed once
6223 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00006224 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00006225 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006226 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006227 if (const IncompleteArrayType *ArrayT
6228 = S.Context.getAsIncompleteArrayType(DeclType)) {
6229 // FIXME: We don't currently have the ability to accurately
6230 // compute the length of an initializer list without
6231 // performing full type-checking of the initializer list
6232 // (since we have to determine where braces are implicitly
6233 // introduced and such). So, we fall back to making the array
6234 // type a dependently-sized array type with no specified
6235 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006236 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006237 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00006238
Douglas Gregor51e77d52009-12-10 17:56:55 +00006239 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00006240 if (DeclaratorDecl *DD = Entity.getDecl()) {
6241 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6242 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00006243 if (IncompleteArrayTypeLoc ArrayLoc =
6244 TL.getAs<IncompleteArrayTypeLoc>())
6245 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00006246 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00006247 }
6248
6249 *ResultType
6250 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006251 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006252 ArrayT->getSizeModifier(),
6253 ArrayT->getIndexTypeCVRQualifiers(),
6254 Brackets);
6255 }
6256
6257 }
6258 }
Sebastian Redla9351792012-02-11 23:51:47 +00006259 if (Kind.getKind() == InitializationKind::IK_Direct &&
6260 !Kind.isExplicitCast()) {
6261 // Rebuild the ParenListExpr.
6262 SourceRange ParenRange = Kind.getParenRange();
6263 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006264 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00006265 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00006266 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00006267 Kind.isExplicitCast() ||
6268 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006269 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006270 }
6271
Sebastian Redld201edf2011-06-05 13:59:11 +00006272 // No steps means no initialization.
6273 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006274 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006275
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006276 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006277 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006278 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00006279 // Produce a C++98 compatibility warning if we are initializing a reference
6280 // from an initializer list. For parameters, we produce a better warning
6281 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006282 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00006283 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6284 << Init->getSourceRange();
6285 }
6286
Richard Smitheb3cad52012-06-04 22:27:30 +00006287 // Diagnose cases where we initialize a pointer to an array temporary, and the
6288 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006289 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00006290 Entity.getType()->isPointerType() &&
6291 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006292 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00006293 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6294 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6295 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6296 << Init->getSourceRange();
6297 }
6298
Douglas Gregor1b303932009-12-22 15:35:07 +00006299 QualType DestType = Entity.getType().getNonReferenceType();
6300 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00006301 // the same as Entity.getDecl()->getType() in cases involving type merging,
6302 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00006303 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00006304 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00006305 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006306
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006307 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006308
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006309 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00006310 // grab the only argument out the Args and place it into the "current"
6311 // initializer.
6312 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006313 case SK_ResolveAddressOfOverloadedFunction:
6314 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006315 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006316 case SK_CastDerivedToBaseLValue:
6317 case SK_BindReference:
6318 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006319 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00006320 case SK_UserConversion:
6321 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006322 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006323 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00006324 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00006325 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006326 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00006327 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00006328 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00006329 case SK_UnwrapInitList:
6330 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00006331 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00006332 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00006333 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00006334 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00006335 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00006336 case SK_PassByIndirectCopyRestore:
6337 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00006338 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006339 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00006340 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006341 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00006342 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006343 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00006344 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006345 break;
John McCall34376a62010-12-04 03:47:34 +00006346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006347
Douglas Gregore1314a62009-12-18 05:02:21 +00006348 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00006349 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006350 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00006351 case SK_ZeroInitialization:
6352 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006354
6355 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006356 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006357 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006358 for (step_iterator Step = step_begin(), StepEnd = step_end();
6359 Step != StepEnd; ++Step) {
6360 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006361 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006362
John Wiegley01296292011-04-08 18:41:53 +00006363 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006364
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006365 switch (Step->Kind) {
6366 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006367 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006368 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00006369 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00006370 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6371 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006372 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00006373 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00006374 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006375 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006376
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006377 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006378 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006379 case SK_CastDerivedToBaseLValue: {
6380 // We have a derived-to-base cast that produces either an rvalue or an
6381 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006382
John McCallcf142162010-08-07 06:22:56 +00006383 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00006384
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006385 // Casts to inaccessible base classes are allowed with C-style casts.
6386 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6387 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00006388 CurInit.get()->getLocStart(),
6389 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00006390 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00006391 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006392
John McCall2536c6d2010-08-25 10:28:54 +00006393 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006394 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006395 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006396 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006397 VK_XValue :
6398 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006399 CurInit =
6400 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6401 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006402 break;
6403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006404
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006405 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00006406 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
6407 if (CurInit.get()->refersToBitField()) {
6408 // We don't necessarily have an unambiguous source bit-field.
6409 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006410 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00006411 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00006412 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00006413 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00006414 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00006415 if (BitField)
6416 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
6417
John McCallfaf5fb42010-08-26 23:41:50 +00006418 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006419 }
Anders Carlssona91be642010-01-29 02:47:33 +00006420
John Wiegley01296292011-04-08 18:41:53 +00006421 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00006422 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00006423 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
6424 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00006425 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006426 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006427 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00006428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006429
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006430 // Reference binding does not have any corresponding ASTs.
6431
6432 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006433 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006434 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006435
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006436 // Even though we didn't materialize a temporary, the binding may still
6437 // extend the lifetime of a temporary. This happens if we bind a reference
6438 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00006439 if (const InitializedEntity *ExtendingEntity =
6440 getEntityForTemporaryLifetimeExtension(&Entity))
6441 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6442 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6443 /*IsInitializerList=*/false,
6444 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006445
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006446 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006447
Richard Smithe6c01442013-06-05 00:46:14 +00006448 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00006449 // Make sure the "temporary" is actually an rvalue.
6450 assert(CurInit.get()->isRValue() && "not a temporary");
6451
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006452 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006453 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006454 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006455
Douglas Gregorfe314812011-06-21 17:03:29 +00006456 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00006457 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00006458 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006459 Entity.getType()->isLValueReferenceType());
6460
6461 // Maybe lifetime-extend the temporary's subobjects to match the
6462 // entity's lifetime.
6463 if (const InitializedEntity *ExtendingEntity =
6464 getEntityForTemporaryLifetimeExtension(&Entity))
6465 if (performReferenceExtension(MTE, ExtendingEntity))
6466 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
6467 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006468
6469 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00006470 // need cleanups. Likewise if we're extending this temporary to automatic
6471 // storage duration -- we need to register its cleanup during the
6472 // full-expression's cleanups.
6473 if ((S.getLangOpts().ObjCAutoRefCount &&
6474 MTE->getType()->isObjCLifetimeType()) ||
6475 (MTE->getStorageDuration() == SD_Automatic &&
6476 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00006477 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00006478
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006479 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006480 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006482
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006483 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006484 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006485 /*IsExtraneousCopy=*/true);
6486 break;
6487
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006488 case SK_UserConversion: {
6489 // We have a user-defined conversion that invokes either a constructor
6490 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006491 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00006492 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00006493 FunctionDecl *Fn = Step->Function.Function;
6494 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006495 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006496 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006497 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006498 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006499 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006500 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006501 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00006502
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006503 // Determine the arguments required to actually perform the constructor
6504 // call.
John Wiegley01296292011-04-08 18:41:53 +00006505 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006506 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006507 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006508 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006509 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006510
Richard Smithb24f0672012-02-11 19:22:50 +00006511 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006513 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006514 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006515 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006516 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006517 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006518 CXXConstructExpr::CK_Complete,
6519 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006520 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006521 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006522
Anders Carlssona01874b2010-04-21 18:47:17 +00006523 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00006524 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00006525 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6526 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527
John McCalle3027922010-08-25 11:45:40 +00006528 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00006529 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6530 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00006531 S.IsDerivedFrom(Loc, SourceType, Class))
Douglas Gregore1314a62009-12-18 05:02:21 +00006532 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006533
Douglas Gregor95562572010-04-24 23:45:46 +00006534 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006535 } else {
6536 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006537 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006538 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006539 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006540 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6541 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006542
6543 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006544 // derived-to-base conversion? I believe the answer is "no", because
6545 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006546 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006547 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006548 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006549 FoundFn, Conversion);
6550 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006551 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006552 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006553
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006554 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006555 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6556 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006557 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006558 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006559
John McCalle3027922010-08-25 11:45:40 +00006560 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561
Alp Toker314cc812014-01-25 16:55:45 +00006562 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006564
Sebastian Redl112aa822011-07-14 19:07:55 +00006565 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006566 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6567
6568 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006569 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006570 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006571 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006572 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006573 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006574 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006575 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006576 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6577 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006578 }
6579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006580
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006581 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6582 CastKind, CurInit.get(), nullptr,
6583 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006584 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006585 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006586 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006587 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006588 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006589 break;
6590 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006591
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006592 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006593 case SK_QualificationConversionXValue:
6594 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006595 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006596 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006597 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006598 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006599 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006600 VK_XValue :
6601 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006602 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006603 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006604 }
6605
Richard Smith77be48a2014-07-31 06:31:19 +00006606 case SK_AtomicConversion: {
6607 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6608 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6609 CK_NonAtomicToAtomic, VK_RValue);
6610 break;
6611 }
6612
Jordan Roseb1312a52013-04-11 00:58:58 +00006613 case SK_LValueToRValue: {
6614 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006615 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6616 CK_LValueToRValue, CurInit.get(),
6617 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006618 break;
6619 }
6620
Richard Smithaaa0ec42013-09-21 21:19:19 +00006621 case SK_ConversionSequence:
6622 case SK_ConversionSequenceNoNarrowing: {
6623 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006624 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6625 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006626 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006627 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006628 ExprResult CurInitExprRes =
6629 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006630 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006631 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006632 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006633 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006634
6635 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6636 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6637 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6638 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006639 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006641
Douglas Gregor51e77d52009-12-10 17:56:55 +00006642 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006643 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006644 // If we're not initializing the top-level entity, we need to create an
6645 // InitializeTemporary entity for our target type.
6646 QualType Ty = Step->Type;
6647 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006648 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006649 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6650 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00006651 InitList, Ty, /*VerifyOnly=*/false,
6652 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006653 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006654 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006655
Richard Smithcc1b96d2013-06-12 22:31:48 +00006656 // Hack: We must update *ResultType if available in order to set the
6657 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6658 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6659 if (ResultType &&
6660 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006661 if ((*ResultType)->isRValueReferenceType())
6662 Ty = S.Context.getRValueReferenceType(Ty);
6663 else if ((*ResultType)->isLValueReferenceType())
6664 Ty = S.Context.getLValueReferenceType(Ty,
6665 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6666 *ResultType = Ty;
6667 }
6668
6669 InitListExpr *StructuredInitList =
6670 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006671 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006672 CurInit = shouldBindAsTemporary(InitEntity)
6673 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006674 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006675 break;
6676 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006677
Richard Smith53324112014-07-16 21:33:43 +00006678 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006679 // When an initializer list is passed for a parameter of type "reference
6680 // to object", we don't get an EK_Temporary entity, but instead an
6681 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006682 // FIXME: This is a hack. What we really should do is create a user
6683 // conversion step for this case, but this makes it considerably more
6684 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006685 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6686 Entity.getType().getNonReferenceType());
6687 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006688 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006689 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006690 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6691 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006692 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006693 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6694 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006695 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006696 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006697 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006698 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006699 InitList->getLBraceLoc(),
6700 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006701 break;
6702 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006703
Sebastian Redl29526f02011-11-27 16:50:07 +00006704 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006705 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006706 break;
6707
6708 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006709 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006710 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6711 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006712 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006713 ILE->setSyntacticForm(Syntactic);
6714 ILE->setType(E->getType());
6715 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006716 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006717 break;
6718 }
6719
Richard Smith53324112014-07-16 21:33:43 +00006720 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006721 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006722 // When an initializer list is passed for a parameter of type "reference
6723 // to object", we don't get an EK_Temporary entity, but instead an
6724 // EK_Parameter entity with reference type.
6725 // FIXME: This is a hack. What we really should do is create a user
6726 // conversion step for this case, but this makes it considerably more
6727 // complicated. For now, this will do.
6728 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6729 Entity.getType().getNonReferenceType());
6730 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006731 bool IsStdInitListInit =
6732 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006733 CurInit = PerformConstructorInitialization(
6734 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6735 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006736 /*IsListInitialization*/IsStdInitListInit,
6737 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006738 /*LBraceLoc*/SourceLocation(),
6739 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006740 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006742
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006743 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006744 step_iterator NextStep = Step;
6745 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006746 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006747 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006748 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006749 // The need for zero-initialization is recorded directly into
6750 // the call to the object's constructor within the next step.
6751 ConstructorInitRequiresZeroInit = true;
6752 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006753 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006754 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006755 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6756 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006757 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006758 Kind.getRange().getBegin());
6759
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006760 CurInit = new (S.Context) CXXScalarValueInitExpr(
6761 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6762 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006763 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006764 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006765 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006766 break;
6767 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006768
6769 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006770 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00006771 // Save off the initial CurInit in case we need to emit a diagnostic
6772 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006773 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006774 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006775 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6776 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006777 if (Result.isInvalid())
6778 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006779 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006780
6781 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006782 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006783 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006784 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006785 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006786 == Sema::Compatible)
6787 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006788 if (CurInitExprRes.isInvalid())
6789 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006790 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006791
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006792 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006793 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6794 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00006795 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006796 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006797 &Complained)) {
6798 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006799 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006800 } else if (Complained)
6801 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006802 break;
6803 }
Eli Friedman78275202009-12-19 08:11:05 +00006804
6805 case SK_StringInit: {
6806 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006807 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006808 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006809 break;
6810 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006811
6812 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006813 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006814 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006815 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006816 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006817
6818 case SK_ArrayInit:
6819 // Okay: we checked everything before creating this step. Note that
6820 // this is a GNU extension.
6821 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006822 << Step->Type << CurInit.get()->getType()
6823 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006824
6825 // If the destination type is an incomplete array type, update the
6826 // type accordingly.
6827 if (ResultType) {
6828 if (const IncompleteArrayType *IncompleteDest
6829 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6830 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006831 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006832 *ResultType = S.Context.getConstantArrayType(
6833 IncompleteDest->getElementType(),
6834 ConstantSource->getSize(),
6835 ArrayType::Normal, 0);
6836 }
6837 }
6838 }
John McCall31168b02011-06-15 23:02:42 +00006839 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006840
Richard Smithebeed412012-02-15 22:38:09 +00006841 case SK_ParenthesizedArrayInit:
6842 // Okay: we checked everything before creating this step. Note that
6843 // this is a GNU extension.
6844 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6845 << CurInit.get()->getSourceRange();
6846 break;
6847
John McCall31168b02011-06-15 23:02:42 +00006848 case SK_PassByIndirectCopyRestore:
6849 case SK_PassByIndirectRestore:
6850 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006851 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6852 CurInit.get(), Step->Type,
6853 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006854 break;
6855
6856 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006857 CurInit =
6858 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6859 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006860 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006861
6862 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006863 S.Diag(CurInit.get()->getExprLoc(),
6864 diag::warn_cxx98_compat_initializer_list_init)
6865 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006866
Richard Smithcc1b96d2013-06-12 22:31:48 +00006867 // Materialize the temporary into memory.
6868 MaterializeTemporaryExpr *MTE = new (S.Context)
6869 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006870 /*BoundToLvalueReference=*/false);
6871
6872 // Maybe lifetime-extend the array temporary's subobjects to match the
6873 // entity's lifetime.
6874 if (const InitializedEntity *ExtendingEntity =
6875 getEntityForTemporaryLifetimeExtension(&Entity))
6876 if (performReferenceExtension(MTE, ExtendingEntity))
6877 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6878 /*IsInitializerList=*/true,
6879 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006880
6881 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006882 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006883
6884 // Bind the result, in case the library has given initializer_list a
6885 // non-trivial destructor.
6886 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006887 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006888 break;
6889 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006890
Guy Benyei61054192013-02-07 10:55:47 +00006891 case SK_OCLSamplerInit: {
6892 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006893 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006894
6895 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006896
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006897 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006898 if (!SourceType->isSamplerT())
6899 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6900 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006901 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006902 llvm_unreachable("Invalid EntityKind!");
6903 }
6904
6905 break;
6906 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006907 case SK_OCLZeroEvent: {
6908 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006909 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006910
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006911 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006912 CK_ZeroToOCLEvent,
6913 CurInit.get()->getValueKind());
6914 break;
6915 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006916 }
6917 }
John McCall1f425642010-11-11 03:21:53 +00006918
6919 // Diagnose non-fatal problems with the completed initialization.
6920 if (Entity.getKind() == InitializedEntity::EK_Member &&
6921 cast<FieldDecl>(Entity.getDecl())->isBitField())
6922 S.CheckBitFieldInitialization(Kind.getLocation(),
6923 cast<FieldDecl>(Entity.getDecl()),
6924 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006925
Richard Trieuac3eca52015-04-29 01:52:17 +00006926 // Check for std::move on construction.
6927 if (const Expr *E = CurInit.get()) {
6928 CheckMoveOnConstruction(S, E,
6929 Entity.getKind() == InitializedEntity::EK_Result);
6930 }
6931
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006932 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006933}
6934
Richard Smith593f9932012-12-08 02:01:17 +00006935/// Somewhere within T there is an uninitialized reference subobject.
6936/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006937static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6938 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006939 if (T->isReferenceType()) {
6940 S.Diag(Loc, diag::err_reference_without_init)
6941 << T.getNonReferenceType();
6942 return true;
6943 }
6944
6945 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6946 if (!RD || !RD->hasUninitializedReferenceMember())
6947 return false;
6948
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006949 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006950 if (FI->isUnnamedBitfield())
6951 continue;
6952
6953 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6954 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6955 return true;
6956 }
6957 }
6958
Aaron Ballman574705e2014-03-13 15:41:46 +00006959 for (const auto &BI : RD->bases()) {
6960 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006961 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6962 return true;
6963 }
6964 }
6965
6966 return false;
6967}
6968
6969
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006970//===----------------------------------------------------------------------===//
6971// Diagnose initialization failures
6972//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006973
6974/// Emit notes associated with an initialization that failed due to a
6975/// "simple" conversion failure.
6976static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6977 Expr *op) {
6978 QualType destType = entity.getType();
6979 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6980 op->getType()->isObjCObjectPointerType()) {
6981
6982 // Emit a possible note about the conversion failing because the
6983 // operand is a message send with a related result type.
6984 S.EmitRelatedResultTypeNote(op);
6985
6986 // Emit a possible note about a return failing because we're
6987 // expecting a related result type.
6988 if (entity.getKind() == InitializedEntity::EK_Result)
6989 S.EmitRelatedResultTypeNoteForReturn(destType);
6990 }
6991}
6992
Richard Smith0449aaf2013-11-21 23:30:57 +00006993static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6994 InitListExpr *InitList) {
6995 QualType DestType = Entity.getType();
6996
6997 QualType E;
6998 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6999 QualType ArrayType = S.Context.getConstantArrayType(
7000 E.withConst(),
7001 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7002 InitList->getNumInits()),
7003 clang::ArrayType::Normal, 0);
7004 InitializedEntity HiddenArray =
7005 InitializedEntity::InitializeTemporary(ArrayType);
7006 return diagnoseListInit(S, HiddenArray, InitList);
7007 }
7008
Richard Smith8d082d12014-09-04 22:13:39 +00007009 if (DestType->isReferenceType()) {
7010 // A list-initialization failure for a reference means that we tried to
7011 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7012 // inner initialization failed.
7013 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7014 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7015 SourceLocation Loc = InitList->getLocStart();
7016 if (auto *D = Entity.getDecl())
7017 Loc = D->getLocation();
7018 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7019 return;
7020 }
7021
Richard Smith0449aaf2013-11-21 23:30:57 +00007022 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00007023 /*VerifyOnly=*/false,
7024 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00007025 assert(DiagnoseInitList.HadError() &&
7026 "Inconsistent init list check result.");
7027}
7028
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007030 const InitializedEntity &Entity,
7031 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007032 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007033 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007034 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007035
Douglas Gregor1b303932009-12-22 15:35:07 +00007036 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007037 switch (Failure) {
7038 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007039 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007040 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00007041 // Dig out the reference subobject which is uninitialized and diagnose it.
7042 // If this is value-initialization, this could be nested some way within
7043 // the target type.
7044 assert(Kind.getKind() == InitializationKind::IK_Value ||
7045 DestType->isReferenceType());
7046 bool Diagnosed =
7047 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7048 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7049 (void)Diagnosed;
7050 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007051 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007052 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007053 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007054
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007055 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007056 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007057 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007058 case FK_ArrayNeedsInitListOrStringLiteral:
7059 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7060 break;
7061 case FK_ArrayNeedsInitListOrWideStringLiteral:
7062 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7063 break;
7064 case FK_NarrowStringIntoWideCharArray:
7065 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7066 break;
7067 case FK_WideStringIntoCharArray:
7068 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7069 break;
7070 case FK_IncompatWideStringIntoWideChar:
7071 S.Diag(Kind.getLocation(),
7072 diag::err_array_init_incompat_wide_string_into_wchar);
7073 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007074 case FK_ArrayTypeMismatch:
7075 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00007076 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00007077 (Failure == FK_ArrayTypeMismatch
7078 ? diag::err_array_init_different_type
7079 : diag::err_array_init_non_constant_array))
7080 << DestType.getNonReferenceType()
7081 << Args[0]->getType()
7082 << Args[0]->getSourceRange();
7083 break;
7084
John McCalla59dc2f2012-01-05 00:13:19 +00007085 case FK_VariableLengthArrayHasInitializer:
7086 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7087 << Args[0]->getSourceRange();
7088 break;
7089
John McCall16df1e52010-03-30 21:47:33 +00007090 case FK_AddressOfOverloadFailed: {
7091 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007092 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007093 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00007094 true,
7095 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007096 break;
John McCall16df1e52010-03-30 21:47:33 +00007097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007099 case FK_AddressOfUnaddressableFunction: {
7100 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7101 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7102 Args[0]->getLocStart());
7103 break;
7104 }
7105
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007106 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00007107 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007108 switch (FailedOverloadResult) {
7109 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00007110 if (Failure == FK_UserConversionOverloadFailed)
7111 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7112 << Args[0]->getType() << DestType
7113 << Args[0]->getSourceRange();
7114 else
7115 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7116 << DestType << Args[0]->getType()
7117 << Args[0]->getSourceRange();
7118
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007119 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007120 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007121
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007122 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00007123 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007124 DestType.getNonReferenceType(),
7125 diag::err_typecheck_nonviable_condition_incomplete,
7126 Args[0]->getType(), Args[0]->getSourceRange()))
7127 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00007128 << (Entity.getKind() == InitializedEntity::EK_Result)
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007129 << Args[0]->getType() << Args[0]->getSourceRange()
7130 << DestType.getNonReferenceType();
7131
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007132 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007133 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007134
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007135 case OR_Deleted: {
7136 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7137 << Args[0]->getType() << DestType.getNonReferenceType()
7138 << Args[0]->getSourceRange();
7139 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007140 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00007141 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
7142 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007143 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00007144 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007145 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007146 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007147 }
7148 break;
7149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007150
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007151 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007152 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007153 }
7154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007155
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007156 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00007157 if (isa<InitListExpr>(Args[0])) {
7158 S.Diag(Kind.getLocation(),
7159 diag::err_lvalue_reference_bind_to_initlist)
7160 << DestType.getNonReferenceType().isVolatileQualified()
7161 << DestType.getNonReferenceType()
7162 << Args[0]->getSourceRange();
7163 break;
7164 }
7165 // Intentional fallthrough
7166
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007167 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007168 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007169 Failure == FK_NonConstLValueReferenceBindingToTemporary
7170 ? diag::err_lvalue_reference_bind_to_temporary
7171 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00007172 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007173 << DestType.getNonReferenceType()
7174 << Args[0]->getType()
7175 << Args[0]->getSourceRange();
7176 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007178 case FK_RValueReferenceBindingToLValue:
7179 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00007180 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007181 << Args[0]->getSourceRange();
7182 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183
Richard Trieuf956a492015-05-16 01:27:03 +00007184 case FK_ReferenceInitDropsQualifiers: {
7185 QualType SourceType = Args[0]->getType();
7186 QualType NonRefType = DestType.getNonReferenceType();
7187 Qualifiers DroppedQualifiers =
7188 SourceType.getQualifiers() - NonRefType.getQualifiers();
7189
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007190 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00007191 << SourceType
7192 << NonRefType
7193 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007194 << Args[0]->getSourceRange();
7195 break;
Richard Trieuf956a492015-05-16 01:27:03 +00007196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007197
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007198 case FK_ReferenceInitFailed:
7199 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7200 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00007201 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007202 << Args[0]->getType()
7203 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00007204 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007205 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007206
Douglas Gregorb491ed32011-02-19 21:32:49 +00007207 case FK_ConversionFailed: {
7208 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00007209 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00007210 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007211 << DestType
John McCall086a4642010-11-24 05:12:34 +00007212 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00007213 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007214 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00007215 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7216 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00007217 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00007218 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007219 }
John Wiegley01296292011-04-08 18:41:53 +00007220
7221 case FK_ConversionFromPropertyFailed:
7222 // No-op. This error has already been reported.
7223 break;
7224
Douglas Gregor51e77d52009-12-10 17:56:55 +00007225 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00007226 SourceRange R;
7227
David Majnemerbd385442015-04-10 04:52:06 +00007228 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007229 if (InitList && InitList->getNumInits() >= 1) {
David Majnemerbd385442015-04-10 04:52:06 +00007230 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007231 } else {
7232 assert(Args.size() > 1 && "Expected multiple initializers!");
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007233 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007234 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007235
Alp Tokerb6cc5922014-05-03 03:45:55 +00007236 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00007237 if (Kind.isCStyleOrFunctionalCast())
7238 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7239 << R;
7240 else
7241 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7242 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007243 break;
7244 }
7245
7246 case FK_ReferenceBindingToInitList:
7247 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7248 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7249 break;
7250
7251 case FK_InitListBadDestinationType:
7252 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7253 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7254 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007255
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007256 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007257 case FK_ConstructorOverloadFailed: {
7258 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007259 if (Args.size())
7260 ArgsRange = SourceRange(Args.front()->getLocStart(),
7261 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007262
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007263 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00007264 assert(Args.size() == 1 &&
7265 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007266 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007267 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007268 }
7269
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007270 // FIXME: Using "DestType" for the entity we're printing is probably
7271 // bad.
7272 switch (FailedOverloadResult) {
7273 case OR_Ambiguous:
7274 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7275 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007276 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007277 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007278
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007279 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007280 if (Kind.getKind() == InitializationKind::IK_Default &&
7281 (Entity.getKind() == InitializedEntity::EK_Base ||
7282 Entity.getKind() == InitializedEntity::EK_Member) &&
7283 isa<CXXConstructorDecl>(S.CurContext)) {
7284 // This is implicit default initialization of a member or
7285 // base within a constructor. If no viable function was
7286 // found, notify the user that she needs to explicitly
7287 // initialize this base/member.
7288 CXXConstructorDecl *Constructor
7289 = cast<CXXConstructorDecl>(S.CurContext);
7290 if (Entity.getKind() == InitializedEntity::EK_Base) {
7291 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007292 << (Constructor->getInheritedConstructor() ? 2 :
7293 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007294 << S.Context.getTypeDeclType(Constructor->getParent())
7295 << /*base=*/0
7296 << Entity.getType();
7297
7298 RecordDecl *BaseDecl
7299 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7300 ->getDecl();
7301 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7302 << S.Context.getTagDeclType(BaseDecl);
7303 } else {
7304 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007305 << (Constructor->getInheritedConstructor() ? 2 :
7306 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007307 << S.Context.getTypeDeclType(Constructor->getParent())
7308 << /*member=*/1
7309 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00007310 S.Diag(Entity.getDecl()->getLocation(),
7311 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007312
7313 if (const RecordType *Record
7314 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007315 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007316 diag::note_previous_decl)
7317 << S.Context.getTagDeclType(Record->getDecl());
7318 }
7319 break;
7320 }
7321
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007322 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7323 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007324 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007325 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007326
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007327 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007328 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007329 OverloadingResult Ovl
7330 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00007331 if (Ovl != OR_Deleted) {
7332 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7333 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007334 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00007335 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007336 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00007337
7338 // If this is a defaulted or implicitly-declared function, then
7339 // it was implicitly deleted. Make it clear that the deletion was
7340 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00007341 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007342 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00007343 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007344 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00007345 else
7346 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7347 << true << DestType << ArgsRange;
7348
7349 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007350 break;
7351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007352
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007353 case OR_Success:
7354 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007355 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007356 }
David Blaikie60deeee2012-01-17 08:24:58 +00007357 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007358
Douglas Gregor85dabae2009-12-16 01:38:02 +00007359 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007360 if (Entity.getKind() == InitializedEntity::EK_Member &&
7361 isa<CXXConstructorDecl>(S.CurContext)) {
7362 // This is implicit default-initialization of a const member in
7363 // a constructor. Complain that it needs to be explicitly
7364 // initialized.
7365 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7366 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007367 << (Constructor->getInheritedConstructor() ? 2 :
7368 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007369 << S.Context.getTypeDeclType(Constructor->getParent())
7370 << /*const=*/1
7371 << Entity.getName();
7372 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7373 << Entity.getName();
7374 } else {
7375 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00007376 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007377 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00007378 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007379
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007380 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00007381 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007382 diag::err_init_incomplete_type);
7383 break;
7384
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007385 case FK_ListInitializationFailed: {
7386 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00007387 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7388 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007389 break;
7390 }
John McCall4124c492011-10-17 18:40:02 +00007391
7392 case FK_PlaceholderType: {
7393 // FIXME: Already diagnosed!
7394 break;
7395 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00007396
Sebastian Redl048a6d72012-04-01 19:54:59 +00007397 case FK_ExplicitConstructor: {
7398 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7399 << Args[0]->getSourceRange();
7400 OverloadCandidateSet::iterator Best;
7401 OverloadingResult Ovl
7402 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00007403 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007404 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7405 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
7406 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
7407 break;
7408 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007410
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007411 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007412 return true;
7413}
Douglas Gregore1314a62009-12-18 05:02:21 +00007414
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007415void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007416 switch (SequenceKind) {
7417 case FailedSequence: {
7418 OS << "Failed sequence: ";
7419 switch (Failure) {
7420 case FK_TooManyInitsForReference:
7421 OS << "too many initializers for reference";
7422 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007423
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007424 case FK_ArrayNeedsInitList:
7425 OS << "array requires initializer list";
7426 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007427
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007428 case FK_AddressOfUnaddressableFunction:
7429 OS << "address of unaddressable function was taken";
7430 break;
7431
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007432 case FK_ArrayNeedsInitListOrStringLiteral:
7433 OS << "array requires initializer list or string literal";
7434 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007435
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007436 case FK_ArrayNeedsInitListOrWideStringLiteral:
7437 OS << "array requires initializer list or wide string literal";
7438 break;
7439
7440 case FK_NarrowStringIntoWideCharArray:
7441 OS << "narrow string into wide char array";
7442 break;
7443
7444 case FK_WideStringIntoCharArray:
7445 OS << "wide string into char array";
7446 break;
7447
7448 case FK_IncompatWideStringIntoWideChar:
7449 OS << "incompatible wide string into wide char array";
7450 break;
7451
Douglas Gregore2f943b2011-02-22 18:29:51 +00007452 case FK_ArrayTypeMismatch:
7453 OS << "array type mismatch";
7454 break;
7455
7456 case FK_NonConstantArrayInit:
7457 OS << "non-constant array initializer";
7458 break;
7459
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007460 case FK_AddressOfOverloadFailed:
7461 OS << "address of overloaded function failed";
7462 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007463
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007464 case FK_ReferenceInitOverloadFailed:
7465 OS << "overload resolution for reference initialization failed";
7466 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007467
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007468 case FK_NonConstLValueReferenceBindingToTemporary:
7469 OS << "non-const lvalue reference bound to temporary";
7470 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007471
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007472 case FK_NonConstLValueReferenceBindingToUnrelated:
7473 OS << "non-const lvalue reference bound to unrelated type";
7474 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007475
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007476 case FK_RValueReferenceBindingToLValue:
7477 OS << "rvalue reference bound to an lvalue";
7478 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007479
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007480 case FK_ReferenceInitDropsQualifiers:
7481 OS << "reference initialization drops qualifiers";
7482 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007483
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007484 case FK_ReferenceInitFailed:
7485 OS << "reference initialization failed";
7486 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007487
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007488 case FK_ConversionFailed:
7489 OS << "conversion failed";
7490 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007491
John Wiegley01296292011-04-08 18:41:53 +00007492 case FK_ConversionFromPropertyFailed:
7493 OS << "conversion from property failed";
7494 break;
7495
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007496 case FK_TooManyInitsForScalar:
7497 OS << "too many initializers for scalar";
7498 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007499
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007500 case FK_ReferenceBindingToInitList:
7501 OS << "referencing binding to initializer list";
7502 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007503
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007504 case FK_InitListBadDestinationType:
7505 OS << "initializer list for non-aggregate, non-scalar type";
7506 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007507
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007508 case FK_UserConversionOverloadFailed:
7509 OS << "overloading failed for user-defined conversion";
7510 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007511
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007512 case FK_ConstructorOverloadFailed:
7513 OS << "constructor overloading failed";
7514 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007516 case FK_DefaultInitOfConst:
7517 OS << "default initialization of a const variable";
7518 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007519
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00007520 case FK_Incomplete:
7521 OS << "initialization of incomplete type";
7522 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007523
7524 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007525 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00007526 break;
7527
John McCalla59dc2f2012-01-05 00:13:19 +00007528 case FK_VariableLengthArrayHasInitializer:
7529 OS << "variable length array has an initializer";
7530 break;
7531
John McCall4124c492011-10-17 18:40:02 +00007532 case FK_PlaceholderType:
7533 OS << "initializer expression isn't contextually valid";
7534 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00007535
7536 case FK_ListConstructorOverloadFailed:
7537 OS << "list constructor overloading failed";
7538 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007539
Sebastian Redl048a6d72012-04-01 19:54:59 +00007540 case FK_ExplicitConstructor:
7541 OS << "list copy initialization chose explicit constructor";
7542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007543 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007544 OS << '\n';
7545 return;
7546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007547
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007548 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007549 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007550 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007551
Sebastian Redld201edf2011-06-05 13:59:11 +00007552 case NormalSequence:
7553 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007554 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007557 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7558 if (S != step_begin()) {
7559 OS << " -> ";
7560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007561
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007562 switch (S->Kind) {
7563 case SK_ResolveAddressOfOverloadedFunction:
7564 OS << "resolve address of overloaded function";
7565 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007566
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007567 case SK_CastDerivedToBaseRValue:
7568 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7569 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007570
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007571 case SK_CastDerivedToBaseXValue:
7572 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7573 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007574
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007575 case SK_CastDerivedToBaseLValue:
7576 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7577 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007579 case SK_BindReference:
7580 OS << "bind reference to lvalue";
7581 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007582
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007583 case SK_BindReferenceToTemporary:
7584 OS << "bind reference to a temporary";
7585 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007586
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007587 case SK_ExtraneousCopyToTemporary:
7588 OS << "extraneous C++03 copy to temporary";
7589 break;
7590
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007591 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007592 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007593 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007594
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007595 case SK_QualificationConversionRValue:
7596 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007597 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007598
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007599 case SK_QualificationConversionXValue:
7600 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007601 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007602
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007603 case SK_QualificationConversionLValue:
7604 OS << "qualification conversion (lvalue)";
7605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007606
Richard Smith77be48a2014-07-31 06:31:19 +00007607 case SK_AtomicConversion:
7608 OS << "non-atomic-to-atomic conversion";
7609 break;
7610
Jordan Roseb1312a52013-04-11 00:58:58 +00007611 case SK_LValueToRValue:
7612 OS << "load (lvalue to rvalue)";
7613 break;
7614
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007615 case SK_ConversionSequence:
7616 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007617 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007618 OS << ")";
7619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007620
Richard Smithaaa0ec42013-09-21 21:19:19 +00007621 case SK_ConversionSequenceNoNarrowing:
7622 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007623 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007624 OS << ")";
7625 break;
7626
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007627 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007628 OS << "list aggregate initialization";
7629 break;
7630
Sebastian Redl29526f02011-11-27 16:50:07 +00007631 case SK_UnwrapInitList:
7632 OS << "unwrap reference initializer list";
7633 break;
7634
7635 case SK_RewrapInitList:
7636 OS << "rewrap reference initializer list";
7637 break;
7638
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007639 case SK_ConstructorInitialization:
7640 OS << "constructor initialization";
7641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007642
Richard Smith53324112014-07-16 21:33:43 +00007643 case SK_ConstructorInitializationFromList:
7644 OS << "list initialization via constructor";
7645 break;
7646
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007647 case SK_ZeroInitialization:
7648 OS << "zero initialization";
7649 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007650
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007651 case SK_CAssignment:
7652 OS << "C assignment";
7653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007654
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007655 case SK_StringInit:
7656 OS << "string initialization";
7657 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007658
7659 case SK_ObjCObjectConversion:
7660 OS << "Objective-C object conversion";
7661 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007662
7663 case SK_ArrayInit:
7664 OS << "array initialization";
7665 break;
John McCall31168b02011-06-15 23:02:42 +00007666
Richard Smithebeed412012-02-15 22:38:09 +00007667 case SK_ParenthesizedArrayInit:
7668 OS << "parenthesized array initialization";
7669 break;
7670
John McCall31168b02011-06-15 23:02:42 +00007671 case SK_PassByIndirectCopyRestore:
7672 OS << "pass by indirect copy and restore";
7673 break;
7674
7675 case SK_PassByIndirectRestore:
7676 OS << "pass by indirect restore";
7677 break;
7678
7679 case SK_ProduceObjCObject:
7680 OS << "Objective-C object retension";
7681 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007682
7683 case SK_StdInitializerList:
7684 OS << "std::initializer_list from initializer list";
7685 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007686
Richard Smithf8adcdc2014-07-17 05:12:35 +00007687 case SK_StdInitializerListConstructorCall:
7688 OS << "list initialization from std::initializer_list";
7689 break;
7690
Guy Benyei61054192013-02-07 10:55:47 +00007691 case SK_OCLSamplerInit:
7692 OS << "OpenCL sampler_t from integer constant";
7693 break;
7694
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007695 case SK_OCLZeroEvent:
7696 OS << "OpenCL event_t from zero";
7697 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007698 }
Richard Smith6b216962013-02-05 05:52:24 +00007699
7700 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007701 }
Richard Smith6b216962013-02-05 05:52:24 +00007702
7703 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007704}
7705
7706void InitializationSequence::dump() const {
7707 dump(llvm::errs());
7708}
7709
Richard Smithaaa0ec42013-09-21 21:19:19 +00007710static void DiagnoseNarrowingInInitList(Sema &S,
7711 const ImplicitConversionSequence &ICS,
7712 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007713 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007714 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007715 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007716 switch (ICS.getKind()) {
7717 case ImplicitConversionSequence::StandardConversion:
7718 SCS = &ICS.Standard;
7719 break;
7720 case ImplicitConversionSequence::UserDefinedConversion:
7721 SCS = &ICS.UserDefined.After;
7722 break;
7723 case ImplicitConversionSequence::AmbiguousConversion:
7724 case ImplicitConversionSequence::EllipsisConversion:
7725 case ImplicitConversionSequence::BadConversion:
7726 return;
7727 }
7728
Richard Smith66e05fe2012-01-18 05:21:49 +00007729 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7730 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007731 QualType ConstantType;
7732 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7733 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007734 case NK_Not_Narrowing:
7735 // No narrowing occurred.
7736 return;
7737
7738 case NK_Type_Narrowing:
7739 // This was a floating-to-integer conversion, which is always considered a
7740 // narrowing conversion even if the value is a constant and can be
7741 // represented exactly as an integer.
7742 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007743 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7744 ? diag::warn_init_list_type_narrowing
7745 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007746 << PostInit->getSourceRange()
7747 << PreNarrowingType.getLocalUnqualifiedType()
7748 << EntityType.getLocalUnqualifiedType();
7749 break;
7750
7751 case NK_Constant_Narrowing:
7752 // A constant value was narrowed.
7753 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007754 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7755 ? diag::warn_init_list_constant_narrowing
7756 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007757 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007758 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007759 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007760 break;
7761
7762 case NK_Variable_Narrowing:
7763 // A variable's value may have been narrowed.
7764 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007765 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7766 ? diag::warn_init_list_variable_narrowing
7767 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007768 << PostInit->getSourceRange()
7769 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007770 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007771 break;
7772 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007773
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007774 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007775 llvm::raw_svector_ostream OS(StaticCast);
7776 OS << "static_cast<";
7777 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7778 // It's important to use the typedef's name if there is one so that the
7779 // fixit doesn't break code using types like int64_t.
7780 //
7781 // FIXME: This will break if the typedef requires qualification. But
7782 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007783 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007784 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007785 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007786 else {
7787 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7788 // with a broken cast.
7789 return;
7790 }
7791 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007792 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007793 << PostInit->getSourceRange()
7794 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7795 << FixItHint::CreateInsertion(
7796 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007797}
7798
Douglas Gregore1314a62009-12-18 05:02:21 +00007799//===----------------------------------------------------------------------===//
7800// Initialization helper functions
7801//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007802bool
7803Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7804 ExprResult Init) {
7805 if (Init.isInvalid())
7806 return false;
7807
7808 Expr *InitE = Init.get();
7809 assert(InitE && "No initialization expression");
7810
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007811 InitializationKind Kind
7812 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007813 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007814 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007815}
7816
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007817ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007818Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7819 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007820 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007821 bool TopLevelOfInitList,
7822 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007823 if (Init.isInvalid())
7824 return ExprError();
7825
John McCall1f425642010-11-11 03:21:53 +00007826 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007827 assert(InitE && "No initialization expression?");
7828
7829 if (EqualLoc.isInvalid())
7830 EqualLoc = InitE->getLocStart();
7831
7832 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007833 EqualLoc,
7834 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007835 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007836
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007837 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007838
Richard Smith66e05fe2012-01-18 05:21:49 +00007839 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007840}