blob: f4687fe818a978e773622fc3a9fb8ccc7d44b163 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Steve Narofff8ecff22008-05-01 22:18:59 +000014#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000016#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000017#include "clang/AST/ExprObjC.h"
Richard Smithafe48f92018-07-23 21:21:22 +000018#include "clang/AST/ExprOpenMP.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"
Mehdi Amini9670f842016-07-18 19:02:11 +000022#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Lookup.h"
24#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000025#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000026#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000028#include "llvm/Support/raw_ostream.h"
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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000036/// Check whether T is compatible with a wide character type (wchar_t,
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000037/// 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,
Richard Smith3a8244d2018-05-01 05:02:45 +000053 SIF_UTF8StringIntoPlainChar,
54 SIF_PlainStringIntoUTF8Char,
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000055 SIF_Other
56};
57
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058/// Check whether the array of type AT can be initialized by the Init
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000059/// expression by means of string initialization. Returns SIF_None if so,
60/// otherwise returns a StringInitFailureKind that describes why the
61/// initialization would not work.
62static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
63 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000064 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000065 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // See if this is a string literal or @encode.
68 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattnera9196812009-02-26 23:26:43 +000070 // Handle @encode, which is a narrow string.
71 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000072 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000073
74 // Otherwise we can only handle string literals.
75 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000076 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000077 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000078
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000079 const QualType ElemTy =
80 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000081
82 switch (SL->getKind()) {
Douglas Gregorfb65e592011-07-27 05:40:30 +000083 case StringLiteral::UTF8:
Richard Smith3a8244d2018-05-01 05:02:45 +000084 // char8_t array can be initialized with a UTF-8 string.
85 if (ElemTy->isChar8Type())
86 return SIF_None;
87 LLVM_FALLTHROUGH;
88 case StringLiteral::Ascii:
Douglas Gregorfb65e592011-07-27 05:40:30 +000089 // char array can be initialized with a narrow string.
90 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000091 if (ElemTy->isCharType())
Richard Smith3a8244d2018-05-01 05:02:45 +000092 return (SL->getKind() == StringLiteral::UTF8 &&
93 Context.getLangOpts().Char8)
94 ? SIF_UTF8StringIntoPlainChar
95 : SIF_None;
96 if (ElemTy->isChar8Type())
97 return SIF_PlainStringIntoUTF8Char;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000098 if (IsWideCharCompatible(ElemTy, Context))
99 return SIF_NarrowStringIntoWideChar;
100 return SIF_Other;
101 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
102 // "An array with element type compatible with a qualified or unqualified
103 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
104 // string literal with the corresponding encoding prefix (L, u, or U,
105 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +0000106 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000107 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
108 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000109 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000110 return SIF_WideStringIntoChar;
111 if (IsWideCharCompatible(ElemTy, Context))
112 return SIF_IncompatWideStringIntoWideChar;
113 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000114 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000115 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
116 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000117 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000118 return SIF_WideStringIntoChar;
119 if (IsWideCharCompatible(ElemTy, Context))
120 return SIF_IncompatWideStringIntoWideChar;
121 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000122 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000123 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
124 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000125 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 return SIF_WideStringIntoChar;
127 if (IsWideCharCompatible(ElemTy, Context))
128 return SIF_IncompatWideStringIntoWideChar;
129 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Douglas Gregorfb65e592011-07-27 05:40:30 +0000132 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000133}
134
Hans Wennborg950f3182013-05-16 09:22:40 +0000135static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
136 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000137 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000138 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000139 return SIF_Other;
140 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000141}
142
Richard Smith430c23b2013-05-05 16:40:13 +0000143/// Update the type of a string literal, including any surrounding parentheses,
144/// to match the type of the object which it is initializing.
145static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000146 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000147 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000148 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
149 break;
150 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
151 E = PE->getSubExpr();
152 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
153 E = UO->getSubExpr();
154 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
155 E = GSE->getResultExpr();
156 else
157 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000158 }
Richard Smith430c23b2013-05-05 16:40:13 +0000159}
160
John McCall5decec92011-02-21 07:57:55 +0000161static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
162 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000163 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000164 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000165 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000166 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattner0cb78032009-02-24 22:27:37 +0000168 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000169 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000170 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000171 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000172 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000173 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
174 ConstVal,
175 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000176 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000177 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000178 }
Mike Stump11289f42009-09-09 15:08:12 +0000179
Eli Friedman893abe42009-05-29 18:22:49 +0000180 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Eli Friedman554eba92011-04-11 00:23:45 +0000182 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000183 // the size may be smaller or larger than the string we are initializing.
184 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000185 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000186 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000187 // For Pascal strings it's OK to strip off the terminating null character,
188 // so the example below is valid:
189 //
190 // unsigned char a[2] = "\pa";
191 if (SL->isPascal())
192 StrLength--;
193 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000194
Eli Friedman554eba92011-04-11 00:23:45 +0000195 // [dcl.init.string]p2
196 if (StrLength > CAT->getSize().getZExtValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000197 S.Diag(Str->getBeginLoc(),
Eli Friedman554eba92011-04-11 00:23:45 +0000198 diag::err_initializer_string_for_char_array_too_long)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000199 << Str->getSourceRange();
Eli Friedman554eba92011-04-11 00:23:45 +0000200 } else {
201 // C99 6.7.8p14.
202 if (StrLength-1 > CAT->getSize().getZExtValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000203 S.Diag(Str->getBeginLoc(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000204 diag::ext_initializer_string_for_char_array_too_long)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000205 << Str->getSourceRange();
Eli Friedman554eba92011-04-11 00:23:45 +0000206 }
Mike Stump11289f42009-09-09 15:08:12 +0000207
Eli Friedman893abe42009-05-29 18:22:49 +0000208 // Set the type to the actual size that we are initializing. If we have
209 // something like:
210 // char x[1] = "foo";
211 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000212 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000213}
214
Chris Lattner0cb78032009-02-24 22:27:37 +0000215//===----------------------------------------------------------------------===//
216// Semantic checking for initializer lists.
217//===----------------------------------------------------------------------===//
218
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000219namespace {
220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// Semantic checking for initializer lists.
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222///
223/// The InitListChecker class contains a set of routines that each
224/// handle the initialization of a certain kind of entity, e.g.,
225/// arrays, vectors, struct/union types, scalars, etc. The
226/// InitListChecker itself performs a recursive walk of the subobject
227/// structure of the type to be initialized, while stepping through
228/// the initializer list one element at a time. The IList and Index
229/// parameters to each of the Check* routines contain the active
230/// (syntactic) initializer list and the index into that initializer
231/// list that represents the current initializer. Each routine is
232/// responsible for moving that Index forward as it consumes elements.
233///
234/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000235/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000236/// initializer list and the index into that initializer list where we
237/// are copying initializers as we map them over to the semantic
238/// list. Once we have completed our recursive walk of the subobject
239/// structure, we will have constructed a full semantic initializer
240/// list.
241///
242/// C99 designators cause changes in the initializer list traversal,
243/// because they make the initialization "jump" into a specific
244/// subobject and then continue the initialization from that
245/// point. CheckDesignatedInitializer() recursively steps into the
246/// designated subobject and manages backing out the recursion to
247/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000248class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000249 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000251 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000252 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000253 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000254 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000255
Anders Carlsson6cabf312010-01-23 23:23:01 +0000256 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000257 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000258 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000259 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000260 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000261 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000262 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000263 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000264 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000265 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000266 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000267 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000268 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000269 unsigned &StructuredIndex,
270 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000271 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000272 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000273 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000274 InitListExpr *StructuredList,
275 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000276 void CheckComplexType(const InitializedEntity &Entity,
277 InitListExpr *IList, QualType DeclType,
278 unsigned &Index,
279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000282 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000283 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000284 InitListExpr *StructuredList,
285 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000286 void CheckReferenceType(const InitializedEntity &Entity,
287 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000288 unsigned &Index,
289 InitListExpr *StructuredList,
290 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000291 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000292 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000293 InitListExpr *StructuredList,
294 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000295 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000296 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000297 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000298 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000299 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000300 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000301 unsigned &StructuredIndex,
302 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000303 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000304 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000305 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000306 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000309 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000310 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000311 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000312 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000313 RecordDecl::field_iterator *NextField,
314 llvm::APSInt *NextElementIndex,
315 unsigned &Index,
316 InitListExpr *StructuredList,
317 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000318 bool FinishSubobjectInit,
319 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000320 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
321 QualType CurrentObjectType,
322 InitListExpr *StructuredList,
323 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000324 SourceRange InitRange,
325 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000326 void UpdateStructuredListElement(InitListExpr *StructuredList,
327 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000328 Expr *expr);
329 int numArrayElements(QualType DeclType);
330 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000331
Richard Smith454a7cd2014-06-03 08:26:00 +0000332 static ExprResult PerformEmptyInit(Sema &SemaRef,
333 SourceLocation Loc,
334 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000335 bool VerifyOnly,
336 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000337
338 // Explanation on the "FillWithNoInit" mode:
339 //
340 // Assume we have the following definitions (Case#1):
341 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
342 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
343 //
344 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
345 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
346 //
347 // But if we have (Case#2):
348 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
349 //
350 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
351 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
352 //
353 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
354 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
355 // initializers but with special "NoInitExpr" place holders, which tells the
356 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000357 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
358 const InitializedEntity &ParentEntity,
359 InitListExpr *ILE, bool &RequiresSecondPass,
360 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000361 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000362 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000363 InitListExpr *ILE, bool &RequiresSecondPass,
364 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000365 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000366 InitListExpr *ILE, bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000367 InitListExpr *OuterILE, unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000368 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000369 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
370 Expr *InitExpr, FieldDecl *Field,
371 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000372 void CheckEmptyInitializable(const InitializedEntity &Entity,
373 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000374
Douglas Gregor85df8d82009-01-29 00:45:39 +0000375public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000376 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000377 InitListExpr *IL, QualType &T, bool VerifyOnly,
378 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000379 bool HadError() { return hadError; }
380
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000381 // Retrieves the fully-structured initializer list used for
Douglas Gregor85df8d82009-01-29 00:45:39 +0000382 // semantic analysis and code generation.
383 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
384};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000385
Chris Lattner9ececce2009-02-24 22:48:58 +0000386} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000387
Richard Smith454a7cd2014-06-03 08:26:00 +0000388ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
389 SourceLocation Loc,
390 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000391 bool VerifyOnly,
392 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000393 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
394 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000395 MultiExprArg SubInit;
396 Expr *InitExpr;
397 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
398
399 // C++ [dcl.init.aggr]p7:
400 // If there are fewer initializer-clauses in the list than there are
401 // members in the aggregate, then each member not explicitly initialized
402 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000403 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
404 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
405 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000406 // C++1y / DR1070:
407 // shall be initialized [...] from an empty initializer list.
408 //
409 // We apply the resolution of this DR to C++11 but not C++98, since C++98
410 // does not have useful semantics for initialization from an init list.
411 // We treat this as copy-initialization, because aggregate initialization
412 // always performs copy-initialization on its elements.
413 //
414 // Only do this if we're initializing a class type, to avoid filling in
415 // the initializer list where possible.
416 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
417 InitListExpr(SemaRef.Context, Loc, None, Loc);
418 InitExpr->setType(SemaRef.Context.VoidTy);
419 SubInit = InitExpr;
420 Kind = InitializationKind::CreateCopy(Loc, Loc);
421 } else {
422 // C++03:
423 // shall be value-initialized.
424 }
425
426 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000427 // libstdc++4.6 marks the vector default constructor as explicit in
428 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
429 // stlport does so too. Look for std::__debug for libstdc++, and for
430 // std:: for stlport. This is effectively a compiler-side implementation of
431 // LWG2193.
432 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
433 InitializationSequence::FK_ExplicitConstructor) {
434 OverloadCandidateSet::iterator Best;
435 OverloadingResult O =
436 InitSeq.getFailedCandidateSet()
437 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
438 (void)O;
439 assert(O == OR_Success && "Inconsistent overload resolution");
440 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
441 CXXRecordDecl *R = CtorDecl->getParent();
442
443 if (CtorDecl->getMinRequiredArguments() == 0 &&
444 CtorDecl->isExplicit() && R->getDeclName() &&
445 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000446 bool IsInStd = false;
447 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000448 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000449 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
450 IsInStd = true;
451 }
452
Fangrui Song6907ce22018-07-30 19:24:48 +0000453 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
Nico Weberbcb70ee2014-07-02 23:51:09 +0000454 .Cases("basic_string", "deque", "forward_list", true)
455 .Cases("list", "map", "multimap", "multiset", true)
456 .Cases("priority_queue", "queue", "set", "stack", true)
457 .Cases("unordered_map", "unordered_set", "vector", true)
458 .Default(false)) {
459 InitSeq.InitializeFrom(
460 SemaRef, Entity,
461 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000462 MultiExprArg(), /*TopLevelOfInitList=*/false,
463 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000464 // Emit a warning for this. System header warnings aren't shown
465 // by default, but people working on system headers should see it.
466 if (!VerifyOnly) {
467 SemaRef.Diag(CtorDecl->getLocation(),
468 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000469 if (Entity.getKind() == InitializedEntity::EK_Member)
470 SemaRef.Diag(Entity.getDecl()->getLocation(),
471 diag::note_used_in_initialization_here);
472 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
473 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000474 }
475 }
476 }
477 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000478 if (!InitSeq) {
479 if (!VerifyOnly) {
480 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
481 if (Entity.getKind() == InitializedEntity::EK_Member)
482 SemaRef.Diag(Entity.getDecl()->getLocation(),
483 diag::note_in_omitted_aggregate_initializer)
484 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000485 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
486 bool IsTrailingArrayNewMember =
487 Entity.getParent() &&
488 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000489 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000490 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
491 << Entity.getElementIndex();
492 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000493 }
494 return ExprError();
495 }
496
497 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
498 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
499}
500
501void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
502 SourceLocation Loc) {
503 assert(VerifyOnly &&
504 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000505 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
506 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000507 hadError = true;
508}
509
Richard Smith872307e2016-03-08 22:17:41 +0000510void InitListChecker::FillInEmptyInitForBase(
511 unsigned Init, const CXXBaseSpecifier &Base,
512 const InitializedEntity &ParentEntity, InitListExpr *ILE,
513 bool &RequiresSecondPass, bool FillWithNoInit) {
514 assert(Init < ILE->getNumInits() && "should have been expanded");
515
516 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
517 SemaRef.Context, &Base, false, &ParentEntity);
518
519 if (!ILE->getInit(Init)) {
520 ExprResult BaseInit =
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000521 FillWithNoInit
522 ? new (SemaRef.Context) NoInitExpr(Base.getType())
523 : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
524 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000525 if (BaseInit.isInvalid()) {
526 hadError = true;
527 return;
528 }
529
530 ILE->setInit(Init, BaseInit.getAs<Expr>());
531 } else if (InitListExpr *InnerILE =
532 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
Richard Smithf3b4ca82018-02-07 22:25:16 +0000533 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
534 ILE, Init, FillWithNoInit);
Richard Smith872307e2016-03-08 22:17:41 +0000535 } else if (DesignatedInitUpdateExpr *InnerDIUE =
536 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
537 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000538 RequiresSecondPass, ILE, Init,
539 /*FillWithNoInit =*/true);
Richard Smith872307e2016-03-08 22:17:41 +0000540 }
541}
542
Richard Smith454a7cd2014-06-03 08:26:00 +0000543void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000544 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000545 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000546 bool &RequiresSecondPass,
547 bool FillWithNoInit) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000548 SourceLocation Loc = ILE->getEndLoc();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000549 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000551 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000552
553 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
554 if (!RType->getDecl()->isUnion())
555 assert(Init < NumInits && "This ILE should have been expanded");
556
Douglas Gregor2bb07652009-12-22 00:05:34 +0000557 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000558 if (FillWithNoInit) {
559 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
560 if (Init < NumInits)
561 ILE->setInit(Init, Filler);
562 else
563 ILE->updateInit(SemaRef.Context, Init, Filler);
564 return;
565 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000566 // C++1y [dcl.init.aggr]p7:
567 // If there are fewer initializer-clauses in the list than there are
568 // members in the aggregate, then each member not explicitly initialized
569 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000570 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000571 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
572 if (DIE.isInvalid()) {
573 hadError = true;
574 return;
575 }
Richard Smithd87aab92018-07-17 22:24:09 +0000576 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000577 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000578 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000579 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000580 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000581 RequiresSecondPass = true;
582 }
583 return;
584 }
585
Douglas Gregor2bb07652009-12-22 00:05:34 +0000586 if (Field->getType()->isReferenceType()) {
587 // C++ [dcl.init.aggr]p9:
588 // If an incomplete or empty initializer-list leaves a
589 // member of reference type uninitialized, the program is
590 // ill-formed.
591 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
592 << Field->getType()
593 << ILE->getSyntacticForm()->getSourceRange();
594 SemaRef.Diag(Field->getLocation(),
595 diag::note_uninit_reference_member);
596 hadError = true;
597 return;
598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
Richard Smith454a7cd2014-06-03 08:26:00 +0000600 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000601 /*VerifyOnly*/false,
602 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000603 if (MemberInit.isInvalid()) {
604 hadError = true;
605 return;
606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor2bb07652009-12-22 00:05:34 +0000608 if (hadError) {
609 // Do nothing
610 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000611 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000612 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
613 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000614 // extend the initializer list to include the constructor
615 // call and make a note that we'll need to take another pass
616 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000617 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000618 RequiresSecondPass = true;
619 }
620 } else if (InitListExpr *InnerILE
621 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000622 FillInEmptyInitializations(MemberEntity, InnerILE,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000623 RequiresSecondPass, ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000624 else if (DesignatedInitUpdateExpr *InnerDIUE
625 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
626 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000627 RequiresSecondPass, ILE, Init,
628 /*FillWithNoInit =*/true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000629}
630
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000631/// Recursively replaces NULL values within the given initializer list
632/// with expressions that perform value-initialization of the
Richard Smithf3b4ca82018-02-07 22:25:16 +0000633/// appropriate type, and finish off the InitListExpr formation.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634void
Richard Smith454a7cd2014-06-03 08:26:00 +0000635InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000636 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000637 bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000638 InitListExpr *OuterILE,
639 unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000640 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000641 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000642 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000643
Richard Smithf3b4ca82018-02-07 22:25:16 +0000644 // If this is a nested initializer list, we might have changed its contents
645 // (and therefore some of its properties, such as instantiation-dependence)
646 // while filling it in. Inform the outer initializer list so that its state
647 // can be updated to match.
648 // FIXME: We should fully build the inner initializers before constructing
649 // the outer InitListExpr instead of mutating AST nodes after they have
650 // been used as subexpressions of other nodes.
651 struct UpdateOuterILEWithUpdatedInit {
652 InitListExpr *Outer;
653 unsigned OuterIndex;
654 ~UpdateOuterILEWithUpdatedInit() {
655 if (Outer)
656 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
657 }
658 } UpdateOuterRAII = {OuterILE, OuterIndex};
659
Richard Smith382bc512017-02-23 22:41:47 +0000660 // A transparent ILE is not performing aggregate initialization and should
661 // not be filled in.
662 if (ILE->isTransparent())
663 return;
664
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000665 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000666 const RecordDecl *RDecl = RType->getDecl();
667 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000668 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000669 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000670 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
671 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000672 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000673 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000674 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
675 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000676 break;
677 }
678 }
679 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000680 // The fields beyond ILE->getNumInits() are default initialized, so in
681 // order to leave them uninitialized, the ILE is expanded and the extra
682 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000683 unsigned NumElems = numStructUnionElements(ILE->getType());
684 if (RDecl->hasFlexibleArrayMember())
685 ++NumElems;
686 if (ILE->getNumInits() < NumElems)
687 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000688
Douglas Gregor2bb07652009-12-22 00:05:34 +0000689 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000690
691 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
692 for (auto &Base : CXXRD->bases()) {
693 if (hadError)
694 return;
695
696 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
697 FillWithNoInit);
698 ++Init;
699 }
700 }
701
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000702 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000703 if (Field->isUnnamedBitfield())
704 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000705
Douglas Gregor2bb07652009-12-22 00:05:34 +0000706 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000707 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000708
Yunzhong Gaocb779302015-06-10 00:27:52 +0000709 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
710 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000711 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000712 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000713
Douglas Gregor2bb07652009-12-22 00:05:34 +0000714 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000715
Douglas Gregor2bb07652009-12-22 00:05:34 +0000716 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000717 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000718 break;
719 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000720 }
721
722 return;
Mike Stump11289f42009-09-09 15:08:12 +0000723 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000724
725 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000726
Douglas Gregor723796a2009-12-16 06:35:08 +0000727 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000728 unsigned NumInits = ILE->getNumInits();
729 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000730 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000731 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000732 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000733 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000734 // For an array new with an unknown bound, ask for one additional element
735 // in order to populate the array filler.
736 if (Entity.isVariableLengthArrayNew())
737 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000739 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000740 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000741 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000742 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000743 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000744 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000745 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000746 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000747
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000748 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000749 if (hadError)
750 return;
751
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000752 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
753 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000754 ElementEntity.setElementIndex(Init);
755
Richard Smith3e268632018-05-23 23:41:38 +0000756 if (Init >= NumInits && ILE->hasArrayFiller())
757 return;
758
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000760 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
761 ILE->setInit(Init, ILE->getArrayFiller());
762 else if (!InitExpr && !ILE->hasArrayFiller()) {
763 Expr *Filler = nullptr;
764
765 if (FillWithNoInit)
766 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
767 else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000768 ExprResult ElementInit =
769 PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
770 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000771 if (ElementInit.isInvalid()) {
772 hadError = true;
773 return;
774 }
775
776 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000777 }
778
779 if (hadError) {
780 // Do nothing
781 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000782 // For arrays, just set the expression used for value-initialization
783 // of the "holes" in the array.
784 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000785 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000786 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000787 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000788 } else {
789 // For arrays, just set the expression used for value-initialization
790 // of the rest of elements and exit.
791 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000792 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000793 return;
794 }
795
Yunzhong Gaocb779302015-06-10 00:27:52 +0000796 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000797 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000798 // extend the initializer list to include the constructor
799 // call and make a note that we'll need to take another pass
800 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000801 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000802 RequiresSecondPass = true;
803 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000804 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000805 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000806 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000807 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000808 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000809 else if (DesignatedInitUpdateExpr *InnerDIUE
810 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
811 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000812 RequiresSecondPass, ILE, Init,
813 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000814 }
815}
816
Douglas Gregor723796a2009-12-16 06:35:08 +0000817InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000818 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000819 bool VerifyOnly,
820 bool TreatUnavailableAsInvalid)
821 : SemaRef(S), VerifyOnly(VerifyOnly),
822 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000823 // FIXME: Check that IL isn't already the semantic form of some other
824 // InitListExpr. If it is, we'd create a broken AST.
825
Steve Narofff8ecff22008-05-01 22:18:59 +0000826 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000827
Richard Smith4e0d2e42013-09-20 20:10:22 +0000828 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000829 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000830 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000831 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000832
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000833 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000834 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000835 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
836 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000837 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000838 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000839 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000840 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000841}
842
843int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000844 // FIXME: use a proper constant
845 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000846 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000847 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000848 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
849 }
850 return maxElements;
851}
852
853int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000854 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000855 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000856 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
857 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000858 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000859 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000860 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000861
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000862 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000863 return std::min(InitializableMembers, 1);
864 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000865}
866
Richard Smith283e2072017-10-03 20:36:00 +0000867/// Determine whether Entity is an entity for which it is idiomatic to elide
868/// the braces in aggregate initialization.
869static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
870 // Recursive initialization of the one and only field within an aggregate
871 // class is considered idiomatic. This case arises in particular for
872 // initialization of std::array, where the C++ standard suggests the idiom of
873 //
874 // std::array<T, N> arr = {1, 2, 3};
875 //
876 // (where std::array is an aggregate struct containing a single array field.
877
878 // FIXME: Should aggregate initialization of a struct with a single
879 // base class and no members also suppress the warning?
880 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
881 return false;
882
883 auto *ParentRD =
884 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
885 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
886 if (CXXRD->getNumBases())
887 return false;
888
889 auto FieldIt = ParentRD->field_begin();
890 assert(FieldIt != ParentRD->field_end() &&
891 "no fields but have initializer for member?");
892 return ++FieldIt == ParentRD->field_end();
893}
894
Richard Smith4e0d2e42013-09-20 20:10:22 +0000895/// Check whether the range of the initializer \p ParentIList from element
896/// \p Index onwards can be used to initialize an object of type \p T. Update
897/// \p Index to indicate how many elements of the list were consumed.
898///
899/// This also fills in \p StructuredList, from element \p StructuredIndex
900/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000901void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000902 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 QualType T, unsigned &Index,
904 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000905 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000906 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Steve Narofff8ecff22008-05-01 22:18:59 +0000908 if (T->isArrayType())
909 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000910 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000911 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000912 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000913 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000914 else
David Blaikie83d382b2011-09-23 05:06:16 +0000915 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000916
Eli Friedmane0f832b2008-05-25 13:49:22 +0000917 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000918 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000919 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000920 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000921 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000922 hadError = true;
923 return;
924 }
925
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000926 // Build a structured initializer list corresponding to this subobject.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000927 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
928 ParentIList, Index, T, StructuredList, StructuredIndex,
929 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
930 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000931 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000932
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000933 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000934 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000936 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000937 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000938 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000939
Richard Smithde229232013-06-06 11:41:05 +0000940 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000942
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000943 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000944 // Update the structured sub-object initializer so that it's ending
945 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000946 if (EndIndex < ParentIList->getNumInits() &&
947 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000948 SourceLocation EndLoc
949 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
950 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000953 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000954 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000955 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
956 !isIdiomaticBraceElisionEntity(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000957 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
Richard Smithde229232013-06-06 11:41:05 +0000958 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000959 << StructuredSubobjectInitList->getSourceRange()
960 << FixItHint::CreateInsertion(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000961 StructuredSubobjectInitList->getBeginLoc(), "{")
Alp Tokerb6cc5922014-05-03 03:45:55 +0000962 << FixItHint::CreateInsertion(
963 SemaRef.getLocForEndOfToken(
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000964 StructuredSubobjectInitList->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +0000965 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000966 }
Richard Smith79c88c32018-09-26 19:00:16 +0000967
968 // Warn if this type won't be an aggregate in future versions of C++.
969 auto *CXXRD = T->getAsCXXRecordDecl();
970 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
971 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
972 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
973 << StructuredSubobjectInitList->getSourceRange() << T;
974 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000975 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000976}
977
Richard Smith420fa122015-02-12 01:50:05 +0000978/// Warn that \p Entity was of scalar type and was initialized by a
979/// single-element braced initializer list.
980static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
981 SourceRange Braces) {
982 // Don't warn during template instantiation. If the initialization was
983 // non-dependent, we warned during the initial parse; otherwise, the
984 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000985 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000986 return;
987
988 unsigned DiagID = 0;
989
990 switch (Entity.getKind()) {
991 case InitializedEntity::EK_VectorElement:
992 case InitializedEntity::EK_ComplexElement:
993 case InitializedEntity::EK_ArrayElement:
994 case InitializedEntity::EK_Parameter:
995 case InitializedEntity::EK_Parameter_CF_Audited:
996 case InitializedEntity::EK_Result:
997 // Extra braces here are suspicious.
998 DiagID = diag::warn_braces_around_scalar_init;
999 break;
1000
1001 case InitializedEntity::EK_Member:
1002 // Warn on aggregate initialization but not on ctor init list or
1003 // default member initializer.
1004 if (Entity.getParent())
1005 DiagID = diag::warn_braces_around_scalar_init;
1006 break;
1007
1008 case InitializedEntity::EK_Variable:
1009 case InitializedEntity::EK_LambdaCapture:
1010 // No warning, might be direct-list-initialization.
1011 // FIXME: Should we warn for copy-list-initialization in these cases?
1012 break;
1013
1014 case InitializedEntity::EK_New:
1015 case InitializedEntity::EK_Temporary:
1016 case InitializedEntity::EK_CompoundLiteralInit:
1017 // No warning, braces are part of the syntax of the underlying construct.
1018 break;
1019
1020 case InitializedEntity::EK_RelatedResult:
1021 // No warning, we already warned when initializing the result.
1022 break;
1023
1024 case InitializedEntity::EK_Exception:
1025 case InitializedEntity::EK_Base:
1026 case InitializedEntity::EK_Delegating:
1027 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001028 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001029 case InitializedEntity::EK_Binding:
Richard Smith67af95b2018-07-23 19:19:08 +00001030 case InitializedEntity::EK_StmtExprResult:
Richard Smith420fa122015-02-12 01:50:05 +00001031 llvm_unreachable("unexpected braced scalar init");
1032 }
1033
1034 if (DiagID) {
1035 S.Diag(Braces.getBegin(), DiagID)
1036 << Braces
1037 << FixItHint::CreateRemoval(Braces.getBegin())
1038 << FixItHint::CreateRemoval(Braces.getEnd());
1039 }
1040}
1041
Richard Smith4e0d2e42013-09-20 20:10:22 +00001042/// Check whether the initializer \p IList (that was written with explicit
1043/// braces) can be used to initialize an object of type \p T.
1044///
1045/// This also fills in \p StructuredList with the fully-braced, desugared
1046/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001047void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001048 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001049 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001050 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001051 if (!VerifyOnly) {
1052 SyntacticToSemantic[IList] = StructuredList;
1053 StructuredList->setSyntacticForm(IList);
1054 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001055
1056 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001057 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001058 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001059 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001060 QualType ExprTy = T;
1061 if (!ExprTy->isArrayType())
1062 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001063 IList->setType(ExprTy);
1064 StructuredList->setType(ExprTy);
1065 }
Eli Friedman85f54972008-05-25 13:22:35 +00001066 if (hadError)
1067 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001068
Eli Friedman85f54972008-05-25 13:22:35 +00001069 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001070 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001071 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001072 if (SemaRef.getLangOpts().CPlusPlus ||
1073 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001074 IList->getType()->isVectorType())) {
1075 hadError = true;
1076 }
1077 return;
1078 }
1079
Eli Friedmanbd327452009-05-29 20:20:05 +00001080 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001081 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1082 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001083 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001084 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001085 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001086 hadError = true;
1087 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001088 // Special-case
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001089 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1090 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001091 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001092 // Don't complain for incomplete types, since we'll get an error
1093 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001094 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001095 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001096 CurrentObjectType->isArrayType()? 0 :
1097 CurrentObjectType->isVectorType()? 1 :
1098 CurrentObjectType->isScalarType()? 2 :
1099 CurrentObjectType->isUnionType()? 3 :
1100 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001101
Richard Smith1b98ccc2014-07-19 01:39:17 +00001102 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001103 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001104 DK = diag::err_excess_initializers;
1105 hadError = true;
1106 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001107 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001108 DK = diag::err_excess_initializers;
1109 hadError = true;
1110 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001111
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001112 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1113 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001114 }
1115 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001116
Richard Smith79c88c32018-09-26 19:00:16 +00001117 if (!VerifyOnly) {
1118 if (T->isScalarType() && IList->getNumInits() == 1 &&
1119 !isa<InitListExpr>(IList->getInit(0)))
1120 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1121
1122 // Warn if this is a class type that won't be an aggregate in future
1123 // versions of C++.
1124 auto *CXXRD = T->getAsCXXRecordDecl();
1125 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1126 // Don't warn if there's an equivalent default constructor that would be
1127 // used instead.
1128 bool HasEquivCtor = false;
1129 if (IList->getNumInits() == 0) {
1130 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1131 HasEquivCtor = CD && !CD->isDeleted();
1132 }
1133
1134 if (!HasEquivCtor) {
1135 SemaRef.Diag(IList->getBeginLoc(),
1136 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1137 << IList->getSourceRange() << T;
1138 }
1139 }
1140 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001141}
1142
Anders Carlsson6cabf312010-01-23 23:23:01 +00001143void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001144 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001145 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001147 unsigned &Index,
1148 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001149 unsigned &StructuredIndex,
1150 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001151 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1152 // Explicitly braced initializer for complex type can be real+imaginary
1153 // parts.
1154 CheckComplexType(Entity, IList, DeclType, Index,
1155 StructuredList, StructuredIndex);
1156 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001157 CheckScalarType(Entity, IList, DeclType, Index,
1158 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001159 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001160 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001161 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001162 } else if (DeclType->isRecordType()) {
1163 assert(DeclType->isAggregateType() &&
1164 "non-aggregate records should be handed in CheckSubElementType");
1165 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001166 auto Bases =
1167 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1168 CXXRecordDecl::base_class_iterator());
1169 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1170 Bases = CXXRD->bases();
1171 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1172 SubobjectIsDesignatorContext, Index, StructuredList,
1173 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001174 } else if (DeclType->isArrayType()) {
1175 llvm::APSInt Zero(
1176 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1177 false);
1178 CheckArrayType(Entity, IList, DeclType, Zero,
1179 SubobjectIsDesignatorContext, Index,
1180 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001181 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1182 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001183 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001184 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001185 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1186 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001187 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001188 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001189 CheckReferenceType(Entity, IList, DeclType, Index,
1190 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001191 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001192 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001193 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001194 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001195 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001196 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001197 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1198 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001199 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001200 }
1201}
1202
Anders Carlsson6cabf312010-01-23 23:23:01 +00001203void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001204 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001205 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001206 unsigned &Index,
1207 InitListExpr *StructuredList,
1208 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001209 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001210
1211 if (ElemType->isReferenceType())
1212 return CheckReferenceType(Entity, IList, ElemType, Index,
1213 StructuredList, StructuredIndex);
1214
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001215 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001216 if (SubInitList->getNumInits() == 1 &&
1217 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1218 SIF_None) {
1219 expr = SubInitList->getInit(0);
1220 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001221 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001222 = getStructuredSubobjectInit(IList, Index, ElemType,
1223 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001224 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001225 CheckExplicitInitList(Entity, SubInitList, ElemType,
1226 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001227
1228 if (!hadError && !VerifyOnly) {
1229 bool RequiresSecondPass = false;
1230 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001231 RequiresSecondPass, StructuredList,
1232 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001233 if (RequiresSecondPass && !hadError)
1234 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001235 RequiresSecondPass, StructuredList,
1236 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001237 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001238 ++StructuredIndex;
1239 ++Index;
1240 return;
1241 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001242 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001243 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001244 // This happens during template instantiation when we see an InitListExpr
1245 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001246 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001247 "found implicit initialization for the wrong type");
1248 if (!VerifyOnly)
1249 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1250 ++Index;
1251 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001252 }
1253
Richard Smith3c567fc2015-02-12 01:55:09 +00001254 if (SemaRef.getLangOpts().CPlusPlus) {
1255 // C++ [dcl.init.aggr]p2:
1256 // Each member is copy-initialized from the corresponding
1257 // initializer-clause.
1258
1259 // FIXME: Better EqualLoc?
1260 InitializationKind Kind =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001261 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
Richard Smith3c567fc2015-02-12 01:55:09 +00001262 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1263 /*TopLevelOfInitList*/ true);
1264
1265 // C++14 [dcl.init.aggr]p13:
1266 // If the assignment-expression can initialize a member, the member is
1267 // initialized. Otherwise [...] brace elision is assumed
1268 //
1269 // Brace elision is never performed if the element is not an
1270 // assignment-expression.
1271 if (Seq || isa<InitListExpr>(expr)) {
1272 if (!VerifyOnly) {
1273 ExprResult Result =
1274 Seq.Perform(SemaRef, Entity, Kind, expr);
1275 if (Result.isInvalid())
1276 hadError = true;
1277
1278 UpdateStructuredListElement(StructuredList, StructuredIndex,
1279 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001280 } else if (!Seq)
1281 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001282 ++Index;
1283 return;
1284 }
1285
1286 // Fall through for subaggregate initialization
1287 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1288 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001289 return CheckScalarType(Entity, IList, ElemType, Index,
1290 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001291 } else if (const ArrayType *arrayType =
1292 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001293 // arrayType can be incomplete if we're initializing a flexible
1294 // array member. There's nothing we can do with the completed
1295 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001297 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001298 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001299 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1300 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001301 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001302 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001303 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001304 }
John McCall5decec92011-02-21 07:57:55 +00001305
1306 // Fall through for subaggregate initialization.
1307
John McCall5decec92011-02-21 07:57:55 +00001308 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001309 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001310 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001311
John McCall5decec92011-02-21 07:57:55 +00001312 // C99 6.7.8p13:
1313 //
1314 // The initializer for a structure or union object that has
1315 // automatic storage duration shall be either an initializer
1316 // list as described below, or a single expression that has
1317 // compatible structure or union type. In the latter case, the
1318 // initial value of the object, including unnamed members, is
1319 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001320 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001321 if (SemaRef.CheckSingleAssignmentConstraints(
1322 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001323 if (ExprRes.isInvalid())
1324 hadError = true;
1325 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001326 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001327 if (ExprRes.isInvalid())
1328 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001329 }
1330 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001331 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001332 ++Index;
1333 return;
1334 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001335 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001336 // Fall through for subaggregate initialization
1337 }
1338
1339 // C++ [dcl.init.aggr]p12:
1340 //
1341 // [...] Otherwise, if the member is itself a non-empty
1342 // subaggregate, brace elision is assumed and the initializer is
1343 // considered for the initialization of the first member of
1344 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001345 // OpenCL vector initializer is handled elsewhere.
1346 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1347 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001348 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1349 StructuredIndex);
1350 ++StructuredIndex;
1351 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001352 if (!VerifyOnly) {
1353 // We cannot initialize this element, so let
1354 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001355 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001356 /*TopLevelOfInitList=*/true);
1357 }
John McCall5decec92011-02-21 07:57:55 +00001358 hadError = true;
1359 ++Index;
1360 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001361 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001362}
1363
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001364void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1365 InitListExpr *IList, QualType DeclType,
1366 unsigned &Index,
1367 InitListExpr *StructuredList,
1368 unsigned &StructuredIndex) {
1369 assert(Index == 0 && "Index in explicit init list must be zero");
1370
1371 // As an extension, clang supports complex initializers, which initialize
1372 // a complex number component-wise. When an explicit initializer list for
1373 // a complex number contains two two initializers, this extension kicks in:
1374 // it exepcts the initializer list to contain two elements convertible to
1375 // the element type of the complex type. The first element initializes
1376 // the real part, and the second element intitializes the imaginary part.
1377
1378 if (IList->getNumInits() != 2)
1379 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1380 StructuredIndex);
1381
1382 // This is an extension in C. (The builtin _Complex type does not exist
1383 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001384 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001385 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1386 << IList->getSourceRange();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001387
1388 // Initialize the complex number.
1389 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1390 InitializedEntity ElementEntity =
1391 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1392
1393 for (unsigned i = 0; i < 2; ++i) {
1394 ElementEntity.setElementIndex(Index);
1395 CheckSubElementType(ElementEntity, IList, elementType, Index,
1396 StructuredList, StructuredIndex);
1397 }
1398}
1399
Anders Carlsson6cabf312010-01-23 23:23:01 +00001400void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001401 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001402 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001403 InitListExpr *StructuredList,
1404 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001405 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001406 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001407 SemaRef.Diag(IList->getBeginLoc(),
1408 SemaRef.getLangOpts().CPlusPlus11
1409 ? diag::warn_cxx98_compat_empty_scalar_initializer
1410 : diag::err_empty_scalar_initializer)
1411 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001412 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001413 ++Index;
1414 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001415 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001416 }
John McCall643169b2010-11-11 00:46:36 +00001417
1418 Expr *expr = IList->getInit(Index);
1419 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001420 // FIXME: This is invalid, and accepting it causes overload resolution
1421 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001422 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001423 SemaRef.Diag(SubIList->getBeginLoc(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001424 diag::ext_many_braces_around_scalar_init)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001425 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001426
1427 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1428 StructuredIndex);
1429 return;
1430 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001431 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001432 SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
1433 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001434 hadError = true;
1435 ++Index;
1436 ++StructuredIndex;
1437 return;
1438 }
1439
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001440 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001441 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001442 hadError = true;
1443 ++Index;
1444 return;
1445 }
1446
John McCall643169b2010-11-11 00:46:36 +00001447 ExprResult Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001448 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1449 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001450
Craig Topperc3ec1492014-05-26 06:22:03 +00001451 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001452
1453 if (Result.isInvalid())
1454 hadError = true; // types weren't compatible.
1455 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001456 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001457
John McCall643169b2010-11-11 00:46:36 +00001458 if (ResultExpr != expr) {
1459 // The type was promoted, update initializer list.
1460 IList->setInit(Index, ResultExpr);
1461 }
1462 }
1463 if (hadError)
1464 ++StructuredIndex;
1465 else
1466 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1467 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001468}
1469
Anders Carlsson6cabf312010-01-23 23:23:01 +00001470void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1471 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001472 unsigned &Index,
1473 InitListExpr *StructuredList,
1474 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001475 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001476 // FIXME: It would be wonderful if we could point at the actual member. In
1477 // general, it would be useful to pass location information down the stack,
1478 // so that we know the location (or decl) of the "current object" being
1479 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001480 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001481 SemaRef.Diag(IList->getBeginLoc(),
1482 diag::err_init_reference_member_uninitialized)
1483 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001484 hadError = true;
1485 ++Index;
1486 ++StructuredIndex;
1487 return;
1488 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001489
1490 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001491 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001492 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001493 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1494 << DeclType << IList->getSourceRange();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001495 hadError = true;
1496 ++Index;
1497 ++StructuredIndex;
1498 return;
1499 }
1500
1501 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001502 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001503 hadError = true;
1504 ++Index;
1505 return;
1506 }
1507
1508 ExprResult Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001509 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001510 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001511
1512 if (Result.isInvalid())
1513 hadError = true;
1514
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001515 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001516 IList->setInit(Index, expr);
1517
1518 if (hadError)
1519 ++StructuredIndex;
1520 else
1521 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1522 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001523}
1524
Anders Carlsson6cabf312010-01-23 23:23:01 +00001525void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001526 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001527 unsigned &Index,
1528 InitListExpr *StructuredList,
1529 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001530 const VectorType *VT = DeclType->getAs<VectorType>();
1531 unsigned maxElements = VT->getNumElements();
1532 unsigned numEltsInit = 0;
1533 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001534
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001535 if (Index >= IList->getNumInits()) {
1536 // Make sure the element type can be value-initialized.
1537 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001538 CheckEmptyInitializable(
1539 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001540 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001541 return;
1542 }
1543
David Blaikiebbafb8a2012-03-11 07:00:24 +00001544 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001545 // If the initializing element is a vector, try to copy-initialize
1546 // instead of breaking it apart (which is doomed to failure anyway).
1547 Expr *Init = IList->getInit(Index);
1548 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001549 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001550 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001551 hadError = true;
1552 ++Index;
1553 return;
1554 }
1555
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001556 ExprResult Result =
1557 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1558 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001559
Craig Topperc3ec1492014-05-26 06:22:03 +00001560 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001561 if (Result.isInvalid())
1562 hadError = true; // types weren't compatible.
1563 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001564 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565
John McCall6a16b2f2010-10-30 00:11:39 +00001566 if (ResultExpr != Init) {
1567 // The type was promoted, update initializer list.
1568 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001569 }
1570 }
John McCall6a16b2f2010-10-30 00:11:39 +00001571 if (hadError)
1572 ++StructuredIndex;
1573 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001574 UpdateStructuredListElement(StructuredList, StructuredIndex,
1575 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001576 ++Index;
1577 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001578 }
Mike Stump11289f42009-09-09 15:08:12 +00001579
John McCall6a16b2f2010-10-30 00:11:39 +00001580 InitializedEntity ElementEntity =
1581 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001582
John McCall6a16b2f2010-10-30 00:11:39 +00001583 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1584 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001585 if (Index >= IList->getNumInits()) {
1586 if (VerifyOnly)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001587 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
John McCall6a16b2f2010-10-30 00:11:39 +00001588 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001590
John McCall6a16b2f2010-10-30 00:11:39 +00001591 ElementEntity.setElementIndex(Index);
1592 CheckSubElementType(ElementEntity, IList, elementType, Index,
1593 StructuredList, StructuredIndex);
1594 }
James Molloy9eef2652014-06-20 14:35:13 +00001595
1596 if (VerifyOnly)
1597 return;
1598
1599 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1600 const VectorType *T = Entity.getType()->getAs<VectorType>();
1601 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1602 T->getVectorKind() == VectorType::NeonPolyVector)) {
1603 // The ability to use vector initializer lists is a GNU vector extension
1604 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
Fangrui Song6907ce22018-07-30 19:24:48 +00001605 // endian machines it works fine, however on big endian machines it
James Molloy9eef2652014-06-20 14:35:13 +00001606 // exhibits surprising behaviour:
1607 //
1608 // uint32x2_t x = {42, 64};
1609 // return vget_lane_u32(x, 0); // Will return 64.
1610 //
1611 // Because of this, explicitly call out that it is non-portable.
1612 //
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001613 SemaRef.Diag(IList->getBeginLoc(),
James Molloy9eef2652014-06-20 14:35:13 +00001614 diag::warn_neon_vector_initializer_non_portable);
1615
1616 const char *typeCode;
1617 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1618
1619 if (elementType->isFloatingType())
1620 typeCode = "f";
1621 else if (elementType->isSignedIntegerType())
1622 typeCode = "s";
1623 else if (elementType->isUnsignedIntegerType())
1624 typeCode = "u";
1625 else
1626 llvm_unreachable("Invalid element type!");
1627
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001628 SemaRef.Diag(IList->getBeginLoc(),
1629 SemaRef.Context.getTypeSize(VT) > 64
1630 ? diag::note_neon_vector_initializer_non_portable_q
1631 : diag::note_neon_vector_initializer_non_portable)
1632 << typeCode << typeSize;
James Molloy9eef2652014-06-20 14:35:13 +00001633 }
1634
John McCall6a16b2f2010-10-30 00:11:39 +00001635 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001636 }
John McCall6a16b2f2010-10-30 00:11:39 +00001637
1638 InitializedEntity ElementEntity =
1639 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640
John McCall6a16b2f2010-10-30 00:11:39 +00001641 // OpenCL initializers allows vectors to be constructed from vectors.
1642 for (unsigned i = 0; i < maxElements; ++i) {
1643 // Don't attempt to go past the end of the init list
1644 if (Index >= IList->getNumInits())
1645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001646
John McCall6a16b2f2010-10-30 00:11:39 +00001647 ElementEntity.setElementIndex(Index);
1648
1649 QualType IType = IList->getInit(Index)->getType();
1650 if (!IType->isVectorType()) {
1651 CheckSubElementType(ElementEntity, IList, elementType, Index,
1652 StructuredList, StructuredIndex);
1653 ++numEltsInit;
1654 } else {
1655 QualType VecType;
1656 const VectorType *IVT = IType->getAs<VectorType>();
1657 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658
John McCall6a16b2f2010-10-30 00:11:39 +00001659 if (IType->isExtVectorType())
1660 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1661 else
1662 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001663 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001664 CheckSubElementType(ElementEntity, IList, VecType, Index,
1665 StructuredList, StructuredIndex);
1666 numEltsInit += numIElts;
1667 }
1668 }
1669
1670 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001671 if (numEltsInit != maxElements) {
1672 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001673 SemaRef.Diag(IList->getBeginLoc(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001674 diag::err_vector_incorrect_num_initializers)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001675 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001676 hadError = true;
1677 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001678}
1679
Anders Carlsson6cabf312010-01-23 23:23:01 +00001680void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001681 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001682 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001683 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001684 unsigned &Index,
1685 InitListExpr *StructuredList,
1686 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001687 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1688
Steve Narofff8ecff22008-05-01 22:18:59 +00001689 // Check for the special-case of initializing an array with a string.
1690 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001691 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1692 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001693 // We place the string literal directly into the resulting
1694 // initializer list. This is the only place where the structure
1695 // of the structured initializer list doesn't match exactly,
1696 // because doing so would involve allocating one character
1697 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001698 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001699 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1700 UpdateStructuredListElement(StructuredList, StructuredIndex,
1701 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001702 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1703 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001704 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001705 return;
1706 }
1707 }
John McCall66884dd2011-02-21 07:22:22 +00001708 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001709 // Check for VLAs; in standard C it would be possible to check this
1710 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1711 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001712 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001713 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1714 diag::err_variable_object_no_init)
1715 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001716 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001717 ++Index;
1718 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001719 return;
1720 }
1721
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001722 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001723 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1724 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001725 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001726 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001727 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001728 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001729 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001730 maxElementsKnown = true;
1731 }
1732
John McCall66884dd2011-02-21 07:22:22 +00001733 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001734 while (Index < IList->getNumInits()) {
1735 Expr *Init = IList->getInit(Index);
1736 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001737 // If we're not the subobject that matches up with the '{' for
1738 // the designator, we shouldn't be handling the
1739 // designator. Return immediately.
1740 if (!SubobjectIsDesignatorContext)
1741 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001742
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001743 // Handle this designated initializer. elementIndex will be
1744 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001745 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001746 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001747 StructuredList, StructuredIndex, true,
1748 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001749 hadError = true;
1750 continue;
1751 }
1752
Douglas Gregor033d1252009-01-23 16:54:12 +00001753 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001754 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001755 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001756 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001757 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001758
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001759 // If the array is of incomplete type, keep track of the number of
1760 // elements in the initializer.
1761 if (!maxElementsKnown && elementIndex > maxElements)
1762 maxElements = elementIndex;
1763
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001764 continue;
1765 }
1766
1767 // If we know the maximum number of elements, and we've already
1768 // hit it, stop consuming elements in the initializer list.
1769 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001770 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001771
Anders Carlsson6cabf312010-01-23 23:23:01 +00001772 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001773 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001774 Entity);
1775 // Check this element.
1776 CheckSubElementType(ElementEntity, IList, elementType, Index,
1777 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001778 ++elementIndex;
1779
1780 // If the array is of incomplete type, keep track of the number of
1781 // elements in the initializer.
1782 if (!maxElementsKnown && elementIndex > maxElements)
1783 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001784 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001785 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001786 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001787 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001788 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001789 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001790 // Sizing an array implicitly to zero is not allowed by ISO C,
1791 // but is supported by GNU.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001792 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001793 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001794
Mike Stump11289f42009-09-09 15:08:12 +00001795 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001796 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001797 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001798 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001799 // If there are any members of the array that get value-initialized, check
1800 // that is possible. That happens if we know the bound and don't have
1801 // enough elements, or if we're performing an array new with an unknown
1802 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001803 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001804 if ((maxElementsKnown && elementIndex < maxElements) ||
1805 Entity.isVariableLengthArrayNew())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001806 CheckEmptyInitializable(
1807 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1808 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001809 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001810}
1811
Eli Friedman3fa64df2011-08-23 22:24:57 +00001812bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1813 Expr *InitExpr,
1814 FieldDecl *Field,
1815 bool TopLevelObject) {
1816 // Handle GNU flexible array initializers.
1817 unsigned FlexArrayDiag;
1818 if (isa<InitListExpr>(InitExpr) &&
1819 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1820 // Empty flexible array init always allowed as an extension
1821 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001822 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001823 // Disallow flexible array init in C++; it is not required for gcc
1824 // compatibility, and it needs work to IRGen correctly in general.
1825 FlexArrayDiag = diag::err_flexible_array_init;
1826 } else if (!TopLevelObject) {
1827 // Disallow flexible array init on non-top-level object
1828 FlexArrayDiag = diag::err_flexible_array_init;
1829 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1830 // Disallow flexible array init on anything which is not a variable.
1831 FlexArrayDiag = diag::err_flexible_array_init;
1832 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1833 // Disallow flexible array init on local variables.
1834 FlexArrayDiag = diag::err_flexible_array_init;
1835 } else {
1836 // Allow other cases.
1837 FlexArrayDiag = diag::ext_flexible_array_init;
1838 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001839
1840 if (!VerifyOnly) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001841 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
1842 << InitExpr->getBeginLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001843 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1844 << Field;
1845 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001846
1847 return FlexArrayDiag != diag::ext_flexible_array_init;
1848}
1849
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001850/// Check if the type of a class element has an accessible destructor.
1851///
1852/// Aggregate initialization requires a class element's destructor be
1853/// accessible per 11.6.1 [dcl.init.aggr]:
1854///
1855/// The destructor for each element of class type is potentially invoked
1856/// (15.4 [class.dtor]) from the context where the aggregate initialization
1857/// occurs.
1858static bool hasAccessibleDestructor(QualType ElementType, SourceLocation Loc,
1859 Sema &SemaRef) {
1860 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1861 if (!CXXRD)
1862 return false;
1863
1864 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1865 SemaRef.CheckDestructorAccess(Loc, Destructor,
1866 SemaRef.PDiag(diag::err_access_dtor_temp)
1867 << ElementType);
1868 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1869 if (SemaRef.DiagnoseUseOfDecl(Destructor, Loc))
1870 return true;
1871 return false;
1872}
1873
Richard Smith872307e2016-03-08 22:17:41 +00001874void InitListChecker::CheckStructUnionTypes(
1875 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1876 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1877 bool SubobjectIsDesignatorContext, unsigned &Index,
1878 InitListExpr *StructuredList, unsigned &StructuredIndex,
1879 bool TopLevelObject) {
1880 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001881
Eli Friedman23a9e312008-05-19 19:16:24 +00001882 // If the record is invalid, some of it's members are invalid. To avoid
1883 // confusion, we forgo checking the intializer for the entire record.
1884 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001885 // Assume it was supposed to consume a single initializer.
1886 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001887 hadError = true;
1888 return;
Mike Stump11289f42009-09-09 15:08:12 +00001889 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001890
1891 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001892 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001893
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001894 if (!VerifyOnly)
1895 for (FieldDecl *FD : RD->fields()) {
1896 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
1897 if (hasAccessibleDestructor(ET, IList->getEndLoc(), SemaRef)) {
1898 hadError = true;
1899 return;
1900 }
1901 }
1902
Richard Smith852c9db2013-04-20 22:23:05 +00001903 // If there's a default initializer, use it.
1904 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1905 if (VerifyOnly)
1906 return;
1907 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1908 Field != FieldEnd; ++Field) {
1909 if (Field->hasInClassInitializer()) {
1910 StructuredList->setInitializedFieldInUnion(*Field);
1911 // FIXME: Actually build a CXXDefaultInitExpr?
1912 return;
1913 }
1914 }
1915 }
1916
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001917 // Value-initialize the first member of the union that isn't an unnamed
1918 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001919 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1920 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001921 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001922 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001923 CheckEmptyInitializable(
1924 InitializedEntity::InitializeMember(*Field, &Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001925 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001926 else
David Blaikie40ed2972012-06-06 20:45:41 +00001927 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001928 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001929 }
1930 }
1931 return;
1932 }
1933
Richard Smith872307e2016-03-08 22:17:41 +00001934 bool InitializedSomething = false;
1935
1936 // If we have any base classes, they are initialized prior to the fields.
1937 for (auto &Base : Bases) {
1938 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
Richard Smith872307e2016-03-08 22:17:41 +00001939
1940 // Designated inits always initialize fields, so if we see one, all
1941 // remaining base classes have no explicit initializer.
1942 if (Init && isa<DesignatedInitExpr>(Init))
1943 Init = nullptr;
1944
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001945 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
Richard Smith872307e2016-03-08 22:17:41 +00001946 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1947 SemaRef.Context, &Base, false, &Entity);
1948 if (Init) {
1949 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1950 StructuredList, StructuredIndex);
1951 InitializedSomething = true;
1952 } else if (VerifyOnly) {
1953 CheckEmptyInitializable(BaseEntity, InitLoc);
1954 }
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001955
1956 if (!VerifyOnly)
1957 if (hasAccessibleDestructor(Base.getType(), InitLoc, SemaRef)) {
1958 hadError = true;
1959 return;
1960 }
Richard Smith872307e2016-03-08 22:17:41 +00001961 }
1962
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001963 // If structDecl is a forward declaration, this loop won't do
1964 // anything except look at designated initializers; That's okay,
1965 // because an error should get printed out elsewhere. It might be
1966 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001967 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001968 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001969 bool CheckForMissingFields =
1970 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001971 bool HasDesignatedInit = false;
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001972
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001973 while (Index < IList->getNumInits()) {
1974 Expr *Init = IList->getInit(Index);
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001975 SourceLocation InitLoc = Init->getBeginLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001976
1977 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001978 // If we're not the subobject that matches up with the '{' for
1979 // the designator, we shouldn't be handling the
1980 // designator. Return immediately.
1981 if (!SubobjectIsDesignatorContext)
1982 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001983
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001984 HasDesignatedInit = true;
1985
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001986 // Handle this designated initializer. Field will be updated to
1987 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001988 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001989 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001990 StructuredList, StructuredIndex,
1991 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001992 hadError = true;
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001993 else if (!VerifyOnly) {
1994 // Find the field named by the designated initializer.
1995 RecordDecl::field_iterator F = RD->field_begin();
1996 while (std::next(F) != Field)
1997 ++F;
1998 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
1999 if (hasAccessibleDestructor(ET, InitLoc, SemaRef)) {
2000 hadError = true;
2001 return;
2002 }
2003 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002004
Douglas Gregora9add4e2009-02-12 19:00:39 +00002005 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00002006
2007 // Disable check for missing fields when designators are used.
2008 // This matches gcc behaviour.
2009 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002010 continue;
2011 }
2012
2013 if (Field == FieldEnd) {
2014 // We've run out of fields. We're done.
2015 break;
2016 }
2017
Douglas Gregora9add4e2009-02-12 19:00:39 +00002018 // We've already initialized a member of a union. We're done.
2019 if (InitializedSomething && DeclType->isUnionType())
2020 break;
2021
Douglas Gregor91f84212008-12-11 16:49:14 +00002022 // If we've hit the flexible array member at the end, we're done.
2023 if (Field->getType()->isIncompleteArrayType())
2024 break;
2025
Douglas Gregor51695702009-01-29 16:53:55 +00002026 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002027 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002028 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00002029 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00002030 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002031
Douglas Gregora82064c2011-06-29 21:51:31 +00002032 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002033 bool InvalidUse;
2034 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002035 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002036 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002037 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2038 *Field, IList->getInit(Index)->getBeginLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002039 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002040 ++Index;
2041 ++Field;
2042 hadError = true;
2043 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002044 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002045
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002046 if (!VerifyOnly) {
2047 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2048 if (hasAccessibleDestructor(ET, InitLoc, SemaRef)) {
2049 hadError = true;
2050 return;
2051 }
2052 }
2053
Anders Carlsson6cabf312010-01-23 23:23:01 +00002054 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002055 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002056 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2057 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00002058 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00002059
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002060 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00002061 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00002062 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00002063 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002064
2065 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00002066 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002067
John McCalle40b58e2010-03-11 19:32:38 +00002068 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002069 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2070 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2071 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00002072 // It is possible we have one or more unnamed bitfields remaining.
2073 // Find first (if any) named field and emit warning.
2074 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2075 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00002076 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00002077 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00002078 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00002079 break;
2080 }
2081 }
2082 }
2083
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002084 // Check that any remaining fields can be value-initialized.
2085 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2086 !Field->getType()->isIncompleteArrayType()) {
2087 // FIXME: Should check for holes left by designated initializers too.
2088 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00002089 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00002090 CheckEmptyInitializable(
2091 InitializedEntity::InitializeMember(*Field, &Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002092 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002093 }
2094 }
2095
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002096 // Check that the types of the remaining fields have accessible destructors.
2097 if (!VerifyOnly) {
2098 // If the initializer expression has a designated initializer, check the
2099 // elements for which a designated initializer is not provided too.
2100 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2101 : Field;
2102 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2103 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2104 if (hasAccessibleDestructor(ET, IList->getEndLoc(), SemaRef)) {
2105 hadError = true;
2106 return;
2107 }
2108 }
2109 }
2110
Mike Stump11289f42009-09-09 15:08:12 +00002111 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002112 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002113 return;
2114
David Blaikie40ed2972012-06-06 20:45:41 +00002115 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002116 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002117 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002118 ++Index;
2119 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002120 }
2121
Anders Carlsson6cabf312010-01-23 23:23:01 +00002122 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002123 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Anders Carlsson6cabf312010-01-23 23:23:01 +00002125 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002126 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002127 StructuredList, StructuredIndex);
2128 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002129 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002130 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002131}
Steve Narofff8ecff22008-05-01 22:18:59 +00002132
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002133/// Expand a field designator that refers to a member of an
Douglas Gregord5846a12009-04-15 06:41:24 +00002134/// anonymous struct or union into a series of field designators that
2135/// refers to the field within the appropriate subobject.
2136///
Douglas Gregord5846a12009-04-15 06:41:24 +00002137static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002138 DesignatedInitExpr *DIE,
2139 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002140 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002141 typedef DesignatedInitExpr::Designator Designator;
2142
Douglas Gregord5846a12009-04-15 06:41:24 +00002143 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002144 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002145 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2146 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2147 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002148 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002149 DIE->getDesignator(DesigIdx)->getDotLoc(),
2150 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2151 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002152 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2153 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002154 assert(isa<FieldDecl>(*PI));
2155 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002156 }
2157
2158 // Expand the current designator into the set of replacement
2159 // designators, so we have a full subobject path down to where the
2160 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002161 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002162 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002163}
Mike Stump11289f42009-09-09 15:08:12 +00002164
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002165static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2166 DesignatedInitExpr *DIE) {
2167 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2168 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2169 for (unsigned I = 0; I < NumIndexExprs; ++I)
2170 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002171 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2172 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002173 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002174 DIE->usesGNUSyntax(), DIE->getInit());
2175}
2176
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002177namespace {
2178
2179// Callback to only accept typo corrections that are for field members of
2180// the given struct or union.
2181class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2182 public:
2183 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2184 : Record(RD) {}
2185
Craig Toppere14c0f82014-03-12 04:55:44 +00002186 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002187 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2188 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2189 }
2190
2191 private:
2192 RecordDecl *Record;
2193};
2194
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002195} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002197/// Check the well-formedness of a C99 designated initializer.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002198///
2199/// Determines whether the designated initializer @p DIE, which
2200/// resides at the given @p Index within the initializer list @p
2201/// IList, is well-formed for a current object of type @p DeclType
2202/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002203/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002204/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002205///
2206/// @param IList The initializer list in which this designated
2207/// initializer occurs.
2208///
Douglas Gregora5324162009-04-15 04:56:10 +00002209/// @param DIE The designated initializer expression.
2210///
2211/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002212///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002213/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002214/// into which the designation in @p DIE should refer.
2215///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002216/// @param NextField If non-NULL and the first designator in @p DIE is
2217/// a field, this will be set to the field declaration corresponding
2218/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002219///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002220/// @param NextElementIndex If non-NULL and the first designator in @p
2221/// DIE is an array designator or GNU array-range designator, this
2222/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002223///
2224/// @param Index Index into @p IList where the designated initializer
2225/// @p DIE occurs.
2226///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002227/// @param StructuredList The initializer list expression that
2228/// describes all of the subobject initializers in the order they'll
2229/// actually be initialized.
2230///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002231/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002232bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002233InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002234 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002235 DesignatedInitExpr *DIE,
2236 unsigned DesigIdx,
2237 QualType &CurrentObjectType,
2238 RecordDecl::field_iterator *NextField,
2239 llvm::APSInt *NextElementIndex,
2240 unsigned &Index,
2241 InitListExpr *StructuredList,
2242 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002243 bool FinishSubobjectInit,
2244 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002245 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002246 // Check the actual initialization for the designated object type.
2247 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002248
2249 // Temporarily remove the designator expression from the
2250 // initializer list that the child calls see, so that we don't try
2251 // to re-process the designator.
2252 unsigned OldIndex = Index;
2253 IList->setInit(OldIndex, DIE->getInit());
2254
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002255 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002256 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002257
2258 // Restore the designated initializer expression in the syntactic
2259 // form of the initializer list.
2260 if (IList->getInit(OldIndex) != DIE->getInit())
2261 DIE->setInit(IList->getInit(OldIndex));
2262 IList->setInit(OldIndex, DIE);
2263
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002264 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002265 }
2266
Douglas Gregora5324162009-04-15 04:56:10 +00002267 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002268 bool IsFirstDesignator = (DesigIdx == 0);
2269 if (!VerifyOnly) {
2270 assert((IsFirstDesignator || StructuredList) &&
2271 "Need a non-designated initializer list to start from");
2272
2273 // Determine the structural initializer list that corresponds to the
2274 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002275 if (IsFirstDesignator)
2276 StructuredList = SyntacticToSemantic.lookup(IList);
2277 else {
2278 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2279 StructuredList->getInit(StructuredIndex) : nullptr;
2280 if (!ExistingInit && StructuredList->hasArrayFiller())
2281 ExistingInit = StructuredList->getArrayFiller();
2282
2283 if (!ExistingInit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002284 StructuredList = getStructuredSubobjectInit(
2285 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002286 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
Yunzhong Gaocb779302015-06-10 00:27:52 +00002287 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2288 StructuredList = Result;
2289 else {
2290 if (DesignatedInitUpdateExpr *E =
2291 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2292 StructuredList = E->getUpdater();
2293 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002294 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2295 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002296 ExistingInit, DIE->getEndLoc());
Yunzhong Gaocb779302015-06-10 00:27:52 +00002297 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2298 StructuredList = DIUE->getUpdater();
2299 }
2300
2301 // We need to check on source range validity because the previous
2302 // initializer does not have to be an explicit initializer. e.g.,
2303 //
2304 // struct P { int a, b; };
2305 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2306 //
2307 // There is an overwrite taking place because the first braced initializer
2308 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2309 if (ExistingInit->getSourceRange().isValid()) {
2310 // We are creating an initializer list that initializes the
2311 // subobjects of the current object, but there was already an
2312 // initialization that completely initialized the current
2313 // subobject, e.g., by a compound literal:
2314 //
2315 // struct X { int a, b; };
2316 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2317 //
2318 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2319 // designated initializer re-initializes the whole
2320 // subobject [0], overwriting previous initializers.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002321 SemaRef.Diag(D->getBeginLoc(),
Yunzhong Gaocb779302015-06-10 00:27:52 +00002322 diag::warn_subobject_initializer_overrides)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002323 << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00002324
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002325 SemaRef.Diag(ExistingInit->getBeginLoc(),
Yunzhong Gaocb779302015-06-10 00:27:52 +00002326 diag::note_previous_initializer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002327 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002328 }
2329 }
2330 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002331 assert(StructuredList && "Expected a structured initializer list");
2332 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002333
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002334 if (D->isFieldDesignator()) {
2335 // C99 6.7.8p7:
2336 //
2337 // If a designator has the form
2338 //
2339 // . identifier
2340 //
2341 // then the current object (defined below) shall have
2342 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002343 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002344 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002345 if (!RT) {
2346 SourceLocation Loc = D->getDotLoc();
2347 if (Loc.isInvalid())
2348 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002349 if (!VerifyOnly)
2350 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002351 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002352 ++Index;
2353 return true;
2354 }
2355
Douglas Gregord5846a12009-04-15 06:41:24 +00002356 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002357 if (!KnownField) {
2358 IdentifierInfo *FieldName = D->getFieldName();
2359 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2360 for (NamedDecl *ND : Lookup) {
2361 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2362 KnownField = FD;
2363 break;
2364 }
2365 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002366 // In verify mode, don't modify the original.
2367 if (VerifyOnly)
2368 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002369 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002370 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002371 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002372 break;
2373 }
2374 }
David Majnemer36ef8982014-08-11 18:33:59 +00002375 if (!KnownField) {
2376 if (VerifyOnly) {
2377 ++Index;
2378 return true; // No typo correction when just trying this out.
2379 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002380
David Majnemer36ef8982014-08-11 18:33:59 +00002381 // Name lookup found something, but it wasn't a field.
2382 if (!Lookup.empty()) {
2383 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2384 << FieldName;
2385 SemaRef.Diag(Lookup.front()->getLocation(),
2386 diag::note_field_designator_found);
2387 ++Index;
2388 return true;
2389 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002390
David Majnemer36ef8982014-08-11 18:33:59 +00002391 // Name lookup didn't find anything.
2392 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002393 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2394 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002395 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002396 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2397 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002398 SemaRef.diagnoseTypo(
2399 Corrected,
2400 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002401 << FieldName << CurrentObjectType);
2402 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002403 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002404 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002405 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002406 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2407 << FieldName << CurrentObjectType;
2408 ++Index;
2409 return true;
2410 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002411 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002412 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002413
David Majnemer58e4ea92014-08-23 01:48:50 +00002414 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002415
2416 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2417 FieldIndex = CXXRD->getNumBases();
2418
David Majnemer58e4ea92014-08-23 01:48:50 +00002419 for (auto *FI : RT->getDecl()->fields()) {
2420 if (FI->isUnnamedBitfield())
2421 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002422 if (declaresSameEntity(KnownField, FI)) {
2423 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002424 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002425 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002426 ++FieldIndex;
2427 }
2428
David Majnemer36ef8982014-08-11 18:33:59 +00002429 RecordDecl::field_iterator Field =
2430 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2431
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002432 // All of the fields of a union are located at the same place in
2433 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002434 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002435 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002436 if (!VerifyOnly) {
2437 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002438 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002439 assert(StructuredList->getNumInits() == 1
2440 && "A union should never have more than one initializer!");
2441
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002442 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002443 if (ExistingInit) {
2444 // We're about to throw away an initializer, emit warning.
2445 SemaRef.Diag(D->getFieldLoc(),
2446 diag::warn_initializer_overrides)
2447 << D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002448 SemaRef.Diag(ExistingInit->getBeginLoc(),
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002449 diag::note_previous_initializer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002450 << /*FIXME:has side effects=*/0
2451 << ExistingInit->getSourceRange();
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002452 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002453
2454 // remove existing initializer
2455 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002456 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002457 }
2458
David Blaikie40ed2972012-06-06 20:45:41 +00002459 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002460 }
Douglas Gregor51695702009-01-29 16:53:55 +00002461 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002462
Douglas Gregora82064c2011-06-29 21:51:31 +00002463 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002464 bool InvalidUse;
2465 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002466 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002467 else
David Blaikie40ed2972012-06-06 20:45:41 +00002468 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002469 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002470 ++Index;
2471 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002472 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002473
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002474 if (!VerifyOnly) {
2475 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002476 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002477
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002478 // Make sure that our non-designated initializer list has space
2479 // for a subobject corresponding to this field.
2480 if (FieldIndex >= StructuredList->getNumInits())
2481 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2482 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002483
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002484 // This designator names a flexible array member.
2485 if (Field->getType()->isIncompleteArrayType()) {
2486 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002487 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002488 // We can't designate an object within the flexible array
2489 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002490 if (!VerifyOnly) {
2491 DesignatedInitExpr::Designator *NextD
2492 = DIE->getDesignator(DesigIdx + 1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002493 SemaRef.Diag(NextD->getBeginLoc(),
2494 diag::err_designator_into_flexible_array_member)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002495 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002496 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002497 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002498 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002499 Invalid = true;
2500 }
2501
Chris Lattner001b29c2010-10-10 17:49:49 +00002502 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2503 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002504 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002505 if (!VerifyOnly) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002506 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2507 diag::err_flexible_array_init_needs_braces)
2508 << DIE->getInit()->getSourceRange();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002509 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002510 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002511 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002512 Invalid = true;
2513 }
2514
Eli Friedman3fa64df2011-08-23 22:24:57 +00002515 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002516 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002517 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002518 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002519
2520 if (Invalid) {
2521 ++Index;
2522 return true;
2523 }
2524
2525 // Initialize the array.
2526 bool prevHadError = hadError;
2527 unsigned newStructuredIndex = FieldIndex;
2528 unsigned OldIndex = Index;
2529 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002530
2531 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002532 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002533 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002534 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002535
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002536 IList->setInit(OldIndex, DIE);
2537 if (hadError && !prevHadError) {
2538 ++Field;
2539 ++FieldIndex;
2540 if (NextField)
2541 *NextField = Field;
2542 StructuredIndex = FieldIndex;
2543 return true;
2544 }
2545 } else {
2546 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002547 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002548 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002549
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002550 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002551 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002553 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002554 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002555 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002556 return true;
2557 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002558
2559 // Find the position of the next field to be initialized in this
2560 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002561 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002562 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002563
2564 // If this the first designator, our caller will continue checking
2565 // the rest of this struct/class/union subobject.
2566 if (IsFirstDesignator) {
2567 if (NextField)
2568 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002569 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002570 return false;
2571 }
2572
Douglas Gregor17bd0942009-01-28 23:36:17 +00002573 if (!FinishSubobjectInit)
2574 return false;
2575
Douglas Gregord5846a12009-04-15 06:41:24 +00002576 // We've already initialized something in the union; we're done.
2577 if (RT->getDecl()->isUnion())
2578 return hadError;
2579
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002580 // Check the remaining fields within this class/struct/union subobject.
2581 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582
Richard Smith872307e2016-03-08 22:17:41 +00002583 auto NoBases =
2584 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2585 CXXRecordDecl::base_class_iterator());
2586 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2587 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002588 return hadError && !prevHadError;
2589 }
2590
2591 // C99 6.7.8p6:
2592 //
2593 // If a designator has the form
2594 //
2595 // [ constant-expression ]
2596 //
2597 // then the current object (defined below) shall have array
2598 // type and the expression shall be an integer constant
2599 // expression. If the array is of unknown size, any
2600 // nonnegative value is valid.
2601 //
2602 // Additionally, cope with the GNU extension that permits
2603 // designators of the form
2604 //
2605 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002606 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002607 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002608 if (!VerifyOnly)
2609 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2610 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002611 ++Index;
2612 return true;
2613 }
2614
Craig Topperc3ec1492014-05-26 06:22:03 +00002615 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002616 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2617 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002618 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002619 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002620 DesignatedEndIndex = DesignatedStartIndex;
2621 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002622 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002623
Mike Stump11289f42009-09-09 15:08:12 +00002624 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002625 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002626 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002627 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002628 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002629
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002630 // Codegen can't handle evaluating array range designators that have side
2631 // effects, because we replicate the AST value for each initialized element.
2632 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2633 // elements with something that has a side effect, so codegen can emit an
2634 // "error unsupported" error instead of miscompiling the app.
2635 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002636 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002637 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002638 }
2639
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002640 if (isa<ConstantArrayType>(AT)) {
2641 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002642 DesignatedStartIndex
2643 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002644 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002645 DesignatedEndIndex
2646 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002647 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2648 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002649 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002650 SemaRef.Diag(IndexExpr->getBeginLoc(),
2651 diag::err_array_designator_too_large)
2652 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2653 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002654 ++Index;
2655 return true;
2656 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002657 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002658 unsigned DesignatedIndexBitWidth =
2659 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2660 DesignatedStartIndex =
2661 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2662 DesignatedEndIndex =
2663 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002664 DesignatedStartIndex.setIsUnsigned(true);
2665 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002666 }
Mike Stump11289f42009-09-09 15:08:12 +00002667
Eli Friedman1f16b742013-06-11 21:48:11 +00002668 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2669 // We're modifying a string literal init; we have to decompose the string
2670 // so we can modify the individual characters.
2671 ASTContext &Context = SemaRef.Context;
2672 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2673
2674 // Compute the character type
2675 QualType CharTy = AT->getElementType();
2676
2677 // Compute the type of the integer literals.
2678 QualType PromotedCharTy = CharTy;
2679 if (CharTy->isPromotableIntegerType())
2680 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2681 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2682
2683 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2684 // Get the length of the string.
2685 uint64_t StrLen = SL->getLength();
2686 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2687 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2688 StructuredList->resizeInits(Context, StrLen);
2689
2690 // Build a literal for each character in the string, and put them into
2691 // the init list.
2692 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2693 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2694 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002695 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002696 if (CharTy != PromotedCharTy)
2697 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002698 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002699 StructuredList->updateInit(Context, i, Init);
2700 }
2701 } else {
2702 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2703 std::string Str;
2704 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2705
2706 // Get the length of the string.
2707 uint64_t StrLen = Str.size();
2708 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2709 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2710 StructuredList->resizeInits(Context, StrLen);
2711
2712 // Build a literal for each character in the string, and put them into
2713 // the init list.
2714 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2715 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2716 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002717 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002718 if (CharTy != PromotedCharTy)
2719 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002720 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002721 StructuredList->updateInit(Context, i, Init);
2722 }
2723 }
2724 }
2725
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002726 // Make sure that our non-designated initializer list has space
2727 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002728 if (!VerifyOnly &&
2729 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002730 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002731 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002732
Douglas Gregor17bd0942009-01-28 23:36:17 +00002733 // Repeatedly perform subobject initializations in the range
2734 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002735
Douglas Gregor17bd0942009-01-28 23:36:17 +00002736 // Move to the next designator
2737 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2738 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002739
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002740 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002741 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002742
Douglas Gregor17bd0942009-01-28 23:36:17 +00002743 while (DesignatedStartIndex <= DesignatedEndIndex) {
2744 // Recurse to check later designated subobjects.
2745 QualType ElementType = AT->getElementType();
2746 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002747
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002748 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002749 if (CheckDesignatedInitializer(
2750 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2751 nullptr, Index, StructuredList, ElementIndex,
2752 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2753 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002754 return true;
2755
2756 // Move to the next index in the array that we'll be initializing.
2757 ++DesignatedStartIndex;
2758 ElementIndex = DesignatedStartIndex.getZExtValue();
2759 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002760
2761 // If this the first designator, our caller will continue checking
2762 // the rest of this array subobject.
2763 if (IsFirstDesignator) {
2764 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002765 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002766 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002767 return false;
2768 }
Mike Stump11289f42009-09-09 15:08:12 +00002769
Douglas Gregor17bd0942009-01-28 23:36:17 +00002770 if (!FinishSubobjectInit)
2771 return false;
2772
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002773 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002774 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002776 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002777 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002778 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002779}
2780
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002781// Get the structured initializer list for a subobject of type
2782// @p CurrentObjectType.
2783InitListExpr *
2784InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2785 QualType CurrentObjectType,
2786 InitListExpr *StructuredList,
2787 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002788 SourceRange InitRange,
2789 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002790 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002791 return nullptr; // No structured list in verification-only mode.
2792 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002793 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002794 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002795 else if (StructuredIndex < StructuredList->getNumInits())
2796 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002797
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002798 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002799 // There might have already been initializers for subobjects of the current
2800 // object, but a subsequent initializer list will overwrite the entirety
2801 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2802 //
2803 // struct P { char x[6]; };
2804 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2805 //
2806 // The first designated initializer is ignored, and l.x is just "f".
2807 if (!IsFullyOverwritten)
2808 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002809
2810 if (ExistingInit) {
2811 // We are creating an initializer list that initializes the
2812 // subobjects of the current object, but there was already an
2813 // initialization that completely initialized the current
2814 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002815 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002816 // struct X { int a, b; };
2817 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002818 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002819 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2820 // designated initializer re-initializes the whole
2821 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002822 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002823 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002824 << InitRange;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002825 SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
2826 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002827 }
2828
Mike Stump11289f42009-09-09 15:08:12 +00002829 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002830 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002831 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002832 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002833
Eli Friedman91f5ae52012-02-23 02:25:10 +00002834 QualType ResultType = CurrentObjectType;
2835 if (!ResultType->isArrayType())
2836 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2837 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002838
Douglas Gregor6d00c992009-03-20 23:58:33 +00002839 // Pre-allocate storage for the structured initializer list.
2840 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002841 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002842 bool GotNumInits = false;
2843 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002844 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002845 GotNumInits = true;
2846 } else if (Index < IList->getNumInits()) {
2847 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002848 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002849 GotNumInits = true;
2850 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002851 }
2852
Mike Stump11289f42009-09-09 15:08:12 +00002853 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002854 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2855 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2856 NumElements = CAType->getSize().getZExtValue();
2857 // Simple heuristic so that we don't allocate a very large
2858 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002859 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002860 NumElements = 0;
2861 }
John McCall9dd450b2009-09-21 23:43:11 +00002862 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002863 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002864 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002865 RecordDecl *RDecl = RType->getDecl();
2866 if (RDecl->isUnion())
2867 NumElements = 1;
2868 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002869 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002870 }
2871
Ted Kremenekac034612010-04-13 23:39:13 +00002872 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002873
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002874 // Link this new initializer list into the structured initializer
2875 // lists.
2876 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002877 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002878 else {
2879 Result->setSyntacticForm(IList);
2880 SyntacticToSemantic[IList] = Result;
2881 }
2882
2883 return Result;
2884}
2885
2886/// Update the initializer at index @p StructuredIndex within the
2887/// structured initializer list to the value @p expr.
2888void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2889 unsigned &StructuredIndex,
2890 Expr *expr) {
2891 // No structured initializer list to update
2892 if (!StructuredList)
2893 return;
2894
Ted Kremenekac034612010-04-13 23:39:13 +00002895 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2896 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002897 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002898 // We need to check on source range validity because the previous
2899 // initializer does not have to be an explicit initializer.
2900 // struct P { int a, b; };
2901 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2902 // There is an overwrite taking place because the first braced initializer
2903 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2904 if (PrevInit->getSourceRange().isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002905 SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
2906 << expr->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002907
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002908 SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
2909 << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002910 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002911 }
Mike Stump11289f42009-09-09 15:08:12 +00002912
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002913 ++StructuredIndex;
2914}
2915
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002916/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002917/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002918/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002919/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002920/// failure. Returns the index expression, possibly with an implicit cast
2921/// added, on success. If everything went okay, Value will receive the
2922/// value of the constant expression.
2923static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002924CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002925 SourceLocation Loc = Index->getBeginLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002926
2927 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002928 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2929 if (Result.isInvalid())
2930 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002931
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002932 if (Value.isSigned() && Value.isNegative())
2933 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002934 << Value.toString(10) << Index->getSourceRange();
2935
Douglas Gregor51650d32009-01-23 21:04:18 +00002936 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002937 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002938}
2939
John McCalldadc5752010-08-24 06:29:42 +00002940ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002941 SourceLocation Loc,
2942 bool GNUSyntax,
2943 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002944 typedef DesignatedInitExpr::Designator ASTDesignator;
2945
2946 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002947 SmallVector<ASTDesignator, 32> Designators;
2948 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002949
2950 // Build designators and check array designator expressions.
2951 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2952 const Designator &D = Desig.getDesignator(Idx);
2953 switch (D.getKind()) {
2954 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002955 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002956 D.getFieldLoc()));
2957 break;
2958
2959 case Designator::ArrayDesignator: {
2960 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2961 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002962 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002963 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002964 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002965 Invalid = true;
2966 else {
2967 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002968 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002969 D.getRBracketLoc()));
2970 InitExpressions.push_back(Index);
2971 }
2972 break;
2973 }
2974
2975 case Designator::ArrayRangeDesignator: {
2976 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2977 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2978 llvm::APSInt StartValue;
2979 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002980 bool StartDependent = StartIndex->isTypeDependent() ||
2981 StartIndex->isValueDependent();
2982 bool EndDependent = EndIndex->isTypeDependent() ||
2983 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002984 if (!StartDependent)
2985 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002986 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002987 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002988 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002989
2990 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002991 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002992 else {
2993 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002994 if (StartDependent || EndDependent) {
2995 // Nothing to compute.
2996 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002997 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002998 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002999 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00003000
Douglas Gregor0f9d4002009-05-21 23:30:39 +00003001 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00003002 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00003003 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00003004 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3005 Invalid = true;
3006 } else {
3007 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00003008 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00003009 D.getEllipsisLoc(),
3010 D.getRBracketLoc()));
3011 InitExpressions.push_back(StartIndex);
3012 InitExpressions.push_back(EndIndex);
3013 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003014 }
3015 break;
3016 }
3017 }
3018 }
3019
3020 if (Invalid || Init.isInvalid())
3021 return ExprError();
3022
3023 // Clear out the expressions within the designation.
3024 Desig.ClearExprs(*this);
3025
3026 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00003027 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00003028 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003029 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003030 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031
David Blaikiebbafb8a2012-03-11 07:00:24 +00003032 if (!getLangOpts().C99)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003033 Diag(DIE->getBeginLoc(), diag::ext_designated_init)
3034 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003035
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003036 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003037}
Douglas Gregor85df8d82009-01-29 00:45:39 +00003038
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003039//===----------------------------------------------------------------------===//
3040// Initialization entity
3041//===----------------------------------------------------------------------===//
3042
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00003044 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003045 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00003046{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003047 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3048 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00003049 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003050 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003051 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003052 Type = VT->getElementType();
3053 } else {
3054 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3055 assert(CT && "Unexpected type");
3056 Kind = EK_ComplexElement;
3057 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003058 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003059}
3060
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003061InitializedEntity
3062InitializedEntity::InitializeBase(ASTContext &Context,
3063 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00003064 bool IsInheritedVirtualBase,
3065 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003066 InitializedEntity Result;
3067 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00003068 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00003069 Result.Base = reinterpret_cast<uintptr_t>(Base);
3070 if (IsInheritedVirtualBase)
3071 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003072
Douglas Gregor1b303932009-12-22 15:35:07 +00003073 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003074 return Result;
3075}
3076
Douglas Gregor85dabae2009-12-16 01:38:02 +00003077DeclarationName InitializedEntity::getName() const {
3078 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003079 case EK_Parameter:
3080 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00003081 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3082 return (D ? D->getDeclName() : DeclarationName());
3083 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003084
3085 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003086 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003087 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003088 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003089
Douglas Gregor19666fb2012-02-15 16:57:26 +00003090 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003091 return DeclarationName(Capture.VarID);
Fangrui Song6907ce22018-07-30 19:24:48 +00003092
Douglas Gregor85dabae2009-12-16 01:38:02 +00003093 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003094 case EK_StmtExprResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003095 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003096 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003097 case EK_Temporary:
3098 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003099 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003100 case EK_ArrayElement:
3101 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003102 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003103 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003104 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003105 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003106 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003107 return DeclarationName();
3108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003109
David Blaikie8a40f702012-01-17 06:56:22 +00003110 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003111}
3112
Richard Smith7873de02016-08-11 22:25:46 +00003113ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003114 switch (getKind()) {
3115 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003116 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003117 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003118 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003119
John McCall31168b02011-06-15 23:02:42 +00003120 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003121 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003122 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3123
Douglas Gregora4b592a2009-12-19 03:01:41 +00003124 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003125 case EK_StmtExprResult:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003126 case EK_Exception:
3127 case EK_New:
3128 case EK_Temporary:
3129 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003130 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003131 case EK_ArrayElement:
3132 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003133 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003134 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003135 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003136 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003137 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003138 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003139 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003140 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003141
David Blaikie8a40f702012-01-17 06:56:22 +00003142 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003143}
3144
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003145bool InitializedEntity::allowsNRVO() const {
3146 switch (getKind()) {
3147 case EK_Result:
3148 case EK_Exception:
3149 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003150
Richard Smith67af95b2018-07-23 19:19:08 +00003151 case EK_StmtExprResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003152 case EK_Variable:
3153 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003154 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003155 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003156 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003157 case EK_New:
3158 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003159 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003160 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003161 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003162 case EK_ArrayElement:
3163 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003164 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003165 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003166 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003167 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003168 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003169 break;
3170 }
3171
3172 return false;
3173}
3174
Richard Smithe6c01442013-06-05 00:46:14 +00003175unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003176 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003177 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3178 for (unsigned I = 0; I != Depth; ++I)
3179 OS << "`-";
3180
3181 switch (getKind()) {
3182 case EK_Variable: OS << "Variable"; break;
3183 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003184 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3185 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003186 case EK_Result: OS << "Result"; break;
Richard Smith67af95b2018-07-23 19:19:08 +00003187 case EK_StmtExprResult: OS << "StmtExprResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003188 case EK_Exception: OS << "Exception"; break;
3189 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003190 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003191 case EK_New: OS << "New"; break;
3192 case EK_Temporary: OS << "Temporary"; break;
3193 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003194 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003195 case EK_Base: OS << "Base"; break;
3196 case EK_Delegating: OS << "Delegating"; break;
3197 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3198 case EK_VectorElement: OS << "VectorElement " << Index; break;
3199 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3200 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003201 case EK_LambdaToBlockConversionBlockElement:
3202 OS << "Block (lambda)";
3203 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003204 case EK_LambdaCapture:
3205 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003206 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003207 break;
3208 }
3209
Richard Smith7873de02016-08-11 22:25:46 +00003210 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003211 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003212 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003213 }
3214
3215 OS << " '" << getType().getAsString() << "'\n";
3216
3217 return Depth + 1;
3218}
3219
Yaron Kerencdae9412016-01-29 19:38:18 +00003220LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003221 dumpImpl(llvm::errs());
3222}
3223
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003224//===----------------------------------------------------------------------===//
3225// Initialization sequence
3226//===----------------------------------------------------------------------===//
3227
3228void InitializationSequence::Step::Destroy() {
3229 switch (Kind) {
3230 case SK_ResolveAddressOfOverloadedFunction:
3231 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003232 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003233 case SK_CastDerivedToBaseLValue:
3234 case SK_BindReference:
3235 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003236 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003237 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 case SK_UserConversion:
3239 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003240 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003241 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003242 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003243 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003244 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003245 case SK_UnwrapInitList:
3246 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003247 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003248 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003249 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003250 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003251 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003252 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003253 case SK_ArrayLoopIndex:
3254 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003255 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003256 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003257 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003258 case SK_PassByIndirectCopyRestore:
3259 case SK_PassByIndirectRestore:
3260 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003261 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003262 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003263 case SK_OCLSamplerInit:
Andrew Savonichevb555b762018-10-23 15:19:20 +00003264 case SK_OCLZeroOpaqueType:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003265 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003268 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003269 delete ICS;
3270 }
3271}
3272
Douglas Gregor838fcc32010-03-26 20:14:36 +00003273bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003274 // There can be some lvalue adjustments after the SK_BindReference step.
3275 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3276 if (I->Kind == SK_BindReference)
3277 return true;
3278 if (I->Kind == SK_BindReferenceToTemporary)
3279 return false;
3280 }
3281 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003282}
3283
3284bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003285 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003286 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287
Douglas Gregor838fcc32010-03-26 20:14:36 +00003288 switch (getFailureKind()) {
3289 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003290 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003291 case FK_ArrayNeedsInitList:
3292 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003293 case FK_ArrayNeedsInitListOrWideStringLiteral:
3294 case FK_NarrowStringIntoWideCharArray:
3295 case FK_WideStringIntoCharArray:
3296 case FK_IncompatWideStringIntoWideChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00003297 case FK_PlainStringIntoUTF8Char:
3298 case FK_UTF8StringIntoPlainChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003299 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3300 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003301 case FK_NonConstLValueReferenceBindingToBitfield:
3302 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003303 case FK_NonConstLValueReferenceBindingToUnrelated:
3304 case FK_RValueReferenceBindingToLValue:
3305 case FK_ReferenceInitDropsQualifiers:
3306 case FK_ReferenceInitFailed:
3307 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003308 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003309 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003310 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003311 case FK_ReferenceBindingToInitList:
3312 case FK_InitListBadDestinationType:
3313 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003314 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003315 case FK_ArrayTypeMismatch:
3316 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003317 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003318 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003319 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003320 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003321 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003322 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323
Douglas Gregor838fcc32010-03-26 20:14:36 +00003324 case FK_ReferenceInitOverloadFailed:
3325 case FK_UserConversionOverloadFailed:
3326 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003327 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003328 return FailedOverloadResult == OR_Ambiguous;
3329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003330
David Blaikie8a40f702012-01-17 06:56:22 +00003331 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003332}
3333
Douglas Gregorb33eed02010-04-16 22:09:46 +00003334bool InitializationSequence::isConstructorInitialization() const {
3335 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3336}
3337
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003338void
3339InitializationSequence
3340::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3341 DeclAccessPair Found,
3342 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003343 Step S;
3344 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3345 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003346 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003347 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003348 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003349 Steps.push_back(S);
3350}
3351
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003353 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003354 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003355 switch (VK) {
3356 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3357 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3358 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003359 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003360 S.Type = BaseType;
3361 Steps.push_back(S);
3362}
3363
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003365 bool BindingTemporary) {
3366 Step S;
3367 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3368 S.Type = T;
3369 Steps.push_back(S);
3370}
3371
Richard Smithb8c0f552016-12-09 18:49:13 +00003372void InitializationSequence::AddFinalCopy(QualType T) {
3373 Step S;
3374 S.Kind = SK_FinalCopy;
3375 S.Type = T;
3376 Steps.push_back(S);
3377}
3378
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003379void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3380 Step S;
3381 S.Kind = SK_ExtraneousCopyToTemporary;
3382 S.Type = T;
3383 Steps.push_back(S);
3384}
3385
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003386void
3387InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3388 DeclAccessPair FoundDecl,
3389 QualType T,
3390 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003391 Step S;
3392 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003393 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003394 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003395 S.Function.Function = Function;
3396 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003397 Steps.push_back(S);
3398}
3399
3400void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003401 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003402 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003403 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003404 switch (VK) {
3405 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003406 S.Kind = SK_QualificationConversionRValue;
3407 break;
John McCall2536c6d2010-08-25 10:28:54 +00003408 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003409 S.Kind = SK_QualificationConversionXValue;
3410 break;
John McCall2536c6d2010-08-25 10:28:54 +00003411 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003412 S.Kind = SK_QualificationConversionLValue;
3413 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003414 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003415 S.Type = Ty;
3416 Steps.push_back(S);
3417}
3418
Richard Smith77be48a2014-07-31 06:31:19 +00003419void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3420 Step S;
3421 S.Kind = SK_AtomicConversion;
3422 S.Type = Ty;
3423 Steps.push_back(S);
3424}
3425
Jordan Roseb1312a52013-04-11 00:58:58 +00003426void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3427 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3428
3429 Step S;
3430 S.Kind = SK_LValueToRValue;
3431 S.Type = Ty;
3432 Steps.push_back(S);
3433}
3434
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003435void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003436 const ImplicitConversionSequence &ICS, QualType T,
3437 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003438 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003439 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3440 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003441 S.Type = T;
3442 S.ICS = new ImplicitConversionSequence(ICS);
3443 Steps.push_back(S);
3444}
3445
Douglas Gregor51e77d52009-12-10 17:56:55 +00003446void InitializationSequence::AddListInitializationStep(QualType T) {
3447 Step S;
3448 S.Kind = SK_ListInitialization;
3449 S.Type = T;
3450 Steps.push_back(S);
3451}
3452
Richard Smith55c28882016-05-12 23:45:49 +00003453void InitializationSequence::AddConstructorInitializationStep(
3454 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3455 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003456 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003457 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003458 : SK_ConstructorInitializationFromList
3459 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003460 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003461 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003462 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003463 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003464 Steps.push_back(S);
3465}
3466
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003467void InitializationSequence::AddZeroInitializationStep(QualType T) {
3468 Step S;
3469 S.Kind = SK_ZeroInitialization;
3470 S.Type = T;
3471 Steps.push_back(S);
3472}
3473
Douglas Gregore1314a62009-12-18 05:02:21 +00003474void InitializationSequence::AddCAssignmentStep(QualType T) {
3475 Step S;
3476 S.Kind = SK_CAssignment;
3477 S.Type = T;
3478 Steps.push_back(S);
3479}
3480
Eli Friedman78275202009-12-19 08:11:05 +00003481void InitializationSequence::AddStringInitStep(QualType T) {
3482 Step S;
3483 S.Kind = SK_StringInit;
3484 S.Type = T;
3485 Steps.push_back(S);
3486}
3487
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003488void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3489 Step S;
3490 S.Kind = SK_ObjCObjectConversion;
3491 S.Type = T;
3492 Steps.push_back(S);
3493}
3494
Richard Smith378b8c82016-12-14 03:22:16 +00003495void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003496 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003497 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003498 S.Type = T;
3499 Steps.push_back(S);
3500}
3501
Richard Smith410306b2016-12-12 02:53:20 +00003502void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3503 Step S;
3504 S.Kind = SK_ArrayLoopIndex;
3505 S.Type = EltT;
3506 Steps.insert(Steps.begin(), S);
3507
3508 S.Kind = SK_ArrayLoopInit;
3509 S.Type = T;
3510 Steps.push_back(S);
3511}
3512
Richard Smithebeed412012-02-15 22:38:09 +00003513void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3514 Step S;
3515 S.Kind = SK_ParenthesizedArrayInit;
3516 S.Type = T;
3517 Steps.push_back(S);
3518}
3519
John McCall31168b02011-06-15 23:02:42 +00003520void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3521 bool shouldCopy) {
3522 Step s;
3523 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3524 : SK_PassByIndirectRestore);
3525 s.Type = type;
3526 Steps.push_back(s);
3527}
3528
3529void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3530 Step S;
3531 S.Kind = SK_ProduceObjCObject;
3532 S.Type = T;
3533 Steps.push_back(S);
3534}
3535
Sebastian Redlc1839b12012-01-17 22:49:42 +00003536void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3537 Step S;
3538 S.Kind = SK_StdInitializerList;
3539 S.Type = T;
3540 Steps.push_back(S);
3541}
3542
Guy Benyei61054192013-02-07 10:55:47 +00003543void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3544 Step S;
3545 S.Kind = SK_OCLSamplerInit;
3546 S.Type = T;
3547 Steps.push_back(S);
3548}
3549
Andrew Savonichevb555b762018-10-23 15:19:20 +00003550void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003551 Step S;
Andrew Savonichevb555b762018-10-23 15:19:20 +00003552 S.Kind = SK_OCLZeroOpaqueType;
Egor Churaev89831422016-12-23 14:55:49 +00003553 S.Type = T;
3554 Steps.push_back(S);
3555}
3556
Sebastian Redl29526f02011-11-27 16:50:07 +00003557void InitializationSequence::RewrapReferenceInitList(QualType T,
3558 InitListExpr *Syntactic) {
3559 assert(Syntactic->getNumInits() == 1 &&
3560 "Can only rewrap trivial init lists.");
3561 Step S;
3562 S.Kind = SK_UnwrapInitList;
3563 S.Type = Syntactic->getInit(0)->getType();
3564 Steps.insert(Steps.begin(), S);
3565
3566 S.Kind = SK_RewrapInitList;
3567 S.Type = T;
3568 S.WrappingSyntacticList = Syntactic;
3569 Steps.push_back(S);
3570}
3571
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003573 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003574 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003575 this->Failure = Failure;
3576 this->FailedOverloadResult = Result;
3577}
3578
3579//===----------------------------------------------------------------------===//
3580// Attempt initialization
3581//===----------------------------------------------------------------------===//
3582
Nico Weber337d5aa2015-04-17 08:32:38 +00003583/// Tries to add a zero initializer. Returns true if that worked.
3584static bool
3585maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3586 const InitializedEntity &Entity) {
3587 if (Entity.getKind() != InitializedEntity::EK_Variable)
3588 return false;
3589
3590 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003591 if (VD->getInit() || VD->getEndLoc().isMacroID())
Nico Weber337d5aa2015-04-17 08:32:38 +00003592 return false;
3593
3594 QualType VariableTy = VD->getType().getCanonicalType();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003595 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
Nico Weber337d5aa2015-04-17 08:32:38 +00003596 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3597 if (!Init.empty()) {
3598 Sequence.AddZeroInitializationStep(Entity.getType());
3599 Sequence.SetZeroInitializationFixit(Init, Loc);
3600 return true;
3601 }
3602 return false;
3603}
3604
John McCall31168b02011-06-15 23:02:42 +00003605static void MaybeProduceObjCObject(Sema &S,
3606 InitializationSequence &Sequence,
3607 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003608 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003609
3610 /// When initializing a parameter, produce the value if it's marked
3611 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003612 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003613 if (!Entity.isParameterConsumed())
3614 return;
3615
3616 assert(Entity.getType()->isObjCRetainableType() &&
3617 "consuming an object of unretainable type?");
3618 Sequence.AddProduceObjCObjectStep(Entity.getType());
3619
3620 /// When initializing a return value, if the return type is a
3621 /// retainable type, then returns need to immediately retain the
3622 /// object. If an autorelease is required, it will be done at the
3623 /// last instant.
Richard Smith67af95b2018-07-23 19:19:08 +00003624 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3625 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
John McCall31168b02011-06-15 23:02:42 +00003626 if (!Entity.getType()->isObjCRetainableType())
3627 return;
3628
3629 Sequence.AddProduceObjCObjectStep(Entity.getType());
3630 }
3631}
3632
Richard Smithcc1b96d2013-06-12 22:31:48 +00003633static void TryListInitialization(Sema &S,
3634 const InitializedEntity &Entity,
3635 const InitializationKind &Kind,
3636 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003637 InitializationSequence &Sequence,
3638 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003639
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003640/// When initializing from init list via constructor, handle
Richard Smithd86812d2012-07-05 08:39:21 +00003641/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003642///
Richard Smithd86812d2012-07-05 08:39:21 +00003643/// \return true if we have handled initialization of an object of type
3644/// std::initializer_list<T>, false otherwise.
3645static bool TryInitializerListConstruction(Sema &S,
3646 InitListExpr *List,
3647 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003648 InitializationSequence &Sequence,
3649 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003650 QualType E;
3651 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003652 return false;
3653
Richard Smithdb0ac552015-12-18 22:40:25 +00003654 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003655 Sequence.setIncompleteTypeFailure(E);
3656 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003657 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003658
3659 // Try initializing a temporary array from the init list.
3660 QualType ArrayType = S.Context.getConstantArrayType(
3661 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3662 List->getNumInits()),
3663 clang::ArrayType::Normal, 0);
3664 InitializedEntity HiddenArray =
3665 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003666 InitializationKind Kind = InitializationKind::CreateDirectList(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003667 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
Manman Ren073db022016-03-10 18:53:19 +00003668 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3669 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003670 if (Sequence)
3671 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003672 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003673}
3674
Richard Smith7c2bcc92016-09-07 02:14:33 +00003675/// Determine if the constructor has the signature of a copy or move
3676/// constructor for the type T of the class in which it was found. That is,
3677/// determine if its first parameter is of type T or reference to (possibly
3678/// cv-qualified) T.
3679static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3680 const ConstructorInfo &Info) {
3681 if (Info.Constructor->getNumParams() == 0)
3682 return false;
3683
3684 QualType ParmT =
3685 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3686 QualType ClassT =
3687 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3688
3689 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3690}
3691
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003692static OverloadingResult
3693ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003694 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003695 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003696 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003697 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003698 OverloadCandidateSet::iterator &Best,
3699 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003700 bool OnlyListConstructors, bool IsListInit,
3701 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003702 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003703
Richard Smith40c78062015-02-21 02:31:57 +00003704 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003705 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003706 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003707 continue;
3708
Richard Smith7c2bcc92016-09-07 02:14:33 +00003709 if (!AllowExplicit && Info.Constructor->isExplicit())
3710 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003711
Richard Smith7c2bcc92016-09-07 02:14:33 +00003712 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3713 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003714
Richard Smith7c2bcc92016-09-07 02:14:33 +00003715 // C++11 [over.best.ics]p4:
3716 // ... and the constructor or user-defined conversion function is a
3717 // candidate by
3718 // - 13.3.1.3, when the argument is the temporary in the second step
3719 // of a class copy-initialization, or
3720 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3721 // - the second phase of 13.3.1.7 when the initializer list has exactly
3722 // one element that is itself an initializer list, and the target is
3723 // the first parameter of a constructor of class X, and the conversion
3724 // is to X or reference to (possibly cv-qualified X),
3725 // user-defined conversion sequences are not considered.
3726 bool SuppressUserConversions =
3727 SecondStepOfCopyInit ||
3728 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3729 hasCopyOrMoveCtorParam(S.Context, Info));
3730
3731 if (Info.ConstructorTmpl)
3732 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3733 /*ExplicitArgs*/ nullptr, Args,
3734 CandidateSet, SuppressUserConversions);
3735 else {
3736 // C++ [over.match.copy]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00003737 // - When initializing a temporary to be bound to the first parameter
Richard Smith7c2bcc92016-09-07 02:14:33 +00003738 // of a constructor [for type T] that takes a reference to possibly
3739 // cv-qualified T as its first argument, called with a single
3740 // argument in the context of direct-initialization, explicit
3741 // conversion functions are also considered.
3742 // FIXME: What if a constructor template instantiates to such a signature?
Fangrui Song6907ce22018-07-30 19:24:48 +00003743 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Richard Smith7c2bcc92016-09-07 02:14:33 +00003744 Args.size() == 1 &&
3745 hasCopyOrMoveCtorParam(S.Context, Info);
3746 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3747 CandidateSet, SuppressUserConversions,
3748 /*PartialOverloading=*/false,
3749 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003750 }
3751 }
3752
Richard Smith67ef14f2017-09-26 18:37:55 +00003753 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3754 //
3755 // When initializing an object of class type T by constructor
3756 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3757 // from a single expression of class type U, conversion functions of
3758 // U that convert to the non-reference type cv T are candidates.
3759 // Explicit conversion functions are only candidates during
3760 // direct-initialization.
3761 //
3762 // Note: SecondStepOfCopyInit is only ever true in this case when
3763 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003764 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003765 !SecondStepOfCopyInit) {
3766 Expr *Initializer = Args[0];
3767 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3768 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3769 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3770 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3771 NamedDecl *D = *I;
3772 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3773 D = D->getUnderlyingDecl();
3774
3775 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3776 CXXConversionDecl *Conv;
3777 if (ConvTemplate)
3778 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3779 else
3780 Conv = cast<CXXConversionDecl>(D);
3781
3782 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3783 if (ConvTemplate)
3784 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3785 ActingDC, Initializer, DestType,
3786 CandidateSet, AllowExplicit,
3787 /*AllowResultConversion*/false);
3788 else
3789 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3790 DestType, CandidateSet, AllowExplicit,
3791 /*AllowResultConversion*/false);
3792 }
3793 }
3794 }
3795 }
3796
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003797 // Perform overload resolution and return the result.
3798 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3799}
3800
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003801/// Attempt initialization by constructor (C++ [dcl.init]), which
Sebastian Redled2e5322011-12-22 14:44:04 +00003802/// enumerates the constructors of the initialized entity and performs overload
3803/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003804/// \param DestType The destination class type.
3805/// \param DestArrayType The destination type, which is either DestType or
3806/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003807/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003808/// \param IsInitListCopy Is this non-list-initialization resulting from a
3809/// list-initialization from {x} where x is the same
3810/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003811static void TryConstructorInitialization(Sema &S,
3812 const InitializedEntity &Entity,
3813 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003814 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003815 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003816 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003817 bool IsListInit = false,
3818 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003819 assert(((!IsListInit && !IsInitListCopy) ||
3820 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3821 "IsListInit/IsInitListCopy must come with a single initializer list "
3822 "argument.");
3823 InitListExpr *ILE =
3824 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3825 MultiExprArg UnwrappedArgs =
3826 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003827
Sebastian Redled2e5322011-12-22 14:44:04 +00003828 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003829 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003830 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003831 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003832 }
3833
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003834 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003835 // - If the initializer expression is a prvalue and the cv-unqualified
3836 // version of the source type is the same class as the class of the
3837 // destination, the initializer expression is used to initialize the
3838 // destination object.
3839 // Per DR (no number yet), this does not apply when initializing a base
3840 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003841 // ObjC++: Lambda captured by the block in the lambda to block conversion
3842 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003843 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003844 Entity.getKind() != InitializedEntity::EK_Base &&
3845 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003846 Entity.getKind() !=
3847 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003848 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3849 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3850 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003851 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003852 if (ILE)
3853 Sequence.RewrapReferenceInitList(DestType, ILE);
3854 return;
3855 }
3856
Sebastian Redled2e5322011-12-22 14:44:04 +00003857 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3858 assert(DestRecordType && "Constructor initialization requires record type");
3859 CXXRecordDecl *DestRecordDecl
3860 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3861
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003862 // Build the candidate set directly in the initialization sequence
3863 // structure, so that it will persist if we fail.
3864 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3865
3866 // Determine whether we are allowed to call explicit constructors or
3867 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003868 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003869 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003870
Sebastian Redled2e5322011-12-22 14:44:04 +00003871 // - Otherwise, if T is a class type, constructors are considered. The
3872 // applicable constructors are enumerated, and the best one is chosen
3873 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003874 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003875
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003876 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003877 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003878 bool AsInitializerList = false;
3879
Larisse Voufo19d08672015-01-27 18:47:05 +00003880 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003881 // When objects of non-aggregate type T are list-initialized, such that
3882 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3883 // according to the rules in this section, overload resolution selects
3884 // the constructor in two phases:
3885 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003886 // - Initially, the candidate functions are the initializer-list
3887 // constructors of the class T and the argument list consists of the
3888 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003889 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003890 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003891
3892 // If the initializer list has no elements and T has a default constructor,
3893 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003894 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003895 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003896 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003897 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003898 /*OnlyListConstructor=*/true,
3899 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003900 }
3901
3902 // C++11 [over.match.list]p1:
3903 // - If no viable initializer-list constructor is found, overload resolution
3904 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003905 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003906 // elements of the initializer list.
3907 if (Result == OR_No_Viable_Function) {
3908 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003909 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003910 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003911 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003912 /*OnlyListConstructors=*/false,
3913 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003914 }
3915 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003916 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003917 InitializationSequence::FK_ListConstructorOverloadFailed :
3918 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003919 Result);
3920 return;
3921 }
3922
Richard Smith67ef14f2017-09-26 18:37:55 +00003923 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3924
3925 // In C++17, ResolveConstructorOverload can select a conversion function
3926 // instead of a constructor.
3927 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3928 // Add the user-defined conversion step that calls the conversion function.
3929 QualType ConvType = CD->getConversionType();
3930 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3931 "should not have selected this conversion function");
3932 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3933 HadMultipleCandidates);
3934 if (!S.Context.hasSameType(ConvType, DestType))
3935 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3936 if (IsListInit)
3937 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3938 return;
3939 }
3940
Richard Smithd86812d2012-07-05 08:39:21 +00003941 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003942 // If a program calls for the default initialization of an object
3943 // of a const-qualified type T, T shall be a class type with a
3944 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003945 // C++ core issue 253 proposal:
3946 // If the implicit default constructor initializes all subobjects, no
3947 // initializer should be required.
3948 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3949 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003950 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003951 Entity.getType().isConstQualified()) {
3952 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3953 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3954 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3955 return;
3956 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003957 }
3958
Sebastian Redl048a6d72012-04-01 19:54:59 +00003959 // C++11 [over.match.list]p1:
3960 // In copy-list-initialization, if an explicit constructor is chosen, the
3961 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003962 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003963 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3964 return;
3965 }
3966
Sebastian Redled2e5322011-12-22 14:44:04 +00003967 // Add the constructor initialization step. Any cv-qualification conversion is
3968 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00003969 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003970 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003971 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003972}
3973
Sebastian Redl29526f02011-11-27 16:50:07 +00003974static bool
3975ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3976 Expr *Initializer,
3977 QualType &SourceType,
3978 QualType &UnqualifiedSourceType,
3979 QualType UnqualifiedTargetType,
3980 InitializationSequence &Sequence) {
3981 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3982 S.Context.OverloadTy) {
3983 DeclAccessPair Found;
3984 bool HadMultipleCandidates = false;
3985 if (FunctionDecl *Fn
3986 = S.ResolveAddressOfOverloadedFunction(Initializer,
3987 UnqualifiedTargetType,
3988 false, Found,
3989 &HadMultipleCandidates)) {
3990 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3991 HadMultipleCandidates);
3992 SourceType = Fn->getType();
3993 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3994 } else if (!UnqualifiedTargetType->isRecordType()) {
3995 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3996 return true;
3997 }
3998 }
3999 return false;
4000}
4001
4002static void TryReferenceInitializationCore(Sema &S,
4003 const InitializedEntity &Entity,
4004 const InitializationKind &Kind,
4005 Expr *Initializer,
4006 QualType cv1T1, QualType T1,
4007 Qualifiers T1Quals,
4008 QualType cv2T2, QualType T2,
4009 Qualifiers T2Quals,
4010 InitializationSequence &Sequence);
4011
Richard Smithd86812d2012-07-05 08:39:21 +00004012static void TryValueInitialization(Sema &S,
4013 const InitializedEntity &Entity,
4014 const InitializationKind &Kind,
4015 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00004016 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00004017
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004018/// Attempt list initialization of a reference.
Sebastian Redl29526f02011-11-27 16:50:07 +00004019static void TryReferenceListInitialization(Sema &S,
4020 const InitializedEntity &Entity,
4021 const InitializationKind &Kind,
4022 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004023 InitializationSequence &Sequence,
4024 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00004025 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004026 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00004027 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4028 return;
4029 }
David Majnemer9370dc22015-04-26 07:35:03 +00004030 // Can't reference initialize a compound literal.
4031 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4032 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4033 return;
4034 }
Sebastian Redl29526f02011-11-27 16:50:07 +00004035
4036 QualType DestType = Entity.getType();
4037 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4038 Qualifiers T1Quals;
4039 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4040
4041 // Reference initialization via an initializer list works thus:
4042 // If the initializer list consists of a single element that is
4043 // reference-related to the referenced type, bind directly to that element
4044 // (possibly creating temporaries).
4045 // Otherwise, initialize a temporary with the initializer list and
4046 // bind to that.
4047 if (InitList->getNumInits() == 1) {
4048 Expr *Initializer = InitList->getInit(0);
4049 QualType cv2T2 = Initializer->getType();
4050 Qualifiers T2Quals;
4051 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4052
4053 // If this fails, creating a temporary wouldn't work either.
4054 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4055 T1, Sequence))
4056 return;
4057
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004058 SourceLocation DeclLoc = Initializer->getBeginLoc();
Sebastian Redl29526f02011-11-27 16:50:07 +00004059 bool dummy1, dummy2, dummy3;
4060 Sema::ReferenceCompareResult RefRelationship
4061 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
4062 dummy2, dummy3);
4063 if (RefRelationship >= Sema::Ref_Related) {
4064 // Try to bind the reference here.
4065 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4066 T1Quals, cv2T2, T2, T2Quals, Sequence);
4067 if (Sequence)
4068 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4069 return;
4070 }
Richard Smith03d93932013-01-15 07:58:29 +00004071
4072 // Update the initializer if we've resolved an overloaded function.
4073 if (Sequence.step_begin() != Sequence.step_end())
4074 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00004075 }
4076
4077 // Not reference-related. Create a temporary and bind to that.
4078 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4079
Manman Ren073db022016-03-10 18:53:19 +00004080 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4081 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00004082 if (Sequence) {
4083 if (DestType->isRValueReferenceType() ||
4084 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
4085 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4086 else
4087 Sequence.SetFailed(
4088 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4089 }
4090}
4091
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004092/// Attempt list initialization (C++0x [dcl.init.list])
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004093static void TryListInitialization(Sema &S,
4094 const InitializedEntity &Entity,
4095 const InitializationKind &Kind,
4096 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004097 InitializationSequence &Sequence,
4098 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004099 QualType DestType = Entity.getType();
4100
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004101 // C++ doesn't allow scalar initialization with more than one argument.
4102 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004103 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004104 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4105 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4106 return;
4107 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004108 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004109 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4110 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004111 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004112 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004113
Larisse Voufod2010992015-01-24 23:09:54 +00004114 if (DestType->isRecordType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004115 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004116 Sequence.setIncompleteTypeFailure(DestType);
4117 return;
4118 }
Richard Smithd86812d2012-07-05 08:39:21 +00004119
Larisse Voufo19d08672015-01-27 18:47:05 +00004120 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004121 // - If T is a class type and the initializer list has a single element of
4122 // type cv U, where U is T or a class derived from T, the object is
4123 // initialized from that element (by copy-initialization for
4124 // copy-list-initialization, or by direct-initialization for
4125 // direct-list-initialization).
4126 // - Otherwise, if T is a character array and the initializer list has a
4127 // single element that is an appropriately-typed string literal
4128 // (8.5.2 [dcl.init.string]), initialization is performed as described
4129 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004130 // - Otherwise, if T is an aggregate, [...] (continue below).
4131 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004132 if (DestType->isRecordType()) {
4133 QualType InitType = InitList->getInit(0)->getType();
4134 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004135 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004136 Expr *InitListAsExpr = InitList;
4137 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004138 DestType, Sequence,
4139 /*InitListSyntax*/false,
4140 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004141 return;
4142 }
4143 }
4144 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4145 Expr *SubInit[1] = {InitList->getInit(0)};
4146 if (!isa<VariableArrayType>(DestAT) &&
4147 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4148 InitializationKind SubKind =
4149 Kind.getKind() == InitializationKind::IK_DirectList
4150 ? InitializationKind::CreateDirect(Kind.getLocation(),
4151 InitList->getLBraceLoc(),
4152 InitList->getRBraceLoc())
4153 : Kind;
4154 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004155 /*TopLevelOfInitList*/ true,
4156 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004157
4158 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4159 // the element is not an appropriately-typed string literal, in which
4160 // case we should proceed as in C++11 (below).
4161 if (Sequence) {
4162 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4163 return;
4164 }
4165 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004166 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004167 }
Larisse Voufod2010992015-01-24 23:09:54 +00004168
4169 // C++11 [dcl.init.list]p3:
4170 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004171 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4172 (S.getLangOpts().CPlusPlus11 &&
4173 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004174 if (S.getLangOpts().CPlusPlus11) {
4175 // - Otherwise, if the initializer list has no elements and T is a
4176 // class type with a default constructor, the object is
4177 // value-initialized.
4178 if (InitList->getNumInits() == 0) {
4179 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4180 if (RD->hasDefaultConstructor()) {
4181 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4182 return;
4183 }
4184 }
4185
4186 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4187 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004188 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4189 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004190 return;
4191
4192 // - Otherwise, if T is a class type, constructors are considered.
4193 Expr *InitListAsExpr = InitList;
4194 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004195 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004196 } else
4197 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4198 return;
4199 }
4200
Richard Smith089c3162013-09-21 21:55:46 +00004201 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004202 InitList->getNumInits() == 1) {
4203 Expr *E = InitList->getInit(0);
4204
4205 // - Otherwise, if T is an enumeration with a fixed underlying type,
4206 // the initializer-list has a single element v, and the initialization
4207 // is direct-list-initialization, the object is initialized with the
4208 // value T(v); if a narrowing conversion is required to convert v to
4209 // the underlying type of T, the program is ill-formed.
4210 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004211 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004212 Kind.getKind() == InitializationKind::IK_DirectList &&
4213 ET && ET->getDecl()->isFixed() &&
4214 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4215 (E->getType()->isIntegralOrEnumerationType() ||
4216 E->getType()->isFloatingType())) {
4217 // There are two ways that T(v) can work when T is an enumeration type.
4218 // If there is either an implicit conversion sequence from v to T or
4219 // a conversion function that can convert from v to T, then we use that.
4220 // Otherwise, if v is of integral, enumeration, or floating-point type,
4221 // it is converted to the enumeration type via its underlying type.
4222 // There is no overlap possible between these two cases (except when the
4223 // source value is already of the destination type), and the first
4224 // case is handled by the general case for single-element lists below.
4225 ImplicitConversionSequence ICS;
4226 ICS.setStandard();
4227 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004228 if (!E->isRValue())
4229 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004230 // If E is of a floating-point type, then the conversion is ill-formed
4231 // due to narrowing, but go through the motions in order to produce the
4232 // right diagnostic.
4233 ICS.Standard.Second = E->getType()->isFloatingType()
4234 ? ICK_Floating_Integral
4235 : ICK_Integral_Conversion;
4236 ICS.Standard.setFromType(E->getType());
4237 ICS.Standard.setToType(0, E->getType());
4238 ICS.Standard.setToType(1, DestType);
4239 ICS.Standard.setToType(2, DestType);
4240 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4241 /*TopLevelOfInitList*/true);
4242 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4243 return;
4244 }
4245
Richard Smith089c3162013-09-21 21:55:46 +00004246 // - Otherwise, if the initializer list has a single element of type E
4247 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004248 // initialized from that element (by copy-initialization for
4249 // copy-list-initialization, or by direct-initialization for
4250 // direct-list-initialization); if a narrowing conversion is required
4251 // to convert the element to T, the program is ill-formed.
4252 //
Richard Smith089c3162013-09-21 21:55:46 +00004253 // Per core-24034, this is direct-initialization if we were performing
4254 // direct-list-initialization and copy-initialization otherwise.
4255 // We can't use InitListChecker for this, because it always performs
4256 // copy-initialization. This only matters if we might use an 'explicit'
4257 // conversion operator, so we only need to handle the cases where the source
4258 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004259 if (InitList->getInit(0)->getType()->isRecordType()) {
4260 InitializationKind SubKind =
4261 Kind.getKind() == InitializationKind::IK_DirectList
4262 ? InitializationKind::CreateDirect(Kind.getLocation(),
4263 InitList->getLBraceLoc(),
4264 InitList->getRBraceLoc())
4265 : Kind;
4266 Expr *SubInit[1] = { InitList->getInit(0) };
4267 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4268 /*TopLevelOfInitList*/true,
4269 TreatUnavailableAsInvalid);
4270 if (Sequence)
4271 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4272 return;
4273 }
Richard Smith089c3162013-09-21 21:55:46 +00004274 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004275
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004276 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004277 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004278 if (CheckInitList.HadError()) {
4279 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4280 return;
4281 }
4282
4283 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004284 Sequence.AddListInitializationStep(DestType);
4285}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004287/// Try a reference initialization that involves calling a conversion
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004288/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004289static OverloadingResult TryRefInitWithConversionFunction(
4290 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4291 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4292 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004293 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004294 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4295 QualType T1 = cv1T1.getUnqualifiedType();
4296 QualType cv2T2 = Initializer->getType();
4297 QualType T2 = cv2T2.getUnqualifiedType();
4298
4299 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004300 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004301 bool ObjCLifetimeConversion;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004302 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
4303 DerivedToBase, ObjCConversion,
John McCall31168b02011-06-15 23:02:42 +00004304 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004305 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004306 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004307 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004308 (void)ObjCLifetimeConversion;
Fangrui Song6907ce22018-07-30 19:24:48 +00004309
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004310 // Build the candidate set directly in the initialization sequence
4311 // structure, so that it will persist if we fail.
4312 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004313 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004314
Richard Smithb368ea82018-07-02 23:25:22 +00004315 // Determine whether we are allowed to call explicit conversion operators.
4316 // Note that none of [over.match.copy], [over.match.conv], nor
4317 // [over.match.ref] permit an explicit constructor to be chosen when
4318 // initializing a reference, not even for direct-initialization.
4319 bool AllowExplicitCtors = false;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004320 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4321
Craig Topperc3ec1492014-05-26 06:22:03 +00004322 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004323 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004324 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004325 // The type we're converting to is a class type. Enumerate its constructors
4326 // to see if there is a suitable conversion.
4327 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004328
Richard Smith40c78062015-02-21 02:31:57 +00004329 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004330 auto Info = getConstructorInfo(D);
4331 if (!Info.Constructor)
4332 continue;
John McCalla0296f72010-03-19 07:35:19 +00004333
Richard Smithc2bebe92016-05-11 20:37:46 +00004334 if (!Info.Constructor->isInvalidDecl() &&
Richard Smithb368ea82018-07-02 23:25:22 +00004335 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004336 if (Info.ConstructorTmpl)
4337 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004338 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004339 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004340 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004341 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004342 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004343 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004344 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004347 }
John McCall3696dcb2010-08-17 07:23:57 +00004348 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4349 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350
Craig Topperc3ec1492014-05-26 06:22:03 +00004351 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004352 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004353 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004354 // The type we're converting from is a class type, enumerate its conversion
4355 // functions.
4356 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4357
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004358 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4359 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004360 NamedDecl *D = *I;
4361 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4362 if (isa<UsingShadowDecl>(D))
4363 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004365 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4366 CXXConversionDecl *Conv;
4367 if (ConvTemplate)
4368 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4369 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004370 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004372 // If the conversion function doesn't return a reference type,
4373 // it can't be considered for this conversion unless we're allowed to
4374 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 // FIXME: Do we need to make sure that we only consider conversion
4376 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004377 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004378 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004379 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4380 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004381 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004382 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004383 DestType, CandidateSet,
4384 /*AllowObjCConversionOnExplicit=*/
4385 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004386 else
John McCalla0296f72010-03-19 07:35:19 +00004387 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004388 Initializer, DestType, CandidateSet,
4389 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004390 }
4391 }
4392 }
John McCall3696dcb2010-08-17 07:23:57 +00004393 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4394 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004396 SourceLocation DeclLoc = Initializer->getBeginLoc();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004397
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004399 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004400 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004401 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004402 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004403
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004404 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004405 // This is the overload that will be used for this initialization step if we
4406 // use this initialization. Mark it as referenced.
4407 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004408
Richard Smithb8c0f552016-12-09 18:49:13 +00004409 // Compute the returned type and value kind of the conversion.
4410 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004411 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004412 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004413 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004414 cv3T3 = T1;
4415
4416 ExprValueKind VK = VK_RValue;
4417 if (cv3T3->isLValueReferenceType())
4418 VK = VK_LValue;
4419 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4420 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4421 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004422
4423 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004424 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004425 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004426 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004427
Richard Smithb8c0f552016-12-09 18:49:13 +00004428 // Determine whether we'll need to perform derived-to-base adjustments or
4429 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004430 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004431 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004432 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004433 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004434 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004435 NewDerivedToBase, NewObjCConversion,
4436 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004437
4438 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004439 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004440 assert(!isa<CXXConstructorDecl>(Function) &&
4441 "should not have conversion after constructor");
4442
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004443 ImplicitConversionSequence ICS;
4444 ICS.setStandard();
4445 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004446 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4447
4448 // Every implicit conversion results in a prvalue, except for a glvalue
4449 // derived-to-base conversion, which we handle below.
4450 cv3T3 = ICS.Standard.getToType(2);
4451 VK = VK_RValue;
4452 }
4453
4454 // If the converted initializer is a prvalue, its type T4 is adjusted to
4455 // type "cv1 T4" and the temporary materialization conversion is applied.
4456 //
4457 // We adjust the cv-qualifications to match the reference regardless of
4458 // whether we have a prvalue so that the AST records the change. In this
4459 // case, T4 is "cv3 T3".
4460 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4461 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4462 Sequence.AddQualificationConversionStep(cv1T4, VK);
4463 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4464 VK = IsLValueRef ? VK_LValue : VK_XValue;
4465
4466 if (NewDerivedToBase)
4467 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004468 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004469 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004470
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004471 return OR_Success;
4472}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473
Richard Smithc620f552011-10-19 16:55:56 +00004474static void CheckCXX98CompatAccessibleCopy(Sema &S,
4475 const InitializedEntity &Entity,
4476 Expr *CurInitExpr);
4477
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004478/// Attempt reference initialization (C++0x [dcl.init.ref])
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004480 const InitializedEntity &Entity,
4481 const InitializationKind &Kind,
4482 Expr *Initializer,
4483 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004484 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004485 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004486 Qualifiers T1Quals;
4487 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004488 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004489 Qualifiers T2Quals;
4490 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004491
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004492 // If the initializer is the address of an overloaded function, try
4493 // to resolve the overloaded function. If all goes well, T2 is the
4494 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004495 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4496 T1, Sequence))
4497 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004498
Sebastian Redl29526f02011-11-27 16:50:07 +00004499 // Delegate everything else to a subfunction.
4500 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4501 T1Quals, cv2T2, T2, T2Quals, Sequence);
4502}
4503
Richard Smithb8c0f552016-12-09 18:49:13 +00004504/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004505/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004506/// such a glvalue will always create a temporary.
4507static bool isNonReferenceableGLValue(Expr *E) {
4508 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004509}
4510
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004511/// Reference initialization without resolving overloaded functions.
Sebastian Redl29526f02011-11-27 16:50:07 +00004512static void TryReferenceInitializationCore(Sema &S,
4513 const InitializedEntity &Entity,
4514 const InitializationKind &Kind,
4515 Expr *Initializer,
4516 QualType cv1T1, QualType T1,
4517 Qualifiers T1Quals,
4518 QualType cv2T2, QualType T2,
4519 Qualifiers T2Quals,
4520 InitializationSequence &Sequence) {
4521 QualType DestType = Entity.getType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004522 SourceLocation DeclLoc = Initializer->getBeginLoc();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004523 // Compute some basic properties of the types and the initializer.
4524 bool isLValueRef = DestType->isLValueReferenceType();
4525 bool isRValueRef = !isLValueRef;
4526 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004527 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004528 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004529 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004530 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004531 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004532 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004533
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004534 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004536 // "cv2 T2" as follows:
4537 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004539 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004540 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004541 // there are no function rvalues in C++, rvalue refs to functions are treated
4542 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004543 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004544 bool T1Function = T1->isFunctionType();
4545 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004546 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004547 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004549 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004551 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004552 if (T1Quals != T2Quals)
4553 // Convert to cv1 T2. This should only add qualifiers unless this is a
4554 // c-style cast. The removal of qualifiers in that case notionally
4555 // happens after the reference binding, but that doesn't matter.
4556 Sequence.AddQualificationConversionStep(
4557 S.Context.getQualifiedType(T2, T1Quals),
4558 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004559 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004560 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004561 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004562 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004563
Richard Smithb8c0f552016-12-09 18:49:13 +00004564 // We only create a temporary here when binding a reference to a
4565 // bit-field or vector element. Those cases are't supposed to be
4566 // handled by this bullet, but the outcome is the same either way.
4567 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004568 return;
4569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570
4571 // - has a class type (i.e., T2 is a class type), where T1 is not
4572 // reference-related to T2, and can be implicitly converted to an
4573 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4574 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004575 // applicable conversion functions (13.3.1.6) and choosing the best
4576 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004577 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004578 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004579 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4580 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004581 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004582 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4583 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004584 if (ConvOvlResult == OR_Success)
4585 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004586 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004587 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004588 InitializationSequence::FK_ReferenceInitOverloadFailed,
4589 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004590 }
4591 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004592
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004594 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004595 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004596 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004597 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4598 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4599 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004600 Sequence.SetOverloadFailure(
4601 InitializationSequence::FK_ReferenceInitOverloadFailed,
4602 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004603 else if (!InitCategory.isLValue())
4604 Sequence.SetFailed(
4605 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4606 else {
4607 InitializationSequence::FailureKind FK;
4608 switch (RefRelationship) {
4609 case Sema::Ref_Compatible:
4610 if (Initializer->refersToBitField())
4611 FK = InitializationSequence::
4612 FK_NonConstLValueReferenceBindingToBitfield;
4613 else if (Initializer->refersToVectorElement())
4614 FK = InitializationSequence::
4615 FK_NonConstLValueReferenceBindingToVectorElement;
4616 else
4617 llvm_unreachable("unexpected kind of compatible initializer");
4618 break;
4619 case Sema::Ref_Related:
4620 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4621 break;
4622 case Sema::Ref_Incompatible:
4623 FK = InitializationSequence::
4624 FK_NonConstLValueReferenceBindingToUnrelated;
4625 break;
4626 }
4627 Sequence.SetFailed(FK);
4628 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004629 return;
4630 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004631
Douglas Gregor92e460e2011-01-20 16:44:54 +00004632 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004633 // - is an
4634 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4635 // [1z] rvalue (but not a bit-field) or
4636 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4637 //
4638 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004639 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004640 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004641 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004642 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004643 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004644 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004645 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004646 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004647 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004648 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004649 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4650 // compiler the freedom to perform a copy here or bind to the
4651 // object, while C++0x requires that we bind directly to the
4652 // object. Hence, we always bind to the object without making an
4653 // extra copy. However, in C++03 requires that we check for the
4654 // presence of a suitable copy constructor:
4655 //
4656 // The constructor that would be used to make the copy shall
4657 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004658 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004659 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004660 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004661 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663
Richard Smithb8c0f552016-12-09 18:49:13 +00004664 // C++1z [dcl.init.ref]/5.2.1.2:
4665 // If the converted initializer is a prvalue, its type T4 is adjusted
4666 // to type "cv1 T4" and the temporary materialization conversion is
4667 // applied.
4668 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4669 if (T1Quals != T2Quals)
4670 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4671 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4672 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4673
4674 // In any case, the reference is bound to the resulting glvalue (or to
4675 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004676 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004677 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004678 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004679 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004681 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004682
4683 // - has a class type (i.e., T2 is a class type), where T1 is not
4684 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004685 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4686 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004687 //
4688 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004689 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004690 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004691 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004692 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4693 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004694 if (ConvOvlResult)
4695 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004696 InitializationSequence::FK_ReferenceInitOverloadFailed,
4697 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004698
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004699 return;
4700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
Richard Smithce766292016-10-21 23:01:55 +00004702 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004703 isRValueRef && InitCategory.isLValue()) {
4704 Sequence.SetFailed(
4705 InitializationSequence::FK_RValueReferenceBindingToLValue);
4706 return;
4707 }
4708
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004709 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4710 return;
4711 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004712
4713 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004714 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004715 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004716 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004717
John McCallec6f4e92010-06-04 02:29:22 +00004718 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4719
Richard Smith2eabf782013-06-13 00:57:57 +00004720 // FIXME: Why do we use an implicit conversion here rather than trying
4721 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004722 ImplicitConversionSequence ICS
4723 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004724 /*SuppressUserConversions=*/false,
4725 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004726 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004727 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4728 /*AllowObjCWritebackConversion=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00004729
John McCall31168b02011-06-15 23:02:42 +00004730 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004731 // FIXME: Use the conversion function set stored in ICS to turn
4732 // this into an overloading ambiguity diagnostic. However, we need
4733 // to keep that set as an OverloadCandidateSet rather than as some
4734 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004735 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4736 Sequence.SetOverloadFailure(
4737 InitializationSequence::FK_ReferenceInitOverloadFailed,
4738 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004739 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4740 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004741 else
4742 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004743 return;
John McCall31168b02011-06-15 23:02:42 +00004744 } else {
4745 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004746 }
4747
4748 // [...] If T1 is reference-related to T2, cv1 must be the
4749 // same cv-qualification as, or greater cv-qualification
4750 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004751 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4752 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004753 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004754 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004755 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4756 return;
4757 }
4758
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004760 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004762 InitCategory.isLValue()) {
4763 Sequence.SetFailed(
4764 InitializationSequence::FK_RValueReferenceBindingToLValue);
4765 return;
4766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004768 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004769}
4770
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004771/// Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772/// (C++ [dcl.init.string], C99 6.7.8).
4773static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004774 const InitializedEntity &Entity,
4775 const InitializationKind &Kind,
4776 Expr *Initializer,
4777 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004778 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004779}
4780
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004781/// Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004783 const InitializedEntity &Entity,
4784 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004785 InitializationSequence &Sequence,
4786 InitListExpr *InitList) {
4787 assert((!InitList || InitList->getNumInits() == 0) &&
4788 "Shouldn't use value-init for non-empty init lists");
4789
Richard Smith1bfe0682012-02-14 21:14:13 +00004790 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004791 //
4792 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004793 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004795 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004796 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004798 if (const RecordType *RT = T->getAs<RecordType>()) {
4799 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004800 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004801 // C++98:
4802 // -- if T is a class type (clause 9) with a user-declared constructor
4803 // (12.1), then the default constructor for T is called (and the
4804 // initialization is ill-formed if T has no accessible default
4805 // constructor);
4806 // C++11:
4807 // -- if T is a class type (clause 9) with either no default constructor
4808 // (12.1 [class.ctor]) or a default constructor that is user-provided
4809 // or deleted, then the object is default-initialized;
4810 //
4811 // Note that the C++11 rule is the same as the C++98 rule if there are no
4812 // defaulted or deleted constructors, so we just use it unconditionally.
4813 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4814 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4815 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004816
Richard Smith1bfe0682012-02-14 21:14:13 +00004817 // -- if T is a (possibly cv-qualified) non-union class type without a
4818 // user-provided or deleted default constructor, then the object is
4819 // zero-initialized and, if T has a non-trivial default constructor,
4820 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004821 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4822 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004823 if (NeedZeroInitialization)
4824 Sequence.AddZeroInitializationStep(Entity.getType());
4825
Richard Smith593f9932012-12-08 02:01:17 +00004826 // C++03:
4827 // -- if T is a non-union class type without a user-declared constructor,
4828 // then every non-static data member and base class component of T is
4829 // value-initialized;
4830 // [...] A program that calls for [...] value-initialization of an
4831 // entity of reference type is ill-formed.
4832 //
4833 // C++11 doesn't need this handling, because value-initialization does not
4834 // occur recursively there, and the implicit default constructor is
4835 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004836 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004837 ClassDecl->hasUninitializedReferenceMember()) {
4838 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4839 return;
4840 }
4841
Richard Smithd86812d2012-07-05 08:39:21 +00004842 // If this is list-value-initialization, pass the empty init list on when
4843 // building the constructor call. This affects the semantics of a few
4844 // things (such as whether an explicit default constructor can be called).
4845 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004846 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004847 bool InitListSyntax = InitList;
4848
Richard Smith81f5ade2016-12-15 02:28:18 +00004849 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004850 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4851 return TryConstructorInitialization(
4852 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004853 }
4854 }
4855
Douglas Gregor1b303932009-12-22 15:35:07 +00004856 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004857}
4858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004859/// Attempt default initialization (C++ [dcl.init]p6).
Douglas Gregor85dabae2009-12-16 01:38:02 +00004860static void TryDefaultInitialization(Sema &S,
4861 const InitializedEntity &Entity,
4862 const InitializationKind &Kind,
4863 InitializationSequence &Sequence) {
4864 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865
Douglas Gregor85dabae2009-12-16 01:38:02 +00004866 // C++ [dcl.init]p6:
4867 // To default-initialize an object of type T means:
4868 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004869 QualType DestType = S.Context.getBaseElementType(Entity.getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00004870
Douglas Gregor85dabae2009-12-16 01:38:02 +00004871 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4872 // constructor for T is called (and the initialization is ill-formed if
4873 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004874 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004875 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4876 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004877 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879
Douglas Gregor85dabae2009-12-16 01:38:02 +00004880 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881
Douglas Gregor85dabae2009-12-16 01:38:02 +00004882 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004884 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004885 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004886 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4887 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004888 return;
4889 }
4890
4891 // If the destination type has a lifetime property, zero-initialize it.
4892 if (DestType.getQualifiers().hasObjCLifetime()) {
4893 Sequence.AddZeroInitializationStep(Entity.getType());
4894 return;
4895 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004896}
4897
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004898/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004899/// which enumerates all conversion functions and performs overload resolution
4900/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004902 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004903 const InitializationKind &Kind,
4904 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004905 InitializationSequence &Sequence,
4906 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004907 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4908 QualType SourceType = Initializer->getType();
4909 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4910 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Douglas Gregor540c3b02009-12-14 17:27:33 +00004912 // Build the candidate set directly in the initialization sequence
4913 // structure, so that it will persist if we fail.
4914 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004915 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916
Douglas Gregor540c3b02009-12-14 17:27:33 +00004917 // Determine whether we are allowed to call explicit constructors or
4918 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004919 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920
Douglas Gregor540c3b02009-12-14 17:27:33 +00004921 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4922 // The type we're converting to is a class type. Enumerate its constructors
4923 // to see if there is a suitable conversion.
4924 CXXRecordDecl *DestRecordDecl
4925 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004926
Douglas Gregord9848152010-04-26 14:36:57 +00004927 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004928 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004929 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004930 auto Info = getConstructorInfo(D);
4931 if (!Info.Constructor)
4932 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933
Richard Smithc2bebe92016-05-11 20:37:46 +00004934 if (!Info.Constructor->isInvalidDecl() &&
4935 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4936 if (Info.ConstructorTmpl)
4937 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004938 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004939 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004940 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004941 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004942 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004943 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004944 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004946 }
Douglas Gregord9848152010-04-26 14:36:57 +00004947 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004948 }
Eli Friedman78275202009-12-19 08:11:05 +00004949
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004950 SourceLocation DeclLoc = Initializer->getBeginLoc();
Eli Friedman78275202009-12-19 08:11:05 +00004951
Douglas Gregor540c3b02009-12-14 17:27:33 +00004952 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4953 // The type we're converting from is a class type, enumerate its conversion
4954 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004955
Eli Friedman4afe9a32009-12-20 22:12:03 +00004956 // We can only enumerate the conversion functions for a complete type; if
4957 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004958 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004959 CXXRecordDecl *SourceRecordDecl
4960 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004962 const auto &Conversions =
4963 SourceRecordDecl->getVisibleConversionFunctions();
4964 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004965 NamedDecl *D = *I;
4966 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4967 if (isa<UsingShadowDecl>(D))
4968 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969
Eli Friedman4afe9a32009-12-20 22:12:03 +00004970 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4971 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004972 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004973 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004974 else
John McCallda4458e2010-03-31 01:36:47 +00004975 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004976
Eli Friedman4afe9a32009-12-20 22:12:03 +00004977 if (AllowExplicit || !Conv->isExplicit()) {
4978 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004979 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004980 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004981 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004982 else
John McCalla0296f72010-03-19 07:35:19 +00004983 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004984 Initializer, DestType, CandidateSet,
4985 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004986 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004987 }
4988 }
4989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004990
4991 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004992 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004993 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004994 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004995 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004997 Result);
4998 return;
4999 }
John McCall0d1da222010-01-12 00:44:57 +00005000
Douglas Gregor540c3b02009-12-14 17:27:33 +00005001 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00005002 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005003 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005004
Douglas Gregor540c3b02009-12-14 17:27:33 +00005005 if (isa<CXXConstructorDecl>(Function)) {
5006 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00005007 // subsumed by the initialization. Per DR5, the created temporary is of the
5008 // cv-unqualified type of the destination.
5009 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5010 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005011 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00005012
5013 // C++14 and before:
5014 // - if the function is a constructor, the call initializes a temporary
5015 // of the cv-unqualified version of the destination type. The [...]
5016 // temporary [...] is then used to direct-initialize, according to the
5017 // rules above, the object that is the destination of the
5018 // copy-initialization.
5019 // Note that this just performs a simple object copy from the temporary.
5020 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005021 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00005022 // - if the function is a constructor, the call is a prvalue of the
5023 // cv-unqualified version of the destination type whose return object
5024 // is initialized by the constructor. The call is used to
5025 // direct-initialize, according to the rules above, the object that
5026 // is the destination of the copy-initialization.
5027 // Therefore we need to do nothing further.
5028 //
5029 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005030 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00005031 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00005032 else if (DestType.hasQualifiers())
5033 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00005034 return;
5035 }
5036
5037 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005038 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005039 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5040 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Richard Smithb8c0f552016-12-09 18:49:13 +00005042 if (ConvType->getAs<RecordType>()) {
5043 // The call is used to direct-initialize [...] the object that is the
5044 // destination of the copy-initialization.
5045 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005046 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00005047 // - If the initializer expression is a prvalue and the cv-unqualified
5048 // version of the source type is the same as the class of the
5049 // destination [... do not make an extra copy]
5050 //
5051 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005052 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00005053 Function->getReturnType()->isReferenceType() ||
5054 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5055 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00005056 else if (!S.Context.hasSameType(ConvType, DestType))
5057 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00005058 return;
5059 }
5060
Douglas Gregor5ab11652010-04-17 22:01:05 +00005061 // If the conversion following the call to the conversion function
5062 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00005063 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5064 Best->FinalConversion.Third) {
5065 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00005066 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00005067 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005068 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00005069 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005070}
5071
Richard Smithf032001b2013-06-20 02:18:31 +00005072/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5073/// a function with a pointer return type contains a 'return false;' statement.
5074/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5075/// code using that header.
5076///
5077/// Work around this by treating 'return false;' as zero-initializing the result
5078/// if it's used in a pointer-returning function in a system header.
5079static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5080 const InitializedEntity &Entity,
5081 const Expr *Init) {
5082 return S.getLangOpts().CPlusPlus11 &&
5083 Entity.getKind() == InitializedEntity::EK_Result &&
5084 Entity.getType()->isPointerType() &&
5085 isa<CXXBoolLiteralExpr>(Init) &&
5086 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5087 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5088}
5089
John McCall31168b02011-06-15 23:02:42 +00005090/// The non-zero enum values here are indexes into diagnostic alternatives.
5091enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5092
5093/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00005094static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005095 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00005096 // Skip parens.
5097 e = e->IgnoreParens();
5098
5099 // Skip address-of nodes.
5100 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5101 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005102 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5103 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005104
5105 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005106 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5107 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005108 case CK_Dependent:
5109 case CK_BitCast:
5110 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005111 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005112 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005113
5114 case CK_ArrayToPointerDecay:
5115 return IIK_nonscalar;
5116
5117 case CK_NullToPointer:
5118 return IIK_okay;
5119
5120 default:
5121 break;
5122 }
5123
5124 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005125 } else if (isa<DeclRefExpr>(e)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005126 // set isWeakAccess to true, to mean that there will be an implicit
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005127 // load which requires a cleanup.
5128 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5129 isWeakAccess = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00005130
John McCall63f84442011-06-27 23:59:58 +00005131 if (!isAddressOf) return IIK_nonlocal;
5132
John McCall113bee02012-03-10 09:33:50 +00005133 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5134 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005135
5136 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005137
5138 // If we have a conditional operator, check both sides.
5139 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005140 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5141 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005142 return iik;
5143
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005144 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005145
5146 // These are never scalar.
5147 } else if (isa<ArraySubscriptExpr>(e)) {
5148 return IIK_nonscalar;
5149
5150 // Otherwise, it needs to be a null pointer constant.
5151 } else {
5152 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5153 ? IIK_okay : IIK_nonlocal);
5154 }
5155
5156 return IIK_nonlocal;
5157}
5158
5159/// Check whether the given expression is a valid operand for an
5160/// indirect copy/restore.
5161static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5162 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005163 bool isWeakAccess = false;
5164 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
Fangrui Song6907ce22018-07-30 19:24:48 +00005165 // If isWeakAccess to true, there will be an implicit
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005166 // load which requires a cleanup.
5167 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005168 S.Cleanup.setExprNeedsCleanups(true);
5169
John McCall31168b02011-06-15 23:02:42 +00005170 if (iik == IIK_okay) return;
5171
5172 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5173 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5174 << src->getSourceRange();
5175}
5176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005177/// Determine whether we have compatible array types for the
Douglas Gregore2f943b2011-02-22 18:29:51 +00005178/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005179static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005180 const ArrayType *Source) {
5181 // If the source and destination array types are equivalent, we're
5182 // done.
5183 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5184 return true;
5185
5186 // Make sure that the element types are the same.
5187 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5188 return false;
5189
5190 // The only mismatch we allow is when the destination is an
5191 // incomplete array type and the source is a constant array type.
5192 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5193}
5194
John McCall31168b02011-06-15 23:02:42 +00005195static bool tryObjCWritebackConversion(Sema &S,
5196 InitializationSequence &Sequence,
5197 const InitializedEntity &Entity,
5198 Expr *Initializer) {
5199 bool ArrayDecay = false;
5200 QualType ArgType = Initializer->getType();
5201 QualType ArgPointee;
5202 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5203 ArrayDecay = true;
5204 ArgPointee = ArgArrayType->getElementType();
5205 ArgType = S.Context.getPointerType(ArgPointee);
5206 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005207
John McCall31168b02011-06-15 23:02:42 +00005208 // Handle write-back conversion.
5209 QualType ConvertedArgType;
5210 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5211 ConvertedArgType))
5212 return false;
5213
5214 // We should copy unless we're passing to an argument explicitly
5215 // marked 'out'.
5216 bool ShouldCopy = true;
5217 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5218 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5219
5220 // Do we need an lvalue conversion?
5221 if (ArrayDecay || Initializer->isGLValue()) {
5222 ImplicitConversionSequence ICS;
5223 ICS.setStandard();
5224 ICS.Standard.setAsIdentityConversion();
5225
5226 QualType ResultType;
5227 if (ArrayDecay) {
5228 ICS.Standard.First = ICK_Array_To_Pointer;
5229 ResultType = S.Context.getPointerType(ArgPointee);
5230 } else {
5231 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5232 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5233 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005234
John McCall31168b02011-06-15 23:02:42 +00005235 Sequence.AddConversionSequenceStep(ICS, ResultType);
5236 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005237
John McCall31168b02011-06-15 23:02:42 +00005238 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5239 return true;
5240}
5241
Guy Benyei61054192013-02-07 10:55:47 +00005242static bool TryOCLSamplerInitialization(Sema &S,
5243 InitializationSequence &Sequence,
5244 QualType DestType,
5245 Expr *Initializer) {
5246 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005247 (!Initializer->isIntegerConstantExpr(S.Context) &&
5248 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005249 return false;
5250
5251 Sequence.AddOCLSamplerInitStep(DestType);
5252 return true;
5253}
5254
Andrew Savonichevb555b762018-10-23 15:19:20 +00005255static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5256 InitializationSequence &Sequence,
5257 QualType DestType,
5258 Expr *Initializer) {
5259 if (!S.getLangOpts().OpenCL)
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005260 return false;
5261
Andrew Savonichevb555b762018-10-23 15:19:20 +00005262 //
5263 // OpenCL 1.2 spec, s6.12.10
5264 //
5265 // The event argument can also be used to associate the
5266 // async_work_group_copy with a previous async copy allowing
5267 // an event to be shared by multiple async copies; otherwise
5268 // event should be zero.
5269 //
5270 if (DestType->isEventT() || DestType->isQueueT()) {
5271 if (!Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5272 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5273 return false;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005274
Andrew Savonichevb555b762018-10-23 15:19:20 +00005275 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5276 return true;
5277 }
Egor Churaev89831422016-12-23 14:55:49 +00005278
Andrew Savonichevb555b762018-10-23 15:19:20 +00005279 return false;
Egor Churaev89831422016-12-23 14:55:49 +00005280}
5281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005282InitializationSequence::InitializationSequence(Sema &S,
5283 const InitializedEntity &Entity,
5284 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005285 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005286 bool TopLevelOfInitList,
5287 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005288 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005289 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5290 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005291}
5292
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005293/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5294/// address of that function, this returns true. Otherwise, it returns false.
5295static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5296 auto *DRE = dyn_cast<DeclRefExpr>(E);
5297 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5298 return false;
5299
5300 return !S.checkAddressOfFunctionIsAvailable(
5301 cast<FunctionDecl>(DRE->getDecl()));
5302}
5303
Richard Smith410306b2016-12-12 02:53:20 +00005304/// Determine whether we can perform an elementwise array copy for this kind
5305/// of entity.
5306static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5307 switch (Entity.getKind()) {
5308 case InitializedEntity::EK_LambdaCapture:
5309 // C++ [expr.prim.lambda]p24:
5310 // For array members, the array elements are direct-initialized in
5311 // increasing subscript order.
5312 return true;
5313
5314 case InitializedEntity::EK_Variable:
5315 // C++ [dcl.decomp]p1:
5316 // [...] each element is copy-initialized or direct-initialized from the
5317 // corresponding element of the assignment-expression [...]
5318 return isa<DecompositionDecl>(Entity.getDecl());
5319
5320 case InitializedEntity::EK_Member:
5321 // C++ [class.copy.ctor]p14:
5322 // - if the member is an array, each element is direct-initialized with
5323 // the corresponding subobject of x
5324 return Entity.isImplicitMemberInitializer();
5325
5326 case InitializedEntity::EK_ArrayElement:
5327 // All the above cases are intended to apply recursively, even though none
5328 // of them actually say that.
5329 if (auto *E = Entity.getParent())
5330 return canPerformArrayCopy(*E);
5331 break;
5332
5333 default:
5334 break;
5335 }
5336
5337 return false;
5338}
5339
Richard Smith089c3162013-09-21 21:55:46 +00005340void InitializationSequence::InitializeFrom(Sema &S,
5341 const InitializedEntity &Entity,
5342 const InitializationKind &Kind,
5343 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005344 bool TopLevelOfInitList,
5345 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005346 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005347
John McCall5e77d762013-04-16 07:28:30 +00005348 // Eliminate non-overload placeholder types in the arguments. We
5349 // need to do this before checking whether types are dependent
5350 // because lowering a pseudo-object expression might well give us
5351 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005352 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005353 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5354 // FIXME: should we be doing this here?
5355 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5356 if (result.isInvalid()) {
5357 SetFailed(FK_PlaceholderType);
5358 return;
5359 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005360 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005361 }
5362
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005363 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005364 // The semantics of initializers are as follows. The destination type is
5365 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005366 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005367 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005368 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005369 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005370
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005371 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005372 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005373 SequenceKind = DependentSequence;
5374 return;
5375 }
5376
Sebastian Redld201edf2011-06-05 13:59:11 +00005377 // Almost everything is a normal sequence.
5378 setSequenceKind(NormalSequence);
5379
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005380 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005381 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005382 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005383 Initializer = Args[0];
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005384 if (S.getLangOpts().ObjC) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005385 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005386 DestType, Initializer->getType(),
5387 Initializer) ||
5388 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5389 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005390 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005391 if (!isa<InitListExpr>(Initializer))
5392 SourceType = Initializer->getType();
5393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005394
Sebastian Redl0501c632012-02-12 16:37:36 +00005395 // - If the initializer is a (non-parenthesized) braced-init-list, the
5396 // object is list-initialized (8.5.4).
5397 if (Kind.getKind() != InitializationKind::IK_Direct) {
5398 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005399 TryListInitialization(S, Entity, Kind, InitList, *this,
5400 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005401 return;
5402 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005404
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005405 // - If the destination type is a reference type, see 8.5.3.
5406 if (DestType->isReferenceType()) {
5407 // C++0x [dcl.init.ref]p1:
5408 // A variable declared to be a T& or T&&, that is, "reference to type T"
5409 // (8.3.2), shall be initialized by an object, or function, of type T or
5410 // by an object that can be converted into a T.
5411 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005412 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005413 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005414 // C++17 [dcl.init.ref]p5:
5415 // A reference [...] is initialized by an expression [...] as follows:
5416 // If the initializer is not an expression, presumably we should reject,
5417 // but the standard fails to actually say so.
5418 else if (isa<InitListExpr>(Args[0]))
5419 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005420 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005421 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005422 return;
5423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005424
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005425 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005426 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005427 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005428 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005429 return;
5430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005431
Douglas Gregor85dabae2009-12-16 01:38:02 +00005432 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005433 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005434 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005435 return;
5436 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005437
John McCall66884dd2011-02-21 07:22:22 +00005438 // - If the destination type is an array of characters, an array of
5439 // char16_t, an array of char32_t, or an array of wchar_t, and the
5440 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005441 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005442 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005443 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005444 if (Initializer && isa<VariableArrayType>(DestAT)) {
5445 SetFailed(FK_VariableLengthArrayHasInitializer);
5446 return;
5447 }
5448
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005449 if (Initializer) {
5450 switch (IsStringInit(Initializer, DestAT, Context)) {
5451 case SIF_None:
5452 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5453 return;
5454 case SIF_NarrowStringIntoWideChar:
5455 SetFailed(FK_NarrowStringIntoWideCharArray);
5456 return;
5457 case SIF_WideStringIntoChar:
5458 SetFailed(FK_WideStringIntoCharArray);
5459 return;
5460 case SIF_IncompatWideStringIntoWideChar:
5461 SetFailed(FK_IncompatWideStringIntoWideChar);
5462 return;
Richard Smith3a8244d2018-05-01 05:02:45 +00005463 case SIF_PlainStringIntoUTF8Char:
5464 SetFailed(FK_PlainStringIntoUTF8Char);
5465 return;
5466 case SIF_UTF8StringIntoPlainChar:
5467 SetFailed(FK_UTF8StringIntoPlainChar);
5468 return;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005469 case SIF_Other:
5470 break;
5471 }
John McCall66884dd2011-02-21 07:22:22 +00005472 }
5473
Richard Smith410306b2016-12-12 02:53:20 +00005474 // Some kinds of initialization permit an array to be initialized from
5475 // another array of the same type, and perform elementwise initialization.
5476 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5477 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5478 Entity.getType()) &&
5479 canPerformArrayCopy(Entity)) {
5480 // If source is a prvalue, use it directly.
5481 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005482 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005483 return;
5484 }
5485
5486 // Emit element-at-a-time copy loop.
5487 InitializedEntity Element =
5488 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5489 QualType InitEltT =
5490 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005491 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5492 Initializer->getValueKind(),
5493 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005494 Expr *OVEAsExpr = &OVE;
5495 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5496 TreatUnavailableAsInvalid);
5497 if (!Failed())
5498 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5499 return;
5500 }
5501
Douglas Gregore2f943b2011-02-22 18:29:51 +00005502 // Note: as an GNU C extension, we allow initialization of an
5503 // array from a compound literal that creates an array of the same
5504 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005505 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005506 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5507 Initializer->getType()->isArrayType()) {
5508 const ArrayType *SourceAT
5509 = Context.getAsArrayType(Initializer->getType());
5510 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005511 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005512 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005513 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005514 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005515 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005516 }
Richard Smithebeed412012-02-15 22:38:09 +00005517 }
Richard Smithd86812d2012-07-05 08:39:21 +00005518 // Note: as a GNU C++ extension, we allow list-initialization of a
5519 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005520 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005521 Entity.getKind() == InitializedEntity::EK_Member &&
5522 Initializer && isa<InitListExpr>(Initializer)) {
5523 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005524 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005525 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005526 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005527 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005528 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5529 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005530 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005531 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005532
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005533 return;
5534 }
Eli Friedman78275202009-12-19 08:11:05 +00005535
Larisse Voufod2010992015-01-24 23:09:54 +00005536 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005537 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005538 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005539 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005540
5541 // We're at the end of the line for C: it's either a write-back conversion
5542 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005543 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005544 // If allowed, check whether this is an Objective-C writeback conversion.
5545 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005546 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005547 return;
5548 }
Guy Benyei61054192013-02-07 10:55:47 +00005549
5550 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5551 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005552
Andrew Savonichevb555b762018-10-23 15:19:20 +00005553 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005554 return;
5555
John McCall31168b02011-06-15 23:02:42 +00005556 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005557 AddCAssignmentStep(DestType);
5558 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005559 return;
5560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005561
David Blaikiebbafb8a2012-03-11 07:00:24 +00005562 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005563
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005564 // - If the destination type is a (possibly cv-qualified) class type:
5565 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566 // - If the initialization is direct-initialization, or if it is
5567 // copy-initialization where the cv-unqualified version of the
5568 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005569 // class of the destination, constructors are considered. [...]
5570 if (Kind.getKind() == InitializationKind::IK_Direct ||
5571 (Kind.getKind() == InitializationKind::IK_Copy &&
5572 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005573 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005574 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005575 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005577 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005578 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005579 // used) to a derived class thereof are enumerated as described in
5580 // 13.3.1.4, and the best one is chosen through overload resolution
5581 // (13.3).
5582 else
Richard Smith77be48a2014-07-31 06:31:19 +00005583 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005584 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005585 return;
5586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005587
Richard Smith49a6b6e2017-03-24 01:14:25 +00005588 assert(Args.size() >= 1 && "Zero-argument case handled above");
5589
5590 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005591 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005592 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005593 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005594 } else if (isa<InitListExpr>(Args[0])) {
5595 SetFailed(FK_ParenthesizedListInitForScalar);
5596 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598
5599 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005600 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005601 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005602 // For a conversion to _Atomic(T) from either T or a class type derived
5603 // from T, initialize the T object then convert to _Atomic type.
5604 bool NeedAtomicConversion = false;
5605 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5606 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005607 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
Richard Smith0f59cb32015-12-18 21:45:41 +00005608 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005609 DestType = Atomic->getValueType();
5610 NeedAtomicConversion = true;
5611 }
5612 }
5613
5614 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005615 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005616 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005617 if (!Failed() && NeedAtomicConversion)
5618 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005619 return;
5620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005621
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005622 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005623 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005624 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005626 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005627
John McCall31168b02011-06-15 23:02:42 +00005628 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005629 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005630 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005631 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005632 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005633 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5634 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005635
5636 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005637 ICS.Standard.Second == ICK_Writeback_Conversion) {
5638 // Objective-C ARC writeback conversion.
Fangrui Song6907ce22018-07-30 19:24:48 +00005639
John McCall31168b02011-06-15 23:02:42 +00005640 // We should copy unless we're passing to an argument explicitly
5641 // marked 'out'.
5642 bool ShouldCopy = true;
5643 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5644 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
Fangrui Song6907ce22018-07-30 19:24:48 +00005645
John McCall31168b02011-06-15 23:02:42 +00005646 // If there was an lvalue adjustment, add it as a separate conversion.
5647 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5648 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5649 ImplicitConversionSequence LvalueICS;
5650 LvalueICS.setStandard();
5651 LvalueICS.Standard.setAsIdentityConversion();
5652 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5653 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005654 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005655 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005656
Richard Smith77be48a2014-07-31 06:31:19 +00005657 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005658 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005659 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005660 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5661 AddZeroInitializationStep(Entity.getType());
5662 } else if (Initializer->getType() == Context.OverloadTy &&
5663 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5664 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005665 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005666 else if (Initializer->getType()->isFunctionType() &&
5667 isExprAnUnaddressableFunction(S, Initializer))
5668 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005669 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005670 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005671 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005672 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005673
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005674 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005675 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005676}
5677
5678InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005679 for (auto &S : Steps)
5680 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005681}
5682
5683//===----------------------------------------------------------------------===//
5684// Perform initialization
5685//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005687getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005688 switch(Entity.getKind()) {
5689 case InitializedEntity::EK_Variable:
5690 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005691 case InitializedEntity::EK_Exception:
5692 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005693 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005694 return Sema::AA_Initializing;
5695
5696 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005697 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005698 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5699 return Sema::AA_Sending;
5700
Douglas Gregore1314a62009-12-18 05:02:21 +00005701 return Sema::AA_Passing;
5702
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005703 case InitializedEntity::EK_Parameter_CF_Audited:
5704 if (Entity.getDecl() &&
5705 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5706 return Sema::AA_Sending;
Fangrui Song6907ce22018-07-30 19:24:48 +00005707
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005708 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
Fangrui Song6907ce22018-07-30 19:24:48 +00005709
Douglas Gregore1314a62009-12-18 05:02:21 +00005710 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005711 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
Douglas Gregore1314a62009-12-18 05:02:21 +00005712 return Sema::AA_Returning;
5713
Douglas Gregore1314a62009-12-18 05:02:21 +00005714 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005715 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005716 // FIXME: Can we tell apart casting vs. converting?
5717 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005718
Douglas Gregore1314a62009-12-18 05:02:21 +00005719 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005720 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005721 case InitializedEntity::EK_ArrayElement:
5722 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005723 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005724 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005725 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005726 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005727 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005728 return Sema::AA_Initializing;
5729 }
5730
David Blaikie8a40f702012-01-17 06:56:22 +00005731 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005732}
5733
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005734/// Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005735/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005736static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005737 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005738 case InitializedEntity::EK_ArrayElement:
5739 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005740 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005741 case InitializedEntity::EK_StmtExprResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005742 case InitializedEntity::EK_New:
5743 case InitializedEntity::EK_Variable:
5744 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005745 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005746 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005747 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005748 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005749 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005750 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005751 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005752 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005753 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005754
Douglas Gregore1314a62009-12-18 05:02:21 +00005755 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005756 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005757 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005758 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005759 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005760 return true;
5761 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005762
Douglas Gregore1314a62009-12-18 05:02:21 +00005763 llvm_unreachable("missed an InitializedEntity kind?");
5764}
5765
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005766/// Whether the given entity, when initialized with an object
Douglas Gregor95562572010-04-24 23:45:46 +00005767/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005768static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005769 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005770 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005771 case InitializedEntity::EK_StmtExprResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005772 case InitializedEntity::EK_New:
5773 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005774 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005775 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005776 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005777 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005778 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005779 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005780 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005781
Richard Smith27874d62013-01-08 00:08:23 +00005782 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005783 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005784 case InitializedEntity::EK_Variable:
5785 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005786 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005787 case InitializedEntity::EK_Temporary:
5788 case InitializedEntity::EK_ArrayElement:
5789 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005790 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005791 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005792 return true;
5793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005794
5795 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005796}
5797
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005798/// Get the location at which initialization diagnostics should appear.
Richard Smithc620f552011-10-19 16:55:56 +00005799static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5800 Expr *Initializer) {
5801 switch (Entity.getKind()) {
5802 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005803 case InitializedEntity::EK_StmtExprResult:
Richard Smithc620f552011-10-19 16:55:56 +00005804 return Entity.getReturnLoc();
5805
5806 case InitializedEntity::EK_Exception:
5807 return Entity.getThrowLoc();
5808
5809 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005810 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005811 return Entity.getDecl()->getLocation();
5812
Douglas Gregor19666fb2012-02-15 16:57:26 +00005813 case InitializedEntity::EK_LambdaCapture:
5814 return Entity.getCaptureLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00005815
Richard Smithc620f552011-10-19 16:55:56 +00005816 case InitializedEntity::EK_ArrayElement:
5817 case InitializedEntity::EK_Member:
5818 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005819 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005820 case InitializedEntity::EK_Temporary:
5821 case InitializedEntity::EK_New:
5822 case InitializedEntity::EK_Base:
5823 case InitializedEntity::EK_Delegating:
5824 case InitializedEntity::EK_VectorElement:
5825 case InitializedEntity::EK_ComplexElement:
5826 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005827 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005828 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005829 case InitializedEntity::EK_RelatedResult:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005830 return Initializer->getBeginLoc();
Richard Smithc620f552011-10-19 16:55:56 +00005831 }
5832 llvm_unreachable("missed an InitializedEntity kind?");
5833}
5834
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005835/// Make a (potentially elidable) temporary copy of the object
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005836/// provided by the given initializer by calling the appropriate copy
5837/// constructor.
5838///
5839/// \param S The Sema object used for type-checking.
5840///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005841/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005842/// the type of the initializer expression or a superclass thereof.
5843///
James Dennett634962f2012-06-14 21:40:34 +00005844/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005845///
5846/// \param CurInit The initializer expression.
5847///
5848/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5849/// is permitted in C++03 (but not C++0x) when binding a reference to
5850/// an rvalue.
5851///
5852/// \returns An expression that copies the initializer expression into
5853/// a temporary object, or an error expression if a copy could not be
5854/// created.
John McCalldadc5752010-08-24 06:29:42 +00005855static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005856 QualType T,
5857 const InitializedEntity &Entity,
5858 ExprResult CurInit,
5859 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005860 if (CurInit.isInvalid())
5861 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005862 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005863 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005864 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005865 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005866 Class = cast<CXXRecordDecl>(Record->getDecl());
5867 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005868 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005869
Richard Smithc620f552011-10-19 16:55:56 +00005870 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005871
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005872 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005873 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005874 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005875
Richard Smith7c2bcc92016-09-07 02:14:33 +00005876 // Perform overload resolution using the class's constructors. Per
5877 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005878 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005879 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005880 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005881
Douglas Gregore1314a62009-12-18 05:02:21 +00005882 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005883 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005884 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005885 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5886 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5887 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005888 case OR_Success:
5889 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005890
Douglas Gregore1314a62009-12-18 05:02:21 +00005891 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005892 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5893 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5894 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005895 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005896 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005897 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005898 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005899 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005900 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005901
Douglas Gregore1314a62009-12-18 05:02:21 +00005902 case OR_Ambiguous:
5903 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005904 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005905 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005906 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005907 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005908
Douglas Gregore1314a62009-12-18 05:02:21 +00005909 case OR_Deleted:
5910 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005911 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005912 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005913 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005914 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005915 }
5916
Richard Smith7c2bcc92016-09-07 02:14:33 +00005917 bool HadMultipleCandidates = CandidateSet.size() > 1;
5918
Douglas Gregor5ab11652010-04-17 22:01:05 +00005919 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005920 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005921 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005922
Richard Smith5179eb72016-06-28 19:03:57 +00005923 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5924 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005925
5926 if (IsExtraneousCopy) {
5927 // If this is a totally extraneous copy for C++03 reference
5928 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005929 // expression. We don't generate an (elided) copy operation here
5930 // because doing so would require us to pass down a flag to avoid
5931 // infinite recursion, where each step adds another extraneous,
5932 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005933
Douglas Gregor30b52772010-04-18 07:57:34 +00005934 // Instantiate the default arguments of any extra parameters in
5935 // the selected copy constructor, as if we were going to create a
5936 // proper call to the copy constructor.
5937 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5938 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5939 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005940 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005941 break;
5942
5943 // Build the default argument expression; we don't actually care
5944 // if this succeeds or not, because this routine will complain
5945 // if there was a problem.
5946 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5947 }
5948
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005949 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005951
Douglas Gregor5ab11652010-04-17 22:01:05 +00005952 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005953 // constructor call (we might have derived-to-base conversions, or
5954 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005955 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005956 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005957
Richard Smith7c2bcc92016-09-07 02:14:33 +00005958 // C++0x [class.copy]p32:
5959 // When certain criteria are met, an implementation is allowed to
5960 // omit the copy/move construction of a class object, even if the
5961 // copy/move constructor and/or destructor for the object have
5962 // side effects. [...]
5963 // - when a temporary class object that has not been bound to a
5964 // reference (12.2) would be copied/moved to a class object
5965 // with the same cv-unqualified type, the copy/move operation
5966 // can be omitted by constructing the temporary object
5967 // directly into the target of the omitted copy/move
5968 //
5969 // Note that the other three bullets are handled elsewhere. Copy
5970 // elision for return statements and throw expressions are handled as part
5971 // of constructor initialization, while copy elision for exception handlers
5972 // is handled by the run-time.
5973 //
5974 // FIXME: If the function parameter is not the same type as the temporary, we
5975 // should still be able to elide the copy, but we don't have a way to
5976 // represent in the AST how much should be elided in this case.
5977 bool Elidable =
5978 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5979 S.Context.hasSameUnqualifiedType(
5980 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5981 CurInitExpr->getType());
5982
Douglas Gregord0ace022010-04-25 00:55:24 +00005983 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00005984 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5985 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005986 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005987 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005988 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005989 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005990 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005991 CXXConstructExpr::CK_Complete,
5992 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005993
Douglas Gregord0ace022010-04-25 00:55:24 +00005994 // If we're supposed to bind temporaries, do so.
5995 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005996 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005997 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005998}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005999
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006000/// Check whether elidable copy construction for binding a reference to
Richard Smithc620f552011-10-19 16:55:56 +00006001/// a temporary would have succeeded if we were building in C++98 mode, for
6002/// -Wc++98-compat.
6003static void CheckCXX98CompatAccessibleCopy(Sema &S,
6004 const InitializedEntity &Entity,
6005 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006006 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00006007
6008 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6009 if (!Record)
6010 return;
6011
6012 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006013 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00006014 return;
6015
6016 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00006017 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00006018 DeclContext::lookup_result Ctors =
6019 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00006020
6021 // Perform overload resolution.
6022 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00006023 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00006024 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00006025 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6026 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6027 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00006028
6029 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6030 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6031 << CurInitExpr->getSourceRange();
6032
6033 switch (OR) {
6034 case OR_Success:
6035 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00006036 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00006037 // FIXME: Check default arguments as far as that's possible.
6038 break;
6039
6040 case OR_No_Viable_Function:
6041 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006042 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00006043 break;
6044
6045 case OR_Ambiguous:
6046 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006047 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00006048 break;
6049
6050 case OR_Deleted:
6051 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00006052 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00006053 break;
6054 }
6055}
6056
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006057void InitializationSequence::PrintInitLocationNote(Sema &S,
6058 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006059 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006060 if (Entity.getDecl()->getLocation().isInvalid())
6061 return;
6062
6063 if (Entity.getDecl()->getDeclName())
6064 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6065 << Entity.getDecl()->getDeclName();
6066 else
6067 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6068 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006069 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6070 Entity.getMethodDecl())
6071 S.Diag(Entity.getMethodDecl()->getLocation(),
6072 diag::note_method_return_type_change)
6073 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006074}
6075
Jordan Rose6c0505e2013-05-06 16:48:12 +00006076/// Returns true if the parameters describe a constructor initialization of
6077/// an explicit temporary object, e.g. "Point(x, y)".
6078static bool isExplicitTemporary(const InitializedEntity &Entity,
6079 const InitializationKind &Kind,
6080 unsigned NumArgs) {
6081 switch (Entity.getKind()) {
6082 case InitializedEntity::EK_Temporary:
6083 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006084 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006085 break;
6086 default:
6087 return false;
6088 }
6089
6090 switch (Kind.getKind()) {
6091 case InitializationKind::IK_DirectList:
6092 return true;
6093 // FIXME: Hack to work around cast weirdness.
6094 case InitializationKind::IK_Direct:
6095 case InitializationKind::IK_Value:
6096 return NumArgs != 1;
6097 default:
6098 return false;
6099 }
6100}
6101
Sebastian Redled2e5322011-12-22 14:44:04 +00006102static ExprResult
6103PerformConstructorInitialization(Sema &S,
6104 const InitializedEntity &Entity,
6105 const InitializationKind &Kind,
6106 MultiExprArg Args,
6107 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006108 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006109 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006110 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006111 SourceLocation LBraceLoc,
6112 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006113 unsigned NumArgs = Args.size();
6114 CXXConstructorDecl *Constructor
6115 = cast<CXXConstructorDecl>(Step.Function.Function);
6116 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6117
6118 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006119 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006120 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6121 ? Kind.getEqualLoc()
6122 : Kind.getLocation();
6123
6124 if (Kind.getKind() == InitializationKind::IK_Default) {
6125 // Force even a trivial, implicit default constructor to be
6126 // semantically checked. We do this explicitly because we don't build
6127 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006128 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006129 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006130 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006131 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6132 }
6133
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006134 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006135
Douglas Gregor6073dca2012-02-24 23:56:31 +00006136 // C++ [over.match.copy]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00006137 // - When initializing a temporary to be bound to the first parameter
6138 // of a constructor that takes a reference to possibly cv-qualified
6139 // T as its first argument, called with a single argument in the
Douglas Gregor6073dca2012-02-24 23:56:31 +00006140 // context of direct-initialization, explicit conversion functions
6141 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006142 bool AllowExplicitConv =
6143 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6144 hasCopyOrMoveCtorParam(S.Context,
6145 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006146
Sebastian Redled2e5322011-12-22 14:44:04 +00006147 // Determine the arguments required to actually perform the constructor
6148 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006149 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006150 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006151 AllowExplicitConv,
6152 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006153 return ExprError();
6154
6155
Jordan Rose6c0505e2013-05-06 16:48:12 +00006156 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006157 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006158 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6159 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006160
6161 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6162 if (!TSInfo)
6163 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumara14a1f92018-01-17 18:53:51 +00006164 SourceRange ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006165
Richard Smith5179eb72016-06-28 19:03:57 +00006166 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006167 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006168 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006169 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6170 return ExprError();
6171 }
Richard Smith5179eb72016-06-28 19:03:57 +00006172 S.MarkFunctionReferenced(Loc, Constructor);
6173
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006174 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00006175 S.Context, Constructor,
6176 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006177 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6178 IsListInitialization, IsStdInitListInitialization,
6179 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006180 } else {
6181 CXXConstructExpr::ConstructionKind ConstructKind =
6182 CXXConstructExpr::CK_Complete;
6183
6184 if (Entity.getKind() == InitializedEntity::EK_Base) {
6185 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6186 CXXConstructExpr::CK_VirtualBase :
6187 CXXConstructExpr::CK_NonVirtualBase;
6188 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6189 ConstructKind = CXXConstructExpr::CK_Delegating;
6190 }
6191
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006192 // Only get the parenthesis or brace range if it is a list initialization or
6193 // direct construction.
6194 SourceRange ParenOrBraceRange;
6195 if (IsListInitialization)
6196 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6197 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006198 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006199
6200 // If the entity allows NRVO, mark the construction as elidable
6201 // unconditionally.
6202 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006203 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006204 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006205 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006206 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006207 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006208 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006209 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006210 ConstructorInitRequiresZeroInit,
6211 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006212 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006213 else
Richard Smith410306b2016-12-12 02:53:20 +00006214 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006215 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006216 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006217 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006218 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006219 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006220 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006221 ConstructorInitRequiresZeroInit,
6222 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006223 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006224 }
6225 if (CurInit.isInvalid())
6226 return ExprError();
6227
6228 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006229 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006230 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6231 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006232
6233 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006234 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006235
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006236 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006237}
6238
Richard Smithd87aab92018-07-17 22:24:09 +00006239namespace {
6240enum LifetimeKind {
6241 /// The lifetime of a temporary bound to this entity ends at the end of the
6242 /// full-expression, and that's (probably) fine.
6243 LK_FullExpression,
6244
6245 /// The lifetime of a temporary bound to this entity is extended to the
6246 /// lifeitme of the entity itself.
6247 LK_Extended,
6248
6249 /// The lifetime of a temporary bound to this entity probably ends too soon,
6250 /// because the entity is allocated in a new-expression.
6251 LK_New,
6252
6253 /// The lifetime of a temporary bound to this entity ends too soon, because
6254 /// the entity is a return object.
6255 LK_Return,
6256
Richard Smith67af95b2018-07-23 19:19:08 +00006257 /// The lifetime of a temporary bound to this entity ends too soon, because
6258 /// the entity is the result of a statement expression.
6259 LK_StmtExprResult,
6260
Richard Smithd87aab92018-07-17 22:24:09 +00006261 /// This is a mem-initializer: if it would extend a temporary (other than via
6262 /// a default member initializer), the program is ill-formed.
6263 LK_MemInitializer,
6264};
6265using LifetimeResult =
6266 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6267}
6268
Richard Smithe6c01442013-06-05 00:46:14 +00006269/// Determine the declaration which an initialized entity ultimately refers to,
6270/// for the purpose of lifetime-extending a temporary bound to a reference in
6271/// the initialization of \p Entity.
Richard Smithca975b22018-07-23 18:50:26 +00006272static LifetimeResult getEntityLifetime(
David Majnemerdaff3702014-05-01 17:50:17 +00006273 const InitializedEntity *Entity,
Richard Smithd87aab92018-07-17 22:24:09 +00006274 const InitializedEntity *InitField = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006275 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006276 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006277 case InitializedEntity::EK_Variable:
6278 // The temporary [...] persists for the lifetime of the reference
Richard Smithd87aab92018-07-17 22:24:09 +00006279 return {Entity, LK_Extended};
Richard Smithe6c01442013-06-05 00:46:14 +00006280
6281 case InitializedEntity::EK_Member:
6282 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006283 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006284 return getEntityLifetime(Entity->getParent(), Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006285
6286 // except:
Richard Smithd87aab92018-07-17 22:24:09 +00006287 // C++17 [class.base.init]p8:
6288 // A temporary expression bound to a reference member in a
6289 // mem-initializer is ill-formed.
6290 // C++17 [class.base.init]p11:
6291 // A temporary expression bound to a reference member from a
6292 // default member initializer is ill-formed.
6293 //
6294 // The context of p11 and its example suggest that it's only the use of a
6295 // default member initializer from a constructor that makes the program
6296 // ill-formed, not its mere existence, and that it can even be used by
6297 // aggregate initialization.
6298 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6299 : LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006300
Richard Smith7873de02016-08-11 22:25:46 +00006301 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006302 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6303 // type.
Richard Smithd87aab92018-07-17 22:24:09 +00006304 return {Entity, LK_Extended};
Richard Smith7873de02016-08-11 22:25:46 +00006305
Richard Smithe6c01442013-06-05 00:46:14 +00006306 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006307 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006308 // -- A temporary bound to a reference parameter in a function call
6309 // persists until the completion of the full-expression containing
6310 // the call.
Richard Smithd87aab92018-07-17 22:24:09 +00006311 return {nullptr, LK_FullExpression};
6312
Richard Smithe6c01442013-06-05 00:46:14 +00006313 case InitializedEntity::EK_Result:
6314 // -- The lifetime of a temporary bound to the returned value in a
6315 // function return statement is not extended; the temporary is
6316 // destroyed at the end of the full-expression in the return statement.
Richard Smithd87aab92018-07-17 22:24:09 +00006317 return {nullptr, LK_Return};
6318
Richard Smith67af95b2018-07-23 19:19:08 +00006319 case InitializedEntity::EK_StmtExprResult:
6320 // FIXME: Should we lifetime-extend through the result of a statement
6321 // expression?
6322 return {nullptr, LK_StmtExprResult};
6323
Richard Smithe6c01442013-06-05 00:46:14 +00006324 case InitializedEntity::EK_New:
6325 // -- A temporary bound to a reference in a new-initializer persists
6326 // until the completion of the full-expression containing the
6327 // new-initializer.
Richard Smithd87aab92018-07-17 22:24:09 +00006328 return {nullptr, LK_New};
Richard Smithe6c01442013-06-05 00:46:14 +00006329
6330 case InitializedEntity::EK_Temporary:
6331 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006332 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006333 // We don't yet know the storage duration of the surrounding temporary.
6334 // Assume it's got full-expression duration for now, it will patch up our
6335 // storage duration if that's not correct.
Richard Smithd87aab92018-07-17 22:24:09 +00006336 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006337
6338 case InitializedEntity::EK_ArrayElement:
6339 // For subobjects, we look at the complete object.
Richard Smithca975b22018-07-23 18:50:26 +00006340 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithe6c01442013-06-05 00:46:14 +00006341
6342 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006343 // For subobjects, we look at the complete object.
6344 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006345 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithd87aab92018-07-17 22:24:09 +00006346 return {InitField, LK_MemInitializer};
6347
Richard Smithe6c01442013-06-05 00:46:14 +00006348 case InitializedEntity::EK_Delegating:
6349 // We can reach this case for aggregate initialization in a constructor:
6350 // struct A { int &&r; };
6351 // struct B : A { B() : A{0} {} };
Richard Smithd87aab92018-07-17 22:24:09 +00006352 // In this case, use the outermost field decl as the context.
6353 return {InitField, LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006354
6355 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006356 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006357 case InitializedEntity::EK_LambdaCapture:
Richard Smithe6c01442013-06-05 00:46:14 +00006358 case InitializedEntity::EK_VectorElement:
6359 case InitializedEntity::EK_ComplexElement:
Richard Smithd87aab92018-07-17 22:24:09 +00006360 return {nullptr, LK_FullExpression};
Richard Smithca975b22018-07-23 18:50:26 +00006361
6362 case InitializedEntity::EK_Exception:
6363 // FIXME: Can we diagnose lifetime problems with exceptions?
6364 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006365 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006366 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006367}
6368
Richard Smithd87aab92018-07-17 22:24:09 +00006369namespace {
Richard Smithca975b22018-07-23 18:50:26 +00006370enum ReferenceKind {
Richard Smithd87aab92018-07-17 22:24:09 +00006371 /// Lifetime would be extended by a reference binding to a temporary.
Richard Smithca975b22018-07-23 18:50:26 +00006372 RK_ReferenceBinding,
Richard Smithd87aab92018-07-17 22:24:09 +00006373 /// Lifetime would be extended by a std::initializer_list object binding to
6374 /// its backing array.
Richard Smithca975b22018-07-23 18:50:26 +00006375 RK_StdInitializerList,
Richard Smithd87aab92018-07-17 22:24:09 +00006376};
Richard Smithca975b22018-07-23 18:50:26 +00006377
Richard Smithafe48f92018-07-23 21:21:22 +00006378/// A temporary or local variable. This will be one of:
6379/// * A MaterializeTemporaryExpr.
6380/// * A DeclRefExpr whose declaration is a local.
6381/// * An AddrLabelExpr.
6382/// * A BlockExpr for a block with captures.
6383using Local = Expr*;
Richard Smithca975b22018-07-23 18:50:26 +00006384
6385/// Expressions we stepped over when looking for the local state. Any steps
6386/// that would inhibit lifetime extension or take us out of subexpressions of
6387/// the initializer are included.
6388struct IndirectLocalPathEntry {
Richard Smithafe48f92018-07-23 21:21:22 +00006389 enum EntryKind {
Richard Smithca975b22018-07-23 18:50:26 +00006390 DefaultInit,
6391 AddressOf,
Richard Smithafe48f92018-07-23 21:21:22 +00006392 VarInit,
6393 LValToRVal,
Richard Smithf4e248c2018-08-01 00:33:25 +00006394 LifetimeBoundCall,
Richard Smithca975b22018-07-23 18:50:26 +00006395 } Kind;
6396 Expr *E;
Richard Smithf4e248c2018-08-01 00:33:25 +00006397 const Decl *D = nullptr;
Richard Smithafe48f92018-07-23 21:21:22 +00006398 IndirectLocalPathEntry() {}
6399 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
Richard Smithf4e248c2018-08-01 00:33:25 +00006400 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
6401 : Kind(K), E(E), D(D) {}
Richard Smithca975b22018-07-23 18:50:26 +00006402};
6403
6404using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
Richard Smithe6c01442013-06-05 00:46:14 +00006405
Richard Smithd87aab92018-07-17 22:24:09 +00006406struct RevertToOldSizeRAII {
Richard Smithca975b22018-07-23 18:50:26 +00006407 IndirectLocalPath &Path;
Richard Smithd87aab92018-07-17 22:24:09 +00006408 unsigned OldSize = Path.size();
Richard Smithca975b22018-07-23 18:50:26 +00006409 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
Richard Smithd87aab92018-07-17 22:24:09 +00006410 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6411};
Richard Smithafe48f92018-07-23 21:21:22 +00006412
6413using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
6414 ReferenceKind RK)>;
Richard Smithd87aab92018-07-17 22:24:09 +00006415}
6416
Richard Smithafe48f92018-07-23 21:21:22 +00006417static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
6418 for (auto E : Path)
6419 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
6420 return true;
6421 return false;
6422}
6423
Richard Smith0e3102d2018-07-24 00:55:08 +00006424static bool pathContainsInit(IndirectLocalPath &Path) {
Fangrui Song3117b172018-10-20 17:53:42 +00006425 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
Richard Smith0e3102d2018-07-24 00:55:08 +00006426 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
6427 E.Kind == IndirectLocalPathEntry::VarInit;
6428 });
6429}
6430
Richard Smithca975b22018-07-23 18:50:26 +00006431static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6432 Expr *Init, LocalVisitor Visit,
6433 bool RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006434
Richard Smithf4e248c2018-08-01 00:33:25 +00006435static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6436 Expr *Init, ReferenceKind RK,
6437 LocalVisitor Visit);
6438
6439static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
6440 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
6441 if (!TSI)
6442 return false;
Martin Storsjod03fa992018-08-02 18:12:08 +00006443 // Don't declare this variable in the second operand of the for-statement;
6444 // GCC miscompiles that by ending its lifetime before evaluating the
6445 // third operand. See gcc.gnu.org/PR86769.
6446 AttributedTypeLoc ATL;
Richard Smithf4e248c2018-08-01 00:33:25 +00006447 for (TypeLoc TL = TSI->getTypeLoc();
Martin Storsjod03fa992018-08-02 18:12:08 +00006448 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
Richard Smithf4e248c2018-08-01 00:33:25 +00006449 TL = ATL.getModifiedLoc()) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006450 if (ATL.getAttrAs<LifetimeBoundAttr>())
Richard Smithf4e248c2018-08-01 00:33:25 +00006451 return true;
6452 }
6453 return false;
6454}
6455
6456static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
6457 LocalVisitor Visit) {
6458 const FunctionDecl *Callee;
6459 ArrayRef<Expr*> Args;
6460
6461 if (auto *CE = dyn_cast<CallExpr>(Call)) {
6462 Callee = CE->getDirectCallee();
6463 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
6464 } else {
6465 auto *CCE = cast<CXXConstructExpr>(Call);
6466 Callee = CCE->getConstructor();
6467 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
6468 }
6469 if (!Callee)
6470 return;
6471
6472 Expr *ObjectArg = nullptr;
6473 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
6474 ObjectArg = Args[0];
6475 Args = Args.slice(1);
6476 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6477 ObjectArg = MCE->getImplicitObjectArgument();
6478 }
6479
6480 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
6481 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
6482 if (Arg->isGLValue())
6483 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6484 Visit);
6485 else
6486 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6487 Path.pop_back();
6488 };
6489
6490 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
6491 VisitLifetimeBoundArg(Callee, ObjectArg);
6492
6493 for (unsigned I = 0,
6494 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
6495 I != N; ++I) {
6496 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
6497 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
6498 }
6499}
6500
Richard Smithca975b22018-07-23 18:50:26 +00006501/// Visit the locals that would be reachable through a reference bound to the
6502/// glvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006503static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6504 Expr *Init, ReferenceKind RK,
6505 LocalVisitor Visit) {
Richard Smithd87aab92018-07-17 22:24:09 +00006506 RevertToOldSizeRAII RAII(Path);
6507
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006508 // Walk past any constructs which we can lifetime-extend across.
6509 Expr *Old;
6510 do {
6511 Old = Init;
6512
Richard Smithafe48f92018-07-23 21:21:22 +00006513 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
6514 Init = EWC->getSubExpr();
6515
Richard Smithdbc82492015-01-10 01:28:13 +00006516 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithd87aab92018-07-17 22:24:09 +00006517 // If this is just redundant braces around an initializer, step over it.
6518 if (ILE->isTransparent())
Richard Smithdbc82492015-01-10 01:28:13 +00006519 Init = ILE->getInit(0);
Richard Smithdbc82492015-01-10 01:28:13 +00006520 }
6521
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006522 // Step over any subobject adjustments; we may have a materialized
6523 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006524 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006525
6526 // Per current approach for DR1376, look through casts to reference type
6527 // when performing lifetime extension.
6528 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6529 if (CE->getSubExpr()->isGLValue())
6530 Init = CE->getSubExpr();
6531
Richard Smithb3189a12016-12-05 07:49:14 +00006532 // Per the current approach for DR1299, look through array element access
Richard Smithca975b22018-07-23 18:50:26 +00006533 // on array glvalues when performing lifetime extension.
6534 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006535 Init = ASE->getBase();
6536 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
6537 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
6538 Init = ICE->getSubExpr();
6539 else
6540 // We can't lifetime extend through this but we might still find some
6541 // retained temporaries.
6542 return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
Richard Smithca975b22018-07-23 18:50:26 +00006543 }
Richard Smithd87aab92018-07-17 22:24:09 +00006544
6545 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6546 // constructor inherits one as an implicit mem-initializer.
6547 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006548 Path.push_back(
6549 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
Richard Smithd87aab92018-07-17 22:24:09 +00006550 Init = DIE->getExpr();
Richard Smithd87aab92018-07-17 22:24:09 +00006551 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006552 } while (Init != Old);
6553
Richard Smithd87aab92018-07-17 22:24:09 +00006554 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006555 if (Visit(Path, Local(MTE), RK))
6556 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
6557 true);
6558 }
6559
Richard Smithf4e248c2018-08-01 00:33:25 +00006560 if (isa<CallExpr>(Init))
6561 return visitLifetimeBoundArguments(Path, Init, Visit);
6562
Richard Smithafe48f92018-07-23 21:21:22 +00006563 switch (Init->getStmtClass()) {
6564 case Stmt::DeclRefExprClass: {
6565 // If we find the name of a local non-reference parameter, we could have a
6566 // lifetime problem.
6567 auto *DRE = cast<DeclRefExpr>(Init);
Richard Smithca975b22018-07-23 18:50:26 +00006568 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6569 if (VD && VD->hasLocalStorage() &&
6570 !DRE->refersToEnclosingVariableOrCapture()) {
Richard Smithafe48f92018-07-23 21:21:22 +00006571 if (!VD->getType()->isReferenceType()) {
6572 Visit(Path, Local(DRE), RK);
6573 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
6574 // The lifetime of a reference parameter is unknown; assume it's OK
6575 // for now.
6576 break;
6577 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
6578 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6579 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
6580 RK_ReferenceBinding, Visit);
6581 }
Richard Smithca975b22018-07-23 18:50:26 +00006582 }
Richard Smithafe48f92018-07-23 21:21:22 +00006583 break;
6584 }
6585
6586 case Stmt::UnaryOperatorClass: {
6587 // The only unary operator that make sense to handle here
6588 // is Deref. All others don't resolve to a "name." This includes
6589 // handling all sorts of rvalues passed to a unary operator.
6590 const UnaryOperator *U = cast<UnaryOperator>(Init);
6591 if (U->getOpcode() == UO_Deref)
6592 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
6593 break;
6594 }
6595
6596 case Stmt::OMPArraySectionExprClass: {
6597 visitLocalsRetainedByInitializer(
6598 Path, cast<OMPArraySectionExpr>(Init)->getBase(), Visit, true);
6599 break;
6600 }
6601
6602 case Stmt::ConditionalOperatorClass:
6603 case Stmt::BinaryConditionalOperatorClass: {
6604 auto *C = cast<AbstractConditionalOperator>(Init);
6605 if (!C->getTrueExpr()->getType()->isVoidType())
6606 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
6607 if (!C->getFalseExpr()->getType()->isVoidType())
6608 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
6609 break;
6610 }
6611
6612 // FIXME: Visit the left-hand side of an -> or ->*.
6613
6614 default:
6615 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006616 }
6617}
6618
Richard Smithca975b22018-07-23 18:50:26 +00006619/// Visit the locals that would be reachable through an object initialized by
6620/// the prvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006621static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6622 Expr *Init, LocalVisitor Visit,
6623 bool RevisitSubinits) {
Richard Smithd87aab92018-07-17 22:24:09 +00006624 RevertToOldSizeRAII RAII(Path);
6625
Richard Smithf4e248c2018-08-01 00:33:25 +00006626 Expr *Old;
6627 do {
6628 Old = Init;
Richard Smithd87aab92018-07-17 22:24:09 +00006629
Richard Smithf4e248c2018-08-01 00:33:25 +00006630 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6631 // constructor inherits one as an implicit mem-initializer.
6632 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6633 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
6634 Init = DIE->getExpr();
6635 }
Richard Smithafe48f92018-07-23 21:21:22 +00006636
Richard Smithf4e248c2018-08-01 00:33:25 +00006637 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
6638 Init = EWC->getSubExpr();
Richard Smithe6c01442013-06-05 00:46:14 +00006639
Richard Smithf4e248c2018-08-01 00:33:25 +00006640 // Dig out the expression which constructs the extended temporary.
6641 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6642
6643 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6644 Init = BTE->getSubExpr();
6645
6646 Init = Init->IgnoreParens();
6647
6648 // Step over value-preserving rvalue casts.
6649 if (auto *CE = dyn_cast<CastExpr>(Init)) {
6650 switch (CE->getCastKind()) {
6651 case CK_LValueToRValue:
6652 // If we can match the lvalue to a const object, we can look at its
6653 // initializer.
6654 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
6655 return visitLocalsRetainedByReferenceBinding(
6656 Path, Init, RK_ReferenceBinding,
6657 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
6658 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
6659 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6660 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
6661 !isVarOnPath(Path, VD)) {
6662 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6663 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true);
6664 }
6665 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
6666 if (MTE->getType().isConstQualified())
6667 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
6668 Visit, true);
6669 }
6670 return false;
6671 });
6672
6673 // We assume that objects can be retained by pointers cast to integers,
6674 // but not if the integer is cast to floating-point type or to _Complex.
6675 // We assume that casts to 'bool' do not preserve enough information to
6676 // retain a local object.
6677 case CK_NoOp:
6678 case CK_BitCast:
6679 case CK_BaseToDerived:
6680 case CK_DerivedToBase:
6681 case CK_UncheckedDerivedToBase:
6682 case CK_Dynamic:
6683 case CK_ToUnion:
6684 case CK_UserDefinedConversion:
6685 case CK_ConstructorConversion:
6686 case CK_IntegralToPointer:
6687 case CK_PointerToIntegral:
6688 case CK_VectorSplat:
6689 case CK_IntegralCast:
6690 case CK_CPointerToObjCPointerCast:
6691 case CK_BlockPointerToObjCPointerCast:
6692 case CK_AnyPointerToBlockPointerCast:
6693 case CK_AddressSpaceConversion:
6694 break;
6695
6696 case CK_ArrayToPointerDecay:
6697 // Model array-to-pointer decay as taking the address of the array
6698 // lvalue.
6699 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
6700 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
6701 RK_ReferenceBinding, Visit);
6702
6703 default:
6704 return;
6705 }
6706
6707 Init = CE->getSubExpr();
6708 }
6709 } while (Old != Init);
Richard Smith736a9472013-06-12 20:42:33 +00006710
Richard Smithd87aab92018-07-17 22:24:09 +00006711 // C++17 [dcl.init.list]p6:
6712 // initializing an initializer_list object from the array extends the
6713 // lifetime of the array exactly like binding a reference to a temporary.
6714 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
Richard Smithca975b22018-07-23 18:50:26 +00006715 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
6716 RK_StdInitializerList, Visit);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006717
Richard Smithe6c01442013-06-05 00:46:14 +00006718 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006719 // We already visited the elements of this initializer list while
6720 // performing the initialization. Don't visit them again unless we've
6721 // changed the lifetime of the initialized entity.
6722 if (!RevisitSubinits)
6723 return;
6724
Richard Smithd87aab92018-07-17 22:24:09 +00006725 if (ILE->isTransparent())
Richard Smithca975b22018-07-23 18:50:26 +00006726 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
6727 RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006728
Richard Smithcc1b96d2013-06-12 22:31:48 +00006729 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006730 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Richard Smithca975b22018-07-23 18:50:26 +00006731 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
6732 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006733 return;
6734 }
6735
Richard Smithcc1b96d2013-06-12 22:31:48 +00006736 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006737 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6738
6739 // If we lifetime-extend a braced initializer which is initializing an
6740 // aggregate, and that aggregate contains reference members which are
6741 // bound to temporaries, those temporaries are also lifetime-extended.
6742 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6743 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006744 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
6745 RK_ReferenceBinding, Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006746 else {
6747 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006748 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006749 if (Index >= ILE->getNumInits())
6750 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006751 if (I->isUnnamedBitfield())
6752 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006753 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006754 if (I->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006755 visitLocalsRetainedByReferenceBinding(Path, SubInit,
6756 RK_ReferenceBinding, Visit);
Richard Smithd87aab92018-07-17 22:24:09 +00006757 else
6758 // This might be either aggregate-initialization of a member or
6759 // initialization of a std::initializer_list object. Regardless,
Richard Smithe6c01442013-06-05 00:46:14 +00006760 // we should recursively lifetime-extend that initializer.
Richard Smithca975b22018-07-23 18:50:26 +00006761 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
6762 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006763 ++Index;
6764 }
6765 }
6766 }
Richard Smithca975b22018-07-23 18:50:26 +00006767 return;
6768 }
6769
Richard Smithb3d203f2018-10-19 19:01:34 +00006770 // The lifetime of an init-capture is that of the closure object constructed
6771 // by a lambda-expression.
6772 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
6773 for (Expr *E : LE->capture_inits()) {
6774 if (!E)
6775 continue;
6776 if (E->isGLValue())
6777 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
6778 Visit);
6779 else
6780 visitLocalsRetainedByInitializer(Path, E, Visit, true);
6781 }
6782 }
6783
Richard Smithf4e248c2018-08-01 00:33:25 +00006784 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init))
6785 return visitLifetimeBoundArguments(Path, Init, Visit);
Richard Smithafe48f92018-07-23 21:21:22 +00006786
Richard Smithafe48f92018-07-23 21:21:22 +00006787 switch (Init->getStmtClass()) {
6788 case Stmt::UnaryOperatorClass: {
6789 auto *UO = cast<UnaryOperator>(Init);
6790 // If the initializer is the address of a local, we could have a lifetime
6791 // problem.
6792 if (UO->getOpcode() == UO_AddrOf) {
Richard Smith0e3102d2018-07-24 00:55:08 +00006793 // If this is &rvalue, then it's ill-formed and we have already diagnosed
6794 // it. Don't produce a redundant warning about the lifetime of the
6795 // temporary.
6796 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
6797 return;
6798
Richard Smithafe48f92018-07-23 21:21:22 +00006799 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
6800 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
6801 RK_ReferenceBinding, Visit);
6802 }
6803 break;
6804 }
6805
6806 case Stmt::BinaryOperatorClass: {
6807 // Handle pointer arithmetic.
6808 auto *BO = cast<BinaryOperator>(Init);
6809 BinaryOperatorKind BOK = BO->getOpcode();
6810 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
6811 break;
6812
6813 if (BO->getLHS()->getType()->isPointerType())
6814 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
6815 else if (BO->getRHS()->getType()->isPointerType())
6816 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
6817 break;
6818 }
6819
6820 case Stmt::ConditionalOperatorClass:
6821 case Stmt::BinaryConditionalOperatorClass: {
6822 auto *C = cast<AbstractConditionalOperator>(Init);
6823 // In C++, we can have a throw-expression operand, which has 'void' type
6824 // and isn't interesting from a lifetime perspective.
6825 if (!C->getTrueExpr()->getType()->isVoidType())
6826 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
6827 if (!C->getFalseExpr()->getType()->isVoidType())
6828 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
6829 break;
6830 }
6831
6832 case Stmt::BlockExprClass:
6833 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
6834 // This is a local block, whose lifetime is that of the function.
6835 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
6836 }
6837 break;
6838
6839 case Stmt::AddrLabelExprClass:
6840 // We want to warn if the address of a label would escape the function.
6841 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
6842 break;
6843
6844 default:
6845 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006846 }
6847}
6848
Richard Smithd87aab92018-07-17 22:24:09 +00006849/// Determine whether this is an indirect path to a temporary that we are
6850/// supposed to lifetime-extend along (but don't).
Richard Smithca975b22018-07-23 18:50:26 +00006851static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
Richard Smithd87aab92018-07-17 22:24:09 +00006852 for (auto Elem : Path) {
Richard Smithf66e4f72018-07-23 22:56:45 +00006853 if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
Richard Smithd87aab92018-07-17 22:24:09 +00006854 return false;
6855 }
6856 return true;
6857}
6858
Richard Smith6a32c052018-07-23 21:21:24 +00006859/// Find the range for the first interesting entry in the path at or after I.
6860static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
6861 Expr *E) {
6862 for (unsigned N = Path.size(); I != N; ++I) {
6863 switch (Path[I].Kind) {
6864 case IndirectLocalPathEntry::AddressOf:
6865 case IndirectLocalPathEntry::LValToRVal:
Richard Smithf4e248c2018-08-01 00:33:25 +00006866 case IndirectLocalPathEntry::LifetimeBoundCall:
Richard Smith6a32c052018-07-23 21:21:24 +00006867 // These exist primarily to mark the path as not permitting or
6868 // supporting lifetime extension.
6869 break;
6870
6871 case IndirectLocalPathEntry::DefaultInit:
6872 case IndirectLocalPathEntry::VarInit:
6873 return Path[I].E->getSourceRange();
6874 }
6875 }
6876 return E->getSourceRange();
6877}
6878
Richard Smithd87aab92018-07-17 22:24:09 +00006879void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
6880 Expr *Init) {
Richard Smithca975b22018-07-23 18:50:26 +00006881 LifetimeResult LR = getEntityLifetime(&Entity);
Richard Smithd87aab92018-07-17 22:24:09 +00006882 LifetimeKind LK = LR.getInt();
6883 const InitializedEntity *ExtendingEntity = LR.getPointer();
6884
6885 // If this entity doesn't have an interesting lifetime, don't bother looking
6886 // for temporaries within its initializer.
6887 if (LK == LK_FullExpression)
6888 return;
6889
Richard Smithca975b22018-07-23 18:50:26 +00006890 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
6891 ReferenceKind RK) -> bool {
Richard Smith6a32c052018-07-23 21:21:24 +00006892 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
6893 SourceLocation DiagLoc = DiagRange.getBegin();
Richard Smithca975b22018-07-23 18:50:26 +00006894
Richard Smithd87aab92018-07-17 22:24:09 +00006895 switch (LK) {
6896 case LK_FullExpression:
6897 llvm_unreachable("already handled this");
6898
Richard Smithafe48f92018-07-23 21:21:22 +00006899 case LK_Extended: {
6900 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
Richard Smith0e3102d2018-07-24 00:55:08 +00006901 if (!MTE) {
6902 // The initialized entity has lifetime beyond the full-expression,
6903 // and the local entity does too, so don't warn.
6904 //
6905 // FIXME: We should consider warning if a static / thread storage
6906 // duration variable retains an automatic storage duration local.
Richard Smithafe48f92018-07-23 21:21:22 +00006907 return false;
Richard Smith0e3102d2018-07-24 00:55:08 +00006908 }
Richard Smithafe48f92018-07-23 21:21:22 +00006909
Richard Smithd87aab92018-07-17 22:24:09 +00006910 // Lifetime-extend the temporary.
6911 if (Path.empty()) {
6912 // Update the storage duration of the materialized temporary.
6913 // FIXME: Rebuild the expression instead of mutating it.
6914 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
6915 ExtendingEntity->allocateManglingNumber());
6916 // Also visit the temporaries lifetime-extended by this initializer.
6917 return true;
6918 }
6919
6920 if (shouldLifetimeExtendThroughPath(Path)) {
6921 // We're supposed to lifetime-extend the temporary along this path (per
6922 // the resolution of DR1815), but we don't support that yet.
6923 //
Richard Smith0e3102d2018-07-24 00:55:08 +00006924 // FIXME: Properly handle this situation. Perhaps the easiest approach
Richard Smithd87aab92018-07-17 22:24:09 +00006925 // would be to clone the initializer expression on each use that would
6926 // lifetime extend its temporaries.
Richard Smith0e3102d2018-07-24 00:55:08 +00006927 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
6928 << RK << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00006929 } else {
Richard Smith0e3102d2018-07-24 00:55:08 +00006930 // If the path goes through the initialization of a variable or field,
6931 // it can't possibly reach a temporary created in this full-expression.
6932 // We will have already diagnosed any problems with the initializer.
6933 if (pathContainsInit(Path))
6934 return false;
6935
6936 Diag(DiagLoc, diag::warn_dangling_variable)
Richard Smithad5bbcc2018-08-01 01:03:33 +00006937 << RK << !Entity.getParent()
6938 << ExtendingEntity->getDecl()->isImplicit()
6939 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00006940 }
6941 break;
Richard Smithafe48f92018-07-23 21:21:22 +00006942 }
Richard Smithd87aab92018-07-17 22:24:09 +00006943
Richard Smithafe48f92018-07-23 21:21:22 +00006944 case LK_MemInitializer: {
George Burgess IV06df2292018-07-24 02:10:53 +00006945 if (isa<MaterializeTemporaryExpr>(L)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006946 // Under C++ DR1696, if a mem-initializer (or a default member
6947 // initializer used by the absence of one) would lifetime-extend a
6948 // temporary, the program is ill-formed.
6949 if (auto *ExtendingDecl =
6950 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
6951 bool IsSubobjectMember = ExtendingEntity != &Entity;
Richard Smith0e3102d2018-07-24 00:55:08 +00006952 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
6953 ? diag::err_dangling_member
6954 : diag::warn_dangling_member)
Richard Smithafe48f92018-07-23 21:21:22 +00006955 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
6956 // Don't bother adding a note pointing to the field if we're inside
6957 // its default member initializer; our primary diagnostic points to
6958 // the same place in that case.
6959 if (Path.empty() ||
6960 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
6961 Diag(ExtendingDecl->getLocation(),
6962 diag::note_lifetime_extending_member_declared_here)
6963 << RK << IsSubobjectMember;
6964 }
6965 } else {
6966 // We have a mem-initializer but no particular field within it; this
6967 // is either a base class or a delegating initializer directly
6968 // initializing the base-class from something that doesn't live long
6969 // enough.
6970 //
6971 // FIXME: Warn on this.
6972 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00006973 }
6974 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00006975 // Paths via a default initializer can only occur during error recovery
6976 // (there's no other way that a default initializer can refer to a
6977 // local). Don't produce a bogus warning on those cases.
Richard Smith0e3102d2018-07-24 00:55:08 +00006978 if (pathContainsInit(Path))
Richard Smithafe48f92018-07-23 21:21:22 +00006979 return false;
6980
6981 auto *DRE = dyn_cast<DeclRefExpr>(L);
6982 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
6983 if (!VD) {
6984 // A member was initialized to a local block.
6985 // FIXME: Warn on this.
6986 return false;
6987 }
6988
6989 if (auto *Member =
6990 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
6991 bool IsPointer = Member->getType()->isAnyPointerType();
6992 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
6993 : diag::warn_bind_ref_member_to_parameter)
6994 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
6995 Diag(Member->getLocation(),
6996 diag::note_ref_or_ptr_member_declared_here)
6997 << (unsigned)IsPointer;
6998 }
Richard Smithd87aab92018-07-17 22:24:09 +00006999 }
7000 break;
Richard Smithafe48f92018-07-23 21:21:22 +00007001 }
Richard Smithd87aab92018-07-17 22:24:09 +00007002
7003 case LK_New:
George Burgess IV06df2292018-07-24 02:10:53 +00007004 if (isa<MaterializeTemporaryExpr>(L)) {
Richard Smithafe48f92018-07-23 21:21:22 +00007005 Diag(DiagLoc, RK == RK_ReferenceBinding
7006 ? diag::warn_new_dangling_reference
7007 : diag::warn_new_dangling_initializer_list)
Richard Smith0e3102d2018-07-24 00:55:08 +00007008 << !Entity.getParent() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00007009 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00007010 // We can't determine if the allocation outlives the local declaration.
7011 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00007012 }
7013 break;
7014
7015 case LK_Return:
Richard Smith67af95b2018-07-23 19:19:08 +00007016 case LK_StmtExprResult:
Richard Smithafe48f92018-07-23 21:21:22 +00007017 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7018 // We can't determine if the local variable outlives the statement
7019 // expression.
7020 if (LK == LK_StmtExprResult)
7021 return false;
7022 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
7023 << Entity.getType()->isReferenceType() << DRE->getDecl()
7024 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
7025 } else if (isa<BlockExpr>(L)) {
7026 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
7027 } else if (isa<AddrLabelExpr>(L)) {
Reid Kleckner4c33d192018-08-17 22:11:31 +00007028 // Don't warn when returning a label from a statement expression.
7029 // Leaving the scope doesn't end its lifetime.
7030 if (LK == LK_StmtExprResult)
7031 return false;
Richard Smithafe48f92018-07-23 21:21:22 +00007032 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
7033 } else {
7034 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
7035 << Entity.getType()->isReferenceType() << DiagRange;
7036 }
7037 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00007038 }
7039
Richard Smithafe48f92018-07-23 21:21:22 +00007040 for (unsigned I = 0; I != Path.size(); ++I) {
7041 auto Elem = Path[I];
7042
Richard Smithca975b22018-07-23 18:50:26 +00007043 switch (Elem.Kind) {
Richard Smithafe48f92018-07-23 21:21:22 +00007044 case IndirectLocalPathEntry::AddressOf:
7045 case IndirectLocalPathEntry::LValToRVal:
Richard Smith6a32c052018-07-23 21:21:24 +00007046 // These exist primarily to mark the path as not permitting or
7047 // supporting lifetime extension.
Richard Smithca975b22018-07-23 18:50:26 +00007048 break;
7049
Richard Smithf4e248c2018-08-01 00:33:25 +00007050 case IndirectLocalPathEntry::LifetimeBoundCall:
7051 // FIXME: Consider adding a note for this.
7052 break;
7053
Richard Smithafe48f92018-07-23 21:21:22 +00007054 case IndirectLocalPathEntry::DefaultInit: {
7055 auto *FD = cast<FieldDecl>(Elem.D);
7056 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
Richard Smith6a32c052018-07-23 21:21:24 +00007057 << FD << nextPathEntryRange(Path, I + 1, L);
Richard Smithafe48f92018-07-23 21:21:22 +00007058 break;
7059 }
7060
7061 case IndirectLocalPathEntry::VarInit:
7062 const VarDecl *VD = cast<VarDecl>(Elem.D);
7063 Diag(VD->getLocation(), diag::note_local_var_initializer)
Richard Smithad5bbcc2018-08-01 01:03:33 +00007064 << VD->getType()->isReferenceType()
7065 << VD->isImplicit() << VD->getDeclName()
Richard Smith6a32c052018-07-23 21:21:24 +00007066 << nextPathEntryRange(Path, I + 1, L);
Richard Smithca975b22018-07-23 18:50:26 +00007067 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00007068 }
7069 }
Richard Smithd87aab92018-07-17 22:24:09 +00007070
7071 // We didn't lifetime-extend, so don't go any further; we don't need more
7072 // warnings or errors on inner temporaries within this one's initializer.
7073 return false;
7074 };
7075
Richard Smithca975b22018-07-23 18:50:26 +00007076 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
Richard Smithd87aab92018-07-17 22:24:09 +00007077 if (Init->isGLValue())
Richard Smithca975b22018-07-23 18:50:26 +00007078 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
7079 TemporaryVisitor);
Richard Smithd87aab92018-07-17 22:24:09 +00007080 else
Richard Smithca975b22018-07-23 18:50:26 +00007081 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007082}
7083
Richard Smithaaa0ec42013-09-21 21:19:19 +00007084static void DiagnoseNarrowingInInitList(Sema &S,
7085 const ImplicitConversionSequence &ICS,
7086 QualType PreNarrowingType,
7087 QualType EntityType,
7088 const Expr *PostInit);
7089
Richard Trieuac3eca52015-04-29 01:52:17 +00007090/// Provide warnings when std::move is used on construction.
7091static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7092 bool IsReturnStmt) {
7093 if (!InitExpr)
7094 return;
7095
Richard Smith51ec0cf2017-02-21 01:17:38 +00007096 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00007097 return;
7098
Richard Trieuac3eca52015-04-29 01:52:17 +00007099 QualType DestType = InitExpr->getType();
7100 if (!DestType->isRecordType())
7101 return;
7102
7103 unsigned DiagID = 0;
7104 if (IsReturnStmt) {
7105 const CXXConstructExpr *CCE =
7106 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7107 if (!CCE || CCE->getNumArgs() != 1)
7108 return;
7109
7110 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7111 return;
7112
7113 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00007114 }
7115
7116 // Find the std::move call and get the argument.
7117 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
Nico Weber192184c2018-06-20 15:57:38 +00007118 if (!CE || !CE->isCallToStdMove())
Richard Trieuac3eca52015-04-29 01:52:17 +00007119 return;
7120
7121 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7122
7123 if (IsReturnStmt) {
7124 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7125 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7126 return;
7127
7128 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7129 if (!VD || !VD->hasLocalStorage())
7130 return;
7131
Alex Lorenzbbe51d82017-11-07 21:40:11 +00007132 // __block variables are not moved implicitly.
7133 if (VD->hasAttr<BlocksAttr>())
7134 return;
7135
Richard Trieu8d4006a2015-07-28 19:06:16 +00007136 QualType SourceType = VD->getType();
7137 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00007138 return;
7139
Richard Trieu8d4006a2015-07-28 19:06:16 +00007140 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00007141 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00007142 }
7143
Davide Italiano7842c3f2015-07-18 01:15:19 +00007144 // If we're returning a function parameter, copy elision
7145 // is not possible.
7146 if (isa<ParmVarDecl>(VD))
7147 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00007148 else
7149 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007150 } else {
7151 DiagID = diag::warn_pessimizing_move_on_initialization;
7152 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7153 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
7154 return;
7155 }
7156
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007157 S.Diag(CE->getBeginLoc(), DiagID);
Richard Trieuac3eca52015-04-29 01:52:17 +00007158
7159 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7160 // is within a macro.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007161 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
Richard Trieuac3eca52015-04-29 01:52:17 +00007162 if (CallBegin.isMacroID())
7163 return;
7164 SourceLocation RParen = CE->getRParenLoc();
7165 if (RParen.isMacroID())
7166 return;
7167 SourceLocation LParen;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007168 SourceLocation ArgLoc = Arg->getBeginLoc();
Richard Trieuac3eca52015-04-29 01:52:17 +00007169
7170 // Special testing for the argument location. Since the fix-it needs the
7171 // location right before the argument, the argument location can be in a
7172 // macro only if it is at the beginning of the macro.
7173 while (ArgLoc.isMacroID() &&
7174 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
Richard Smithb5f81712018-04-30 05:25:48 +00007175 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
Richard Trieuac3eca52015-04-29 01:52:17 +00007176 }
7177
7178 if (LParen.isMacroID())
7179 return;
7180
7181 LParen = ArgLoc.getLocWithOffset(-1);
7182
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007183 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
Richard Trieuac3eca52015-04-29 01:52:17 +00007184 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7185 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7186}
7187
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007188static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7189 // Check to see if we are dereferencing a null pointer. If so, this is
7190 // undefined behavior, so warn about it. This only handles the pattern
7191 // "*null", which is a very syntactic check.
7192 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7193 if (UO->getOpcode() == UO_Deref &&
7194 UO->getSubExpr()->IgnoreParenCasts()->
7195 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7196 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7197 S.PDiag(diag::warn_binding_null_to_reference)
7198 << UO->getSubExpr()->getSourceRange());
7199 }
7200}
7201
Tim Shen4a05bb82016-06-21 20:29:17 +00007202MaterializeTemporaryExpr *
7203Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7204 bool BoundToLvalueReference) {
7205 auto MTE = new (Context)
7206 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7207
7208 // Order an ExprWithCleanups for lifetime marks.
7209 //
7210 // TODO: It'll be good to have a single place to check the access of the
7211 // destructor and generate ExprWithCleanups for various uses. Currently these
7212 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7213 // but there may be a chance to merge them.
7214 Cleanup.setExprNeedsCleanups(false);
7215 return MTE;
7216}
7217
Richard Smith4baaa5a2016-12-03 01:14:32 +00007218ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7219 // In C++98, we don't want to implicitly create an xvalue.
7220 // FIXME: This means that AST consumers need to deal with "prvalues" that
7221 // denote materialized temporaries. Maybe we should add another ValueKind
7222 // for "xvalue pretending to be a prvalue" for C++98 support.
7223 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
7224 return E;
7225
7226 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00007227 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7228 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00007229 QualType T = E->getType();
7230 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7231 return ExprError();
7232
7233 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7234}
7235
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007236ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007237InitializationSequence::Perform(Sema &S,
7238 const InitializedEntity &Entity,
7239 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00007240 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00007241 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007242 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007243 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00007244 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007245 }
Nico Weber337d5aa2015-04-17 08:32:38 +00007246 if (!ZeroInitializationFixit.empty()) {
7247 unsigned DiagID = diag::err_default_init_const;
7248 if (Decl *D = Entity.getDecl())
7249 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
7250 DiagID = diag::ext_default_init_const;
7251
7252 // The initialization would have succeeded with this fixit. Since the fixit
7253 // is on the error, we need to build a valid AST in this case, so this isn't
7254 // handled in the Failed() branch above.
7255 QualType DestType = Entity.getType();
7256 S.Diag(Kind.getLocation(), DiagID)
7257 << DestType << (bool)DestType->getAs<RecordType>()
7258 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7259 ZeroInitializationFixit);
7260 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007261
Sebastian Redld201edf2011-06-05 13:59:11 +00007262 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007263 // If the declaration is a non-dependent, incomplete array type
7264 // that has an initializer, then its type will be completed once
7265 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00007266 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00007267 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007268 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007269 if (const IncompleteArrayType *ArrayT
7270 = S.Context.getAsIncompleteArrayType(DeclType)) {
7271 // FIXME: We don't currently have the ability to accurately
7272 // compute the length of an initializer list without
7273 // performing full type-checking of the initializer list
7274 // (since we have to determine where braces are implicitly
7275 // introduced and such). So, we fall back to making the array
7276 // type a dependently-sized array type with no specified
7277 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007278 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007279 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00007280
Douglas Gregor51e77d52009-12-10 17:56:55 +00007281 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00007282 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007283 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7284 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007285 if (IncompleteArrayTypeLoc ArrayLoc =
7286 TL.getAs<IncompleteArrayTypeLoc>())
7287 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00007288 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007289 }
7290
7291 *ResultType
7292 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007293 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00007294 ArrayT->getSizeModifier(),
7295 ArrayT->getIndexTypeCVRQualifiers(),
7296 Brackets);
7297 }
7298
7299 }
7300 }
Sebastian Redla9351792012-02-11 23:51:47 +00007301 if (Kind.getKind() == InitializationKind::IK_Direct &&
7302 !Kind.isExplicitCast()) {
7303 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00007304 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00007305 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007306 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00007307 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00007308 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Fangrui Song6907ce22018-07-30 19:24:48 +00007309 Kind.isExplicitCast() ||
Douglas Gregorbf138952012-04-04 04:06:51 +00007310 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007311 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007312 }
7313
Sebastian Redld201edf2011-06-05 13:59:11 +00007314 // No steps means no initialization.
7315 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007316 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007317
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007318 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007319 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007320 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00007321 // Produce a C++98 compatibility warning if we are initializing a reference
7322 // from an initializer list. For parameters, we produce a better warning
7323 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007324 Expr *Init = Args[0];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007325 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7326 << Init->getSourceRange();
Richard Smith2b349ae2012-04-19 06:58:00 +00007327 }
7328
Egor Churaev3bccec52017-04-05 12:47:10 +00007329 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7330 QualType ETy = Entity.getType();
7331 Qualifiers TyQualifiers = ETy.getQualifiers();
7332 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
7333 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
7334
7335 if (S.getLangOpts().OpenCLVersion >= 200 &&
7336 ETy->isAtomicType() && !HasGlobalAS &&
7337 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007338 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7339 << 1
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007340 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
Egor Churaev3bccec52017-04-05 12:47:10 +00007341 return ExprError();
7342 }
7343
Douglas Gregor1b303932009-12-22 15:35:07 +00007344 QualType DestType = Entity.getType().getNonReferenceType();
7345 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00007346 // the same as Entity.getDecl()->getType() in cases involving type merging,
7347 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00007348 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00007349 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00007350 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007351
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007352 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00007353 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007354
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007355 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00007356 // grab the only argument out the Args and place it into the "current"
7357 // initializer.
7358 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007359 case SK_ResolveAddressOfOverloadedFunction:
7360 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007361 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007362 case SK_CastDerivedToBaseLValue:
7363 case SK_BindReference:
7364 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00007365 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007366 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00007367 case SK_UserConversion:
7368 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007369 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007370 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00007371 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00007372 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007373 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00007374 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00007375 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00007376 case SK_UnwrapInitList:
7377 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00007378 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00007379 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007380 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00007381 case SK_ArrayLoopIndex:
7382 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00007383 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00007384 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00007385 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00007386 case SK_PassByIndirectCopyRestore:
7387 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00007388 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007389 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00007390 case SK_OCLSamplerInit:
Andrew Savonichevb555b762018-10-23 15:19:20 +00007391 case SK_OCLZeroOpaqueType: {
Douglas Gregore1314a62009-12-18 05:02:21 +00007392 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007393 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00007394 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00007395 break;
John McCall34376a62010-12-04 03:47:34 +00007396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007397
Douglas Gregore1314a62009-12-18 05:02:21 +00007398 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00007399 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007400 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00007401 case SK_ZeroInitialization:
7402 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007404
Richard Smithd6a15082017-01-07 00:48:55 +00007405 // Promote from an unevaluated context to an unevaluated list context in
7406 // C++11 list-initialization; we need to instantiate entities usable in
7407 // constant expressions here in order to perform narrowing checks =(
7408 EnterExpressionEvaluationContext Evaluated(
7409 S, EnterExpressionEvaluationContext::InitList,
7410 CurInit.get() && isa<InitListExpr>(CurInit.get()));
7411
Richard Smith81f5ade2016-12-15 02:28:18 +00007412 // C++ [class.abstract]p2:
7413 // no objects of an abstract class can be created except as subobjects
7414 // of a class derived from it
7415 auto checkAbstractType = [&](QualType T) -> bool {
7416 if (Entity.getKind() == InitializedEntity::EK_Base ||
7417 Entity.getKind() == InitializedEntity::EK_Delegating)
7418 return false;
7419 return S.RequireNonAbstractType(Kind.getLocation(), T,
7420 diag::err_allocation_of_abstract_type);
7421 };
7422
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007423 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007424 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007425 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007426 for (step_iterator Step = step_begin(), StepEnd = step_end();
7427 Step != StepEnd; ++Step) {
7428 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007429 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007430
John Wiegley01296292011-04-08 18:41:53 +00007431 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007432
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007433 switch (Step->Kind) {
7434 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007435 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007436 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00007437 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00007438 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7439 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007440 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00007441 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00007442 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007443 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007444
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007445 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007446 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007447 case SK_CastDerivedToBaseLValue: {
7448 // We have a derived-to-base cast that produces either an rvalue or an
7449 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007450
John McCallcf142162010-08-07 06:22:56 +00007451 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00007452
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007453 // Casts to inaccessible base classes are allowed with C-style casts.
7454 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007455 if (S.CheckDerivedToBaseConversion(
7456 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
7457 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00007458 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007459
John McCall2536c6d2010-08-25 10:28:54 +00007460 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007461 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007462 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007463 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007464 VK_XValue :
7465 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007466 CurInit =
7467 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
7468 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007469 break;
7470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007471
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007472 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007473 // Reference binding does not have any corresponding ASTs.
7474
7475 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007476 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007477 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007478
George Burgess IVcfd48d92017-04-13 23:47:08 +00007479 // We don't check for e.g. function pointers here, since address
7480 // availability checks should only occur when the function first decays
7481 // into a pointer or reference.
7482 if (CurInit.get()->getType()->isFunctionProtoType()) {
7483 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7484 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7485 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007486 DRE->getBeginLoc()))
George Burgess IVcfd48d92017-04-13 23:47:08 +00007487 return ExprError();
7488 }
7489 }
7490 }
7491
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007492 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007493 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007494
Richard Smithe6c01442013-06-05 00:46:14 +00007495 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00007496 // Make sure the "temporary" is actually an rvalue.
7497 assert(CurInit.get()->isRValue() && "not a temporary");
7498
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007499 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007500 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007501 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007502
Douglas Gregorfe314812011-06-21 17:03:29 +00007503 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007504 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00007505 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
Richard Smithd87aab92018-07-17 22:24:09 +00007506 CurInit = MTE;
David Majnemerdaff3702014-05-01 17:50:17 +00007507
Brian Kelley762f9282017-03-29 18:16:38 +00007508 // If we're extending this temporary to automatic storage duration -- we
7509 // need to register its cleanup during the full-expression's cleanups.
7510 if (MTE->getStorageDuration() == SD_Automatic &&
7511 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00007512 S.Cleanup.setExprNeedsCleanups(true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007513 break;
Richard Smithe6c01442013-06-05 00:46:14 +00007514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
Richard Smithb8c0f552016-12-09 18:49:13 +00007516 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00007517 if (checkAbstractType(Step->Type))
7518 return ExprError();
7519
Richard Smithb8c0f552016-12-09 18:49:13 +00007520 // If the overall initialization is initializing a temporary, we already
7521 // bound our argument if it was necessary to do so. If not (if we're
7522 // ultimately initializing a non-temporary), our argument needs to be
7523 // bound since it's initializing a function parameter.
7524 // FIXME: This is a mess. Rationalize temporary destruction.
7525 if (!shouldBindAsTemporary(Entity))
7526 CurInit = S.MaybeBindToTemporary(CurInit.get());
7527 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7528 /*IsExtraneousCopy=*/false);
7529 break;
7530
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007531 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007532 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007533 /*IsExtraneousCopy=*/true);
7534 break;
7535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007536 case SK_UserConversion: {
7537 // We have a user-defined conversion that invokes either a constructor
7538 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00007539 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00007540 FunctionDecl *Fn = Step->Function.Function;
7541 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007542 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00007543 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00007544 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007545 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00007546 SmallVector<Expr*, 8> ConstructorArgs;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007547 SourceLocation Loc = CurInit.get()->getBeginLoc();
John McCall760af172010-02-01 03:16:54 +00007548
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007549 // Determine the arguments required to actually perform the constructor
7550 // call.
John Wiegley01296292011-04-08 18:41:53 +00007551 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007552 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00007553 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007554 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00007555 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556
Richard Smithb24f0672012-02-11 19:22:50 +00007557 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00007558 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
7559 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007560 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007561 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00007562 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007563 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00007564 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00007565 CXXConstructExpr::CK_Complete,
7566 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007567 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007568 return ExprError();
John McCall760af172010-02-01 03:16:54 +00007569
Richard Smith5179eb72016-06-28 19:03:57 +00007570 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7571 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00007572 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7573 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007574
John McCalle3027922010-08-25 11:45:40 +00007575 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00007576 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007577 } else {
7578 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00007579 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00007580 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00007581 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00007582 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7583 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007584
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007585 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7586 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00007587 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007588 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007589
John McCalle3027922010-08-25 11:45:40 +00007590 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00007591 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007593
Richard Smith81f5ade2016-12-15 02:28:18 +00007594 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7595 return ExprError();
7596
Richard Smithb8c0f552016-12-09 18:49:13 +00007597 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
7598 CastKind, CurInit.get(), nullptr,
7599 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00007600
Richard Smithb8c0f552016-12-09 18:49:13 +00007601 if (shouldBindAsTemporary(Entity))
7602 // The overall entity is temporary, so this expression should be
7603 // destroyed at the end of its full-expression.
7604 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7605 else if (CreatedObject && shouldDestroyEntity(Entity)) {
7606 // The object outlasts the full-expression, but we need to prepare for
7607 // a destructor being run on it.
7608 // FIXME: It makes no sense to do this here. This should happen
7609 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00007610 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00007611 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007612 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00007613 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007614 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00007615 S.PDiag(diag::err_access_dtor_temp) << T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007616 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
7617 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
Richard Smith22262ab2013-05-04 06:44:46 +00007618 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00007619 }
7620 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007621 break;
7622 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007623
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007624 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007625 case SK_QualificationConversionXValue:
7626 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007627 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00007628 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007629 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007630 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007631 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007632 VK_XValue :
7633 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007634 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007635 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007636 }
7637
Richard Smith77be48a2014-07-31 06:31:19 +00007638 case SK_AtomicConversion: {
7639 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7640 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7641 CK_NonAtomicToAtomic, VK_RValue);
7642 break;
7643 }
7644
Jordan Roseb1312a52013-04-11 00:58:58 +00007645 case SK_LValueToRValue: {
7646 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Richard Smithd2e69df2018-10-30 02:02:49 +00007647 // C++ [conv.lval]p3:
7648 // If T is cv std::nullptr_t, the result is a null pointer constant.
7649 CastKind CK =
7650 Step->Type->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
7651 CurInit =
7652 ImplicitCastExpr::Create(S.Context, Step->Type, CK, CurInit.get(),
7653 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00007654 break;
7655 }
7656
Richard Smithaaa0ec42013-09-21 21:19:19 +00007657 case SK_ConversionSequence:
7658 case SK_ConversionSequenceNoNarrowing: {
7659 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007660 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7661 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007662 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007663 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007664 ExprResult CurInitExprRes =
7665 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007666 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007667 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007668 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007669
7670 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7671
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007672 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007673
7674 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007675 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007676 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7677 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007678
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007679 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007680 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007681
Douglas Gregor51e77d52009-12-10 17:56:55 +00007682 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007683 if (checkAbstractType(Step->Type))
7684 return ExprError();
7685
John Wiegley01296292011-04-08 18:41:53 +00007686 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007687 // If we're not initializing the top-level entity, we need to create an
7688 // InitializeTemporary entity for our target type.
7689 QualType Ty = Step->Type;
7690 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007691 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007692 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7693 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007694 InitList, Ty, /*VerifyOnly=*/false,
7695 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007696 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007697 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007698
Richard Smithcc1b96d2013-06-12 22:31:48 +00007699 // Hack: We must update *ResultType if available in order to set the
7700 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7701 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7702 if (ResultType &&
7703 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007704 if ((*ResultType)->isRValueReferenceType())
7705 Ty = S.Context.getRValueReferenceType(Ty);
7706 else if ((*ResultType)->isLValueReferenceType())
7707 Ty = S.Context.getLValueReferenceType(Ty,
7708 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7709 *ResultType = Ty;
7710 }
7711
7712 InitListExpr *StructuredInitList =
7713 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007714 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007715 CurInit = shouldBindAsTemporary(InitEntity)
7716 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007717 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007718 break;
7719 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007720
Richard Smith53324112014-07-16 21:33:43 +00007721 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007722 if (checkAbstractType(Step->Type))
7723 return ExprError();
7724
Sebastian Redl5a41f682012-02-12 16:37:24 +00007725 // When an initializer list is passed for a parameter of type "reference
7726 // to object", we don't get an EK_Temporary entity, but instead an
7727 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007728 // FIXME: This is a hack. What we really should do is create a user
7729 // conversion step for this case, but this makes it considerably more
7730 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007731 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7732 Entity.getType().getNonReferenceType());
7733 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007734 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007735 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007736 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7737 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007738 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007739 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7740 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007741 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007742 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007743 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007744 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007745 InitList->getLBraceLoc(),
7746 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007747 break;
7748 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007749
Sebastian Redl29526f02011-11-27 16:50:07 +00007750 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007751 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007752 break;
7753
7754 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007755 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007756 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7757 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007758 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007759 ILE->setSyntacticForm(Syntactic);
7760 ILE->setType(E->getType());
7761 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007762 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007763 break;
7764 }
7765
Richard Smith53324112014-07-16 21:33:43 +00007766 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007767 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007768 if (checkAbstractType(Step->Type))
7769 return ExprError();
7770
Sebastian Redl99f66162012-02-19 12:27:56 +00007771 // When an initializer list is passed for a parameter of type "reference
7772 // to object", we don't get an EK_Temporary entity, but instead an
7773 // EK_Parameter entity with reference type.
7774 // FIXME: This is a hack. What we really should do is create a user
7775 // conversion step for this case, but this makes it considerably more
7776 // complicated. For now, this will do.
7777 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7778 Entity.getType().getNonReferenceType());
7779 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00007780 bool IsStdInitListInit =
7781 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00007782 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00007783 SourceRange Range = Kind.hasParenOrBraceRange()
7784 ? Kind.getParenOrBraceRange()
7785 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00007786 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00007787 S, UseTemporary ? TempEntity : Entity, Kind,
7788 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00007789 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00007790 /*IsListInitialization*/ IsStdInitListInit,
7791 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00007792 /*LBraceLoc*/ Range.getBegin(),
7793 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007794 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00007795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007796
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007797 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007798 step_iterator NextStep = Step;
7799 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007800 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007801 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007802 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007803 // The need for zero-initialization is recorded directly into
7804 // the call to the object's constructor within the next step.
7805 ConstructorInitRequiresZeroInit = true;
7806 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007807 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007808 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007809 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7810 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007811 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007812 Kind.getRange().getBegin());
7813
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007814 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007815 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007816 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007817 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007818 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007819 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007820 break;
7821 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007822
7823 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007824 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007825 // Save off the initial CurInit in case we need to emit a diagnostic
7826 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007827 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007828 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007829 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7830 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007831 if (Result.isInvalid())
7832 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007833 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007834
7835 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007836 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007837 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007838 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007839 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007840 == Sema::Compatible)
7841 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007842 if (CurInitExprRes.isInvalid())
7843 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007844 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007845
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007846 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007847 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7848 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007849 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007850 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007851 &Complained)) {
7852 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007853 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007854 } else if (Complained)
7855 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007856 break;
7857 }
Eli Friedman78275202009-12-19 08:11:05 +00007858
7859 case SK_StringInit: {
7860 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007861 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007862 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007863 break;
7864 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007865
7866 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007867 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007868 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007869 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007870 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007871
Richard Smith410306b2016-12-12 02:53:20 +00007872 case SK_ArrayLoopIndex: {
7873 Expr *Cur = CurInit.get();
7874 Expr *BaseExpr = new (S.Context)
7875 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7876 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7877 Expr *IndexExpr =
7878 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7879 CurInit = S.CreateBuiltinArraySubscriptExpr(
7880 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7881 ArrayLoopCommonExprs.push_back(BaseExpr);
7882 break;
7883 }
7884
7885 case SK_ArrayLoopInit: {
7886 assert(!ArrayLoopCommonExprs.empty() &&
7887 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7888 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7889 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7890 CurInit.get());
7891 break;
7892 }
7893
Richard Smith378b8c82016-12-14 03:22:16 +00007894 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007895 // Okay: we checked everything before creating this step. Note that
7896 // this is a GNU extension.
7897 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007898 << Step->Type << CurInit.get()->getType()
7899 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007900 LLVM_FALLTHROUGH;
7901 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007902 // If the destination type is an incomplete array type, update the
7903 // type accordingly.
7904 if (ResultType) {
7905 if (const IncompleteArrayType *IncompleteDest
7906 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7907 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007908 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007909 *ResultType = S.Context.getConstantArrayType(
7910 IncompleteDest->getElementType(),
7911 ConstantSource->getSize(),
7912 ArrayType::Normal, 0);
7913 }
7914 }
7915 }
John McCall31168b02011-06-15 23:02:42 +00007916 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007917
Richard Smithebeed412012-02-15 22:38:09 +00007918 case SK_ParenthesizedArrayInit:
7919 // Okay: we checked everything before creating this step. Note that
7920 // this is a GNU extension.
7921 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7922 << CurInit.get()->getSourceRange();
7923 break;
7924
John McCall31168b02011-06-15 23:02:42 +00007925 case SK_PassByIndirectCopyRestore:
7926 case SK_PassByIndirectRestore:
7927 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007928 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7929 CurInit.get(), Step->Type,
7930 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007931 break;
7932
7933 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007934 CurInit =
7935 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7936 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007937 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007938
7939 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007940 S.Diag(CurInit.get()->getExprLoc(),
7941 diag::warn_cxx98_compat_initializer_list_init)
7942 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007943
Richard Smithcc1b96d2013-06-12 22:31:48 +00007944 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007945 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7946 CurInit.get()->getType(), CurInit.get(),
7947 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007948
Florian Hahn0aa117d2018-07-17 09:23:31 +00007949 // Wrap it in a construction of a std::initializer_list<T>.
7950 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smith0a9969b2018-07-17 00:11:41 +00007951
Richard Smithcc1b96d2013-06-12 22:31:48 +00007952 // Bind the result, in case the library has given initializer_list a
7953 // non-trivial destructor.
7954 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007955 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007956 break;
7957 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007958
Guy Benyei61054192013-02-07 10:55:47 +00007959 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007960 // Sampler initialzation have 5 cases:
7961 // 1. function argument passing
7962 // 1a. argument is a file-scope variable
7963 // 1b. argument is a function-scope variable
7964 // 1c. argument is one of caller function's parameters
7965 // 2. variable initialization
7966 // 2a. initializing a file-scope variable
7967 // 2b. initializing a function-scope variable
7968 //
7969 // For file-scope variables, since they cannot be initialized by function
7970 // call of __translate_sampler_initializer in LLVM IR, their references
7971 // need to be replaced by a cast from their literal initializers to
7972 // sampler type. Since sampler variables can only be used in function
7973 // calls as arguments, we only need to replace them when handling the
7974 // argument passing.
7975 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007976 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007977 Expr *Init = CurInit.get();
7978 QualType SourceType = Init->getType();
7979 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007980 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00007981 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00007982 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7983 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007984 break;
7985 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7986 auto Var = cast<VarDecl>(DRE->getDecl());
7987 // Case 1b and 1c
7988 // No cast from integer to sampler is needed.
7989 if (!Var->hasGlobalStorage()) {
7990 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7991 CK_LValueToRValue, Init,
7992 /*BasePath=*/nullptr, VK_RValue);
7993 break;
7994 }
7995 // Case 1a
7996 // For function call with a file-scope sampler variable as argument,
7997 // get the integer literal.
7998 // Do not diagnose if the file-scope variable does not have initializer
7999 // since this has already been diagnosed when parsing the variable
8000 // declaration.
8001 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8002 break;
8003 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8004 Var->getInit()))->getSubExpr();
8005 SourceType = Init->getType();
8006 }
8007 } else {
8008 // Case 2
8009 // Check initializer is 32 bit integer constant.
8010 // If the initializer is taken from global variable, do not diagnose since
8011 // this has already been done when parsing the variable declaration.
8012 if (!Init->isConstantInitializer(S.Context, false))
8013 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00008014
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008015 if (!SourceType->isIntegerType() ||
8016 32 != S.Context.getIntWidth(SourceType)) {
8017 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8018 << SourceType;
8019 break;
8020 }
8021
8022 llvm::APSInt Result;
8023 Init->EvaluateAsInt(Result, S.Context);
8024 const uint64_t SamplerValue = Result.getLimitedValue();
8025 // 32-bit value of sampler's initializer is interpreted as
8026 // bit-field with the following structure:
8027 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8028 // |31 6|5 4|3 1| 0|
8029 // This structure corresponds to enum values of sampler properties
8030 // defined in SPIR spec v1.2 and also opencl-c.h
8031 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8032 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8033 if (FilterMode != 1 && FilterMode != 2)
8034 S.Diag(Kind.getLocation(),
8035 diag::warn_sampler_initializer_invalid_bits)
8036 << "Filter Mode";
8037 if (AddressingMode > 4)
8038 S.Diag(Kind.getLocation(),
8039 diag::warn_sampler_initializer_invalid_bits)
8040 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00008041 }
8042
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008043 // Cases 1a, 2a and 2b
8044 // Insert cast from integer to sampler.
8045 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
8046 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00008047 break;
8048 }
Andrew Savonichevb555b762018-10-23 15:19:20 +00008049 case SK_OCLZeroOpaqueType: {
8050 assert((Step->Type->isEventT() || Step->Type->isQueueT()) &&
8051 "Wrong type for initialization of OpenCL opaque type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008052
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008053 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Andrew Savonichevb555b762018-10-23 15:19:20 +00008054 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00008055 CurInit.get()->getValueKind());
8056 break;
8057 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008058 }
8059 }
John McCall1f425642010-11-11 03:21:53 +00008060
Richard Smithca975b22018-07-23 18:50:26 +00008061 // Check whether the initializer has a shorter lifetime than the initialized
8062 // entity, and if not, either lifetime-extend or warn as appropriate.
8063 if (auto *Init = CurInit.get())
8064 S.checkInitializerLifetime(Entity, Init);
8065
John McCall1f425642010-11-11 03:21:53 +00008066 // Diagnose non-fatal problems with the completed initialization.
8067 if (Entity.getKind() == InitializedEntity::EK_Member &&
8068 cast<FieldDecl>(Entity.getDecl())->isBitField())
8069 S.CheckBitFieldInitialization(Kind.getLocation(),
8070 cast<FieldDecl>(Entity.getDecl()),
8071 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008072
Richard Trieuac3eca52015-04-29 01:52:17 +00008073 // Check for std::move on construction.
8074 if (const Expr *E = CurInit.get()) {
8075 CheckMoveOnConstruction(S, E,
8076 Entity.getKind() == InitializedEntity::EK_Result);
8077 }
8078
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008079 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008080}
8081
Richard Smith593f9932012-12-08 02:01:17 +00008082/// Somewhere within T there is an uninitialized reference subobject.
8083/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00008084static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8085 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00008086 if (T->isReferenceType()) {
8087 S.Diag(Loc, diag::err_reference_without_init)
8088 << T.getNonReferenceType();
8089 return true;
8090 }
8091
8092 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8093 if (!RD || !RD->hasUninitializedReferenceMember())
8094 return false;
8095
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008096 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00008097 if (FI->isUnnamedBitfield())
8098 continue;
8099
8100 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8101 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8102 return true;
8103 }
8104 }
8105
Aaron Ballman574705e2014-03-13 15:41:46 +00008106 for (const auto &BI : RD->bases()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008107 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00008108 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8109 return true;
8110 }
8111 }
8112
8113 return false;
8114}
8115
8116
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008117//===----------------------------------------------------------------------===//
8118// Diagnose initialization failures
8119//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00008120
8121/// Emit notes associated with an initialization that failed due to a
8122/// "simple" conversion failure.
8123static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8124 Expr *op) {
8125 QualType destType = entity.getType();
8126 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8127 op->getType()->isObjCObjectPointerType()) {
8128
8129 // Emit a possible note about the conversion failing because the
8130 // operand is a message send with a related result type.
8131 S.EmitRelatedResultTypeNote(op);
8132
8133 // Emit a possible note about a return failing because we're
8134 // expecting a related result type.
8135 if (entity.getKind() == InitializedEntity::EK_Result)
8136 S.EmitRelatedResultTypeNoteForReturn(destType);
8137 }
8138}
8139
Richard Smith0449aaf2013-11-21 23:30:57 +00008140static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8141 InitListExpr *InitList) {
8142 QualType DestType = Entity.getType();
8143
8144 QualType E;
8145 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8146 QualType ArrayType = S.Context.getConstantArrayType(
8147 E.withConst(),
8148 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8149 InitList->getNumInits()),
8150 clang::ArrayType::Normal, 0);
8151 InitializedEntity HiddenArray =
8152 InitializedEntity::InitializeTemporary(ArrayType);
8153 return diagnoseListInit(S, HiddenArray, InitList);
8154 }
8155
Richard Smith8d082d12014-09-04 22:13:39 +00008156 if (DestType->isReferenceType()) {
8157 // A list-initialization failure for a reference means that we tried to
8158 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8159 // inner initialization failed.
8160 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
8161 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008162 SourceLocation Loc = InitList->getBeginLoc();
Richard Smith8d082d12014-09-04 22:13:39 +00008163 if (auto *D = Entity.getDecl())
8164 Loc = D->getLocation();
8165 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8166 return;
8167 }
8168
Richard Smith0449aaf2013-11-21 23:30:57 +00008169 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00008170 /*VerifyOnly=*/false,
8171 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00008172 assert(DiagnoseInitList.HadError() &&
8173 "Inconsistent init list check result.");
8174}
8175
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008176bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008177 const InitializedEntity &Entity,
8178 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008179 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00008180 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008181 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008182
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008183 // When we want to diagnose only one element of a braced-init-list,
8184 // we need to factor it out.
8185 Expr *OnlyArg;
8186 if (Args.size() == 1) {
8187 auto *List = dyn_cast<InitListExpr>(Args[0]);
8188 if (List && List->getNumInits() == 1)
8189 OnlyArg = List->getInit(0);
8190 else
8191 OnlyArg = Args[0];
8192 }
8193 else
8194 OnlyArg = nullptr;
8195
Douglas Gregor1b303932009-12-22 15:35:07 +00008196 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008197 switch (Failure) {
8198 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008199 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008200 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00008201 // Dig out the reference subobject which is uninitialized and diagnose it.
8202 // If this is value-initialization, this could be nested some way within
8203 // the target type.
8204 assert(Kind.getKind() == InitializationKind::IK_Value ||
8205 DestType->isReferenceType());
8206 bool Diagnosed =
8207 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8208 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8209 (void)Diagnosed;
8210 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008211 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008212 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008213 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00008214 case FK_ParenthesizedListInitForReference:
8215 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8216 << 1 << Entity.getType() << Args[0]->getSourceRange();
8217 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008218
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008219 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008220 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008221 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008222 case FK_ArrayNeedsInitListOrStringLiteral:
8223 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8224 break;
8225 case FK_ArrayNeedsInitListOrWideStringLiteral:
8226 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8227 break;
8228 case FK_NarrowStringIntoWideCharArray:
8229 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8230 break;
8231 case FK_WideStringIntoCharArray:
8232 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8233 break;
8234 case FK_IncompatWideStringIntoWideChar:
8235 S.Diag(Kind.getLocation(),
8236 diag::err_array_init_incompat_wide_string_into_wchar);
8237 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00008238 case FK_PlainStringIntoUTF8Char:
8239 S.Diag(Kind.getLocation(),
8240 diag::err_array_init_plain_string_into_char8_t);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008241 S.Diag(Args.front()->getBeginLoc(),
Richard Smith3a8244d2018-05-01 05:02:45 +00008242 diag::note_array_init_plain_string_into_char8_t)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008243 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
Richard Smith3a8244d2018-05-01 05:02:45 +00008244 break;
8245 case FK_UTF8StringIntoPlainChar:
8246 S.Diag(Kind.getLocation(),
8247 diag::err_array_init_utf8_string_into_char);
8248 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008249 case FK_ArrayTypeMismatch:
8250 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00008251 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00008252 (Failure == FK_ArrayTypeMismatch
8253 ? diag::err_array_init_different_type
8254 : diag::err_array_init_non_constant_array))
8255 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008256 << OnlyArg->getType()
Douglas Gregore2f943b2011-02-22 18:29:51 +00008257 << Args[0]->getSourceRange();
8258 break;
8259
John McCalla59dc2f2012-01-05 00:13:19 +00008260 case FK_VariableLengthArrayHasInitializer:
8261 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8262 << Args[0]->getSourceRange();
8263 break;
8264
John McCall16df1e52010-03-30 21:47:33 +00008265 case FK_AddressOfOverloadFailed: {
8266 DeclAccessPair Found;
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008267 S.ResolveAddressOfOverloadedFunction(OnlyArg,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008268 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00008269 true,
8270 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008271 break;
John McCall16df1e52010-03-30 21:47:33 +00008272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008273
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008274 case FK_AddressOfUnaddressableFunction: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008275 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008276 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008277 OnlyArg->getBeginLoc());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008278 break;
8279 }
8280
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008281 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00008282 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008283 switch (FailedOverloadResult) {
8284 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00008285 if (Failure == FK_UserConversionOverloadFailed)
8286 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008287 << OnlyArg->getType() << DestType
Douglas Gregore1314a62009-12-18 05:02:21 +00008288 << Args[0]->getSourceRange();
8289 else
8290 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008291 << DestType << OnlyArg->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00008292 << Args[0]->getSourceRange();
8293
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008294 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008295 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008296
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008297 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00008298 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008299 DestType.getNonReferenceType(),
8300 diag::err_typecheck_nonviable_condition_incomplete,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008301 OnlyArg->getType(), Args[0]->getSourceRange()))
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008302 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00008303 << (Entity.getKind() == InitializedEntity::EK_Result)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008304 << OnlyArg->getType() << Args[0]->getSourceRange()
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008305 << DestType.getNonReferenceType();
8306
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008307 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008308 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008309
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008310 case OR_Deleted: {
8311 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008312 << OnlyArg->getType() << DestType.getNonReferenceType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008313 << Args[0]->getSourceRange();
8314 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008315 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00008316 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008317 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00008318 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008319 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008320 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008321 }
8322 break;
8323 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008324
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008325 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008326 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008327 }
8328 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008329
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008330 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00008331 if (isa<InitListExpr>(Args[0])) {
8332 S.Diag(Kind.getLocation(),
8333 diag::err_lvalue_reference_bind_to_initlist)
8334 << DestType.getNonReferenceType().isVolatileQualified()
8335 << DestType.getNonReferenceType()
8336 << Args[0]->getSourceRange();
8337 break;
8338 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008339 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00008340
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008341 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008342 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008343 Failure == FK_NonConstLValueReferenceBindingToTemporary
8344 ? diag::err_lvalue_reference_bind_to_temporary
8345 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00008346 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008347 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008348 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008349 << Args[0]->getSourceRange();
8350 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008351
Richard Smithb8c0f552016-12-09 18:49:13 +00008352 case FK_NonConstLValueReferenceBindingToBitfield: {
8353 // We don't necessarily have an unambiguous source bit-field.
8354 FieldDecl *BitField = Args[0]->getSourceBitField();
8355 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
8356 << DestType.isVolatileQualified()
8357 << (BitField ? BitField->getDeclName() : DeclarationName())
8358 << (BitField != nullptr)
8359 << Args[0]->getSourceRange();
8360 if (BitField)
8361 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8362 break;
8363 }
8364
8365 case FK_NonConstLValueReferenceBindingToVectorElement:
8366 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
8367 << DestType.isVolatileQualified()
8368 << Args[0]->getSourceRange();
8369 break;
8370
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008371 case FK_RValueReferenceBindingToLValue:
8372 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008373 << DestType.getNonReferenceType() << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008374 << Args[0]->getSourceRange();
8375 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008376
Richard Trieuf956a492015-05-16 01:27:03 +00008377 case FK_ReferenceInitDropsQualifiers: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008378 QualType SourceType = OnlyArg->getType();
Richard Trieuf956a492015-05-16 01:27:03 +00008379 QualType NonRefType = DestType.getNonReferenceType();
8380 Qualifiers DroppedQualifiers =
8381 SourceType.getQualifiers() - NonRefType.getQualifiers();
8382
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008383 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00008384 << SourceType
8385 << NonRefType
8386 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008387 << Args[0]->getSourceRange();
8388 break;
Richard Trieuf956a492015-05-16 01:27:03 +00008389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008390
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008391 case FK_ReferenceInitFailed:
8392 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
8393 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008394 << OnlyArg->isLValue()
8395 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008396 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00008397 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008398 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008399
Douglas Gregorb491ed32011-02-19 21:32:49 +00008400 case FK_ConversionFailed: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008401 QualType FromType = OnlyArg->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00008402 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00008403 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008404 << DestType
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008405 << OnlyArg->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00008406 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008407 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008408 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
8409 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00008410 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00008411 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008412 }
John Wiegley01296292011-04-08 18:41:53 +00008413
8414 case FK_ConversionFromPropertyFailed:
8415 // No-op. This error has already been reported.
8416 break;
8417
Douglas Gregor51e77d52009-12-10 17:56:55 +00008418 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00008419 SourceRange R;
8420
David Majnemerbd385442015-04-10 04:52:06 +00008421 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008422 if (InitList && InitList->getNumInits() >= 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008423 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008424 } else {
8425 assert(Args.size() > 1 && "Expected multiple initializers!");
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008426 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008427 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00008428
Alp Tokerb6cc5922014-05-03 03:45:55 +00008429 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00008430 if (Kind.isCStyleOrFunctionalCast())
8431 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
8432 << R;
8433 else
8434 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
8435 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00008436 break;
8437 }
8438
Richard Smith49a6b6e2017-03-24 01:14:25 +00008439 case FK_ParenthesizedListInitForScalar:
8440 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8441 << 0 << Entity.getType() << Args[0]->getSourceRange();
8442 break;
8443
Douglas Gregor51e77d52009-12-10 17:56:55 +00008444 case FK_ReferenceBindingToInitList:
8445 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
8446 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8447 break;
8448
8449 case FK_InitListBadDestinationType:
8450 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8451 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8452 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008453
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008454 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008455 case FK_ConstructorOverloadFailed: {
8456 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008457 if (Args.size())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008458 ArgsRange =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008459 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008460
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008461 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00008462 assert(Args.size() == 1 &&
8463 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008464 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008465 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008466 }
8467
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008468 // FIXME: Using "DestType" for the entity we're printing is probably
8469 // bad.
8470 switch (FailedOverloadResult) {
8471 case OR_Ambiguous:
8472 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
8473 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008474 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008475 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008476
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008477 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008478 if (Kind.getKind() == InitializationKind::IK_Default &&
8479 (Entity.getKind() == InitializedEntity::EK_Base ||
8480 Entity.getKind() == InitializedEntity::EK_Member) &&
8481 isa<CXXConstructorDecl>(S.CurContext)) {
8482 // This is implicit default initialization of a member or
8483 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00008484 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008485 // initialize this base/member.
8486 CXXConstructorDecl *Constructor
8487 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00008488 const CXXRecordDecl *InheritedFrom = nullptr;
8489 if (auto Inherited = Constructor->getInheritedConstructor())
8490 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008491 if (Entity.getKind() == InitializedEntity::EK_Base) {
8492 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008493 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008494 << S.Context.getTypeDeclType(Constructor->getParent())
8495 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00008496 << Entity.getType()
8497 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008498
8499 RecordDecl *BaseDecl
8500 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
8501 ->getDecl();
8502 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8503 << S.Context.getTagDeclType(BaseDecl);
8504 } else {
8505 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008506 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008507 << S.Context.getTypeDeclType(Constructor->getParent())
8508 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00008509 << Entity.getName()
8510 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00008511 S.Diag(Entity.getDecl()->getLocation(),
8512 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008513
8514 if (const RecordType *Record
8515 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008516 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008517 diag::note_previous_decl)
8518 << S.Context.getTagDeclType(Record->getDecl());
8519 }
8520 break;
8521 }
8522
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008523 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
8524 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008525 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008526 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008527
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008528 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008529 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008530 OverloadingResult Ovl
8531 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00008532 if (Ovl != OR_Deleted) {
8533 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8534 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008535 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00008536 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008537 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008538
Douglas Gregor74f7d502012-02-15 19:33:52 +00008539 // If this is a defaulted or implicitly-declared function, then
8540 // it was implicitly deleted. Make it clear that the deletion was
8541 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00008542 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008543 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00008544 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008545 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00008546 else
8547 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8548 << true << DestType << ArgsRange;
8549
8550 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008551 break;
8552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008553
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008554 case OR_Success:
8555 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008556 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008557 }
David Blaikie60deeee2012-01-17 08:24:58 +00008558 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008559
Douglas Gregor85dabae2009-12-16 01:38:02 +00008560 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008561 if (Entity.getKind() == InitializedEntity::EK_Member &&
8562 isa<CXXConstructorDecl>(S.CurContext)) {
8563 // This is implicit default-initialization of a const member in
8564 // a constructor. Complain that it needs to be explicitly
8565 // initialized.
8566 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
8567 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00008568 << (Constructor->getInheritedConstructor() ? 2 :
8569 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008570 << S.Context.getTypeDeclType(Constructor->getParent())
8571 << /*const=*/1
8572 << Entity.getName();
8573 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
8574 << Entity.getName();
8575 } else {
8576 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00008577 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008578 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00008579 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008580
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008581 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00008582 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008583 diag::err_init_incomplete_type);
8584 break;
8585
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008586 case FK_ListInitializationFailed: {
8587 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00008588 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8589 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008590 break;
8591 }
John McCall4124c492011-10-17 18:40:02 +00008592
8593 case FK_PlaceholderType: {
8594 // FIXME: Already diagnosed!
8595 break;
8596 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00008597
Sebastian Redl048a6d72012-04-01 19:54:59 +00008598 case FK_ExplicitConstructor: {
8599 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
8600 << Args[0]->getSourceRange();
8601 OverloadCandidateSet::iterator Best;
8602 OverloadingResult Ovl
8603 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00008604 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008605 assert(Ovl == OR_Success && "Inconsistent overload resolution");
8606 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00008607 S.Diag(CtorDecl->getLocation(),
8608 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008609 break;
8610 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008612
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008613 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008614 return true;
8615}
Douglas Gregore1314a62009-12-18 05:02:21 +00008616
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008617void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008618 switch (SequenceKind) {
8619 case FailedSequence: {
8620 OS << "Failed sequence: ";
8621 switch (Failure) {
8622 case FK_TooManyInitsForReference:
8623 OS << "too many initializers for reference";
8624 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008625
Richard Smith49a6b6e2017-03-24 01:14:25 +00008626 case FK_ParenthesizedListInitForReference:
8627 OS << "parenthesized list init for reference";
8628 break;
8629
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008630 case FK_ArrayNeedsInitList:
8631 OS << "array requires initializer list";
8632 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008633
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008634 case FK_AddressOfUnaddressableFunction:
8635 OS << "address of unaddressable function was taken";
8636 break;
8637
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008638 case FK_ArrayNeedsInitListOrStringLiteral:
8639 OS << "array requires initializer list or string literal";
8640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008641
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008642 case FK_ArrayNeedsInitListOrWideStringLiteral:
8643 OS << "array requires initializer list or wide string literal";
8644 break;
8645
8646 case FK_NarrowStringIntoWideCharArray:
8647 OS << "narrow string into wide char array";
8648 break;
8649
8650 case FK_WideStringIntoCharArray:
8651 OS << "wide string into char array";
8652 break;
8653
8654 case FK_IncompatWideStringIntoWideChar:
8655 OS << "incompatible wide string into wide char array";
8656 break;
8657
Richard Smith3a8244d2018-05-01 05:02:45 +00008658 case FK_PlainStringIntoUTF8Char:
8659 OS << "plain string literal into char8_t array";
8660 break;
8661
8662 case FK_UTF8StringIntoPlainChar:
8663 OS << "u8 string literal into char array";
8664 break;
8665
Douglas Gregore2f943b2011-02-22 18:29:51 +00008666 case FK_ArrayTypeMismatch:
8667 OS << "array type mismatch";
8668 break;
8669
8670 case FK_NonConstantArrayInit:
8671 OS << "non-constant array initializer";
8672 break;
8673
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008674 case FK_AddressOfOverloadFailed:
8675 OS << "address of overloaded function failed";
8676 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008677
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008678 case FK_ReferenceInitOverloadFailed:
8679 OS << "overload resolution for reference initialization failed";
8680 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008681
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008682 case FK_NonConstLValueReferenceBindingToTemporary:
8683 OS << "non-const lvalue reference bound to temporary";
8684 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008685
Richard Smithb8c0f552016-12-09 18:49:13 +00008686 case FK_NonConstLValueReferenceBindingToBitfield:
8687 OS << "non-const lvalue reference bound to bit-field";
8688 break;
8689
8690 case FK_NonConstLValueReferenceBindingToVectorElement:
8691 OS << "non-const lvalue reference bound to vector element";
8692 break;
8693
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008694 case FK_NonConstLValueReferenceBindingToUnrelated:
8695 OS << "non-const lvalue reference bound to unrelated type";
8696 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008697
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008698 case FK_RValueReferenceBindingToLValue:
8699 OS << "rvalue reference bound to an lvalue";
8700 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008701
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008702 case FK_ReferenceInitDropsQualifiers:
8703 OS << "reference initialization drops qualifiers";
8704 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008705
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008706 case FK_ReferenceInitFailed:
8707 OS << "reference initialization failed";
8708 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008709
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008710 case FK_ConversionFailed:
8711 OS << "conversion failed";
8712 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008713
John Wiegley01296292011-04-08 18:41:53 +00008714 case FK_ConversionFromPropertyFailed:
8715 OS << "conversion from property failed";
8716 break;
8717
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008718 case FK_TooManyInitsForScalar:
8719 OS << "too many initializers for scalar";
8720 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008721
Richard Smith49a6b6e2017-03-24 01:14:25 +00008722 case FK_ParenthesizedListInitForScalar:
8723 OS << "parenthesized list init for reference";
8724 break;
8725
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008726 case FK_ReferenceBindingToInitList:
8727 OS << "referencing binding to initializer list";
8728 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008729
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008730 case FK_InitListBadDestinationType:
8731 OS << "initializer list for non-aggregate, non-scalar type";
8732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008733
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008734 case FK_UserConversionOverloadFailed:
8735 OS << "overloading failed for user-defined conversion";
8736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008737
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008738 case FK_ConstructorOverloadFailed:
8739 OS << "constructor overloading failed";
8740 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008741
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008742 case FK_DefaultInitOfConst:
8743 OS << "default initialization of a const variable";
8744 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008745
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00008746 case FK_Incomplete:
8747 OS << "initialization of incomplete type";
8748 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008749
8750 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008751 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00008752 break;
8753
John McCalla59dc2f2012-01-05 00:13:19 +00008754 case FK_VariableLengthArrayHasInitializer:
8755 OS << "variable length array has an initializer";
8756 break;
8757
John McCall4124c492011-10-17 18:40:02 +00008758 case FK_PlaceholderType:
8759 OS << "initializer expression isn't contextually valid";
8760 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00008761
8762 case FK_ListConstructorOverloadFailed:
8763 OS << "list constructor overloading failed";
8764 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008765
Sebastian Redl048a6d72012-04-01 19:54:59 +00008766 case FK_ExplicitConstructor:
8767 OS << "list copy initialization chose explicit constructor";
8768 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008769 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008770 OS << '\n';
8771 return;
8772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008773
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008774 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00008775 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008776 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008777
Sebastian Redld201edf2011-06-05 13:59:11 +00008778 case NormalSequence:
8779 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008780 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008781 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008782
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008783 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8784 if (S != step_begin()) {
8785 OS << " -> ";
8786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008787
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008788 switch (S->Kind) {
8789 case SK_ResolveAddressOfOverloadedFunction:
8790 OS << "resolve address of overloaded function";
8791 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008792
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008793 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008794 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008795 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008796
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008797 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008798 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008799 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008800
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008801 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008802 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008803 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008804
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008805 case SK_BindReference:
8806 OS << "bind reference to lvalue";
8807 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008808
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008809 case SK_BindReferenceToTemporary:
8810 OS << "bind reference to a temporary";
8811 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008812
Richard Smithb8c0f552016-12-09 18:49:13 +00008813 case SK_FinalCopy:
8814 OS << "final copy in class direct-initialization";
8815 break;
8816
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008817 case SK_ExtraneousCopyToTemporary:
8818 OS << "extraneous C++03 copy to temporary";
8819 break;
8820
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008821 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008822 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008823 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008824
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008825 case SK_QualificationConversionRValue:
8826 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008827 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008828
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008829 case SK_QualificationConversionXValue:
8830 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008831 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008832
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008833 case SK_QualificationConversionLValue:
8834 OS << "qualification conversion (lvalue)";
8835 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008836
Richard Smith77be48a2014-07-31 06:31:19 +00008837 case SK_AtomicConversion:
8838 OS << "non-atomic-to-atomic conversion";
8839 break;
8840
Jordan Roseb1312a52013-04-11 00:58:58 +00008841 case SK_LValueToRValue:
8842 OS << "load (lvalue to rvalue)";
8843 break;
8844
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008845 case SK_ConversionSequence:
8846 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008847 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008848 OS << ")";
8849 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008850
Richard Smithaaa0ec42013-09-21 21:19:19 +00008851 case SK_ConversionSequenceNoNarrowing:
8852 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008853 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008854 OS << ")";
8855 break;
8856
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008857 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008858 OS << "list aggregate initialization";
8859 break;
8860
Sebastian Redl29526f02011-11-27 16:50:07 +00008861 case SK_UnwrapInitList:
8862 OS << "unwrap reference initializer list";
8863 break;
8864
8865 case SK_RewrapInitList:
8866 OS << "rewrap reference initializer list";
8867 break;
8868
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008869 case SK_ConstructorInitialization:
8870 OS << "constructor initialization";
8871 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008872
Richard Smith53324112014-07-16 21:33:43 +00008873 case SK_ConstructorInitializationFromList:
8874 OS << "list initialization via constructor";
8875 break;
8876
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008877 case SK_ZeroInitialization:
8878 OS << "zero initialization";
8879 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008880
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008881 case SK_CAssignment:
8882 OS << "C assignment";
8883 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008884
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008885 case SK_StringInit:
8886 OS << "string initialization";
8887 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008888
8889 case SK_ObjCObjectConversion:
8890 OS << "Objective-C object conversion";
8891 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008892
Richard Smith410306b2016-12-12 02:53:20 +00008893 case SK_ArrayLoopIndex:
8894 OS << "indexing for array initialization loop";
8895 break;
8896
8897 case SK_ArrayLoopInit:
8898 OS << "array initialization loop";
8899 break;
8900
Douglas Gregore2f943b2011-02-22 18:29:51 +00008901 case SK_ArrayInit:
8902 OS << "array initialization";
8903 break;
John McCall31168b02011-06-15 23:02:42 +00008904
Richard Smith378b8c82016-12-14 03:22:16 +00008905 case SK_GNUArrayInit:
8906 OS << "array initialization (GNU extension)";
8907 break;
8908
Richard Smithebeed412012-02-15 22:38:09 +00008909 case SK_ParenthesizedArrayInit:
8910 OS << "parenthesized array initialization";
8911 break;
8912
John McCall31168b02011-06-15 23:02:42 +00008913 case SK_PassByIndirectCopyRestore:
8914 OS << "pass by indirect copy and restore";
8915 break;
8916
8917 case SK_PassByIndirectRestore:
8918 OS << "pass by indirect restore";
8919 break;
8920
8921 case SK_ProduceObjCObject:
8922 OS << "Objective-C object retension";
8923 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008924
8925 case SK_StdInitializerList:
8926 OS << "std::initializer_list from initializer list";
8927 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008928
Richard Smithf8adcdc2014-07-17 05:12:35 +00008929 case SK_StdInitializerListConstructorCall:
8930 OS << "list initialization from std::initializer_list";
8931 break;
8932
Guy Benyei61054192013-02-07 10:55:47 +00008933 case SK_OCLSamplerInit:
8934 OS << "OpenCL sampler_t from integer constant";
8935 break;
8936
Andrew Savonichevb555b762018-10-23 15:19:20 +00008937 case SK_OCLZeroOpaqueType:
8938 OS << "OpenCL opaque type from zero";
Egor Churaev89831422016-12-23 14:55:49 +00008939 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008940 }
Richard Smith6b216962013-02-05 05:52:24 +00008941
8942 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008943 }
Richard Smith6b216962013-02-05 05:52:24 +00008944
8945 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008946}
8947
8948void InitializationSequence::dump() const {
8949 dump(llvm::errs());
8950}
8951
Nico Weber3d7f00d2018-06-19 23:19:34 +00008952static bool NarrowingErrs(const LangOptions &L) {
8953 return L.CPlusPlus11 &&
8954 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
8955}
8956
Richard Smithaaa0ec42013-09-21 21:19:19 +00008957static void DiagnoseNarrowingInInitList(Sema &S,
8958 const ImplicitConversionSequence &ICS,
8959 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008960 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008961 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008962 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008963 switch (ICS.getKind()) {
8964 case ImplicitConversionSequence::StandardConversion:
8965 SCS = &ICS.Standard;
8966 break;
8967 case ImplicitConversionSequence::UserDefinedConversion:
8968 SCS = &ICS.UserDefined.After;
8969 break;
8970 case ImplicitConversionSequence::AmbiguousConversion:
8971 case ImplicitConversionSequence::EllipsisConversion:
8972 case ImplicitConversionSequence::BadConversion:
8973 return;
8974 }
8975
Richard Smith66e05fe2012-01-18 05:21:49 +00008976 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8977 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00008978 QualType ConstantType;
8979 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8980 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00008981 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00008982 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00008983 // No narrowing occurred.
8984 return;
8985
8986 case NK_Type_Narrowing:
8987 // This was a floating-to-integer conversion, which is always considered a
8988 // narrowing conversion even if the value is a constant and can be
8989 // represented exactly as an integer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008990 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
Nico Weber3d7f00d2018-06-19 23:19:34 +00008991 ? diag::ext_init_list_type_narrowing
8992 : diag::warn_init_list_type_narrowing)
8993 << PostInit->getSourceRange()
8994 << PreNarrowingType.getLocalUnqualifiedType()
8995 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008996 break;
8997
8998 case NK_Constant_Narrowing:
8999 // A constant value was narrowed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009000 S.Diag(PostInit->getBeginLoc(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00009001 NarrowingErrs(S.getLangOpts())
9002 ? diag::ext_init_list_constant_narrowing
9003 : diag::warn_init_list_constant_narrowing)
9004 << PostInit->getSourceRange()
9005 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9006 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009007 break;
9008
9009 case NK_Variable_Narrowing:
9010 // A variable's value may have been narrowed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009011 S.Diag(PostInit->getBeginLoc(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00009012 NarrowingErrs(S.getLangOpts())
9013 ? diag::ext_init_list_variable_narrowing
9014 : diag::warn_init_list_variable_narrowing)
9015 << PostInit->getSourceRange()
9016 << PreNarrowingType.getLocalUnqualifiedType()
9017 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009018 break;
9019 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009020
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009021 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009022 llvm::raw_svector_ostream OS(StaticCast);
9023 OS << "static_cast<";
9024 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9025 // It's important to use the typedef's name if there is one so that the
9026 // fixit doesn't break code using types like int64_t.
9027 //
9028 // FIXME: This will break if the typedef requires qualification. But
9029 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00009030 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009031 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00009032 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009033 else {
9034 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9035 // with a broken cast.
9036 return;
9037 }
9038 OS << ">(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009039 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009040 << PostInit->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009041 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
Alp Tokerb6cc5922014-05-03 03:45:55 +00009042 << FixItHint::CreateInsertion(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009043 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009044}
9045
Douglas Gregore1314a62009-12-18 05:02:21 +00009046//===----------------------------------------------------------------------===//
9047// Initialization helper functions
9048//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00009049bool
9050Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
9051 ExprResult Init) {
9052 if (Init.isInvalid())
9053 return false;
9054
9055 Expr *InitE = Init.get();
9056 assert(InitE && "No initialization expression");
9057
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009058 InitializationKind Kind =
9059 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00009060 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00009061 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00009062}
9063
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009064ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00009065Sema::PerformCopyInitialization(const InitializedEntity &Entity,
9066 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009067 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00009068 bool TopLevelOfInitList,
9069 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00009070 if (Init.isInvalid())
9071 return ExprError();
9072
John McCall1f425642010-11-11 03:21:53 +00009073 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00009074 assert(InitE && "No initialization expression?");
9075
9076 if (EqualLoc.isInvalid())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009077 EqualLoc = InitE->getBeginLoc();
Douglas Gregore1314a62009-12-18 05:02:21 +00009078
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009079 InitializationKind Kind = InitializationKind::CreateCopy(
9080 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00009081 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009082
Alex Lorenzde69ff92017-05-16 10:23:58 +00009083 // Prevent infinite recursion when performing parameter copy-initialization.
9084 const bool ShouldTrackCopy =
9085 Entity.isParameterKind() && Seq.isConstructorInitialization();
9086 if (ShouldTrackCopy) {
9087 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
9088 CurrentParameterCopyTypes.end()) {
9089 Seq.SetOverloadFailure(
9090 InitializationSequence::FK_ConstructorOverloadFailed,
9091 OR_No_Viable_Function);
9092
9093 // Try to give a meaningful diagnostic note for the problematic
9094 // constructor.
9095 const auto LastStep = Seq.step_end() - 1;
9096 assert(LastStep->Kind ==
9097 InitializationSequence::SK_ConstructorInitialization);
9098 const FunctionDecl *Function = LastStep->Function.Function;
9099 auto Candidate =
9100 llvm::find_if(Seq.getFailedCandidateSet(),
9101 [Function](const OverloadCandidate &Candidate) -> bool {
9102 return Candidate.Viable &&
9103 Candidate.Function == Function &&
9104 Candidate.Conversions.size() > 0;
9105 });
9106 if (Candidate != Seq.getFailedCandidateSet().end() &&
9107 Function->getNumParams() > 0) {
9108 Candidate->Viable = false;
9109 Candidate->FailureKind = ovl_fail_bad_conversion;
9110 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9111 InitE,
9112 Function->getParamDecl(0)->getType());
9113 }
9114 }
9115 CurrentParameterCopyTypes.push_back(Entity.getType());
9116 }
9117
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00009118 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00009119
Alex Lorenzde69ff92017-05-16 10:23:58 +00009120 if (ShouldTrackCopy)
9121 CurrentParameterCopyTypes.pop_back();
9122
Richard Smith66e05fe2012-01-18 05:21:49 +00009123 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00009124}
Richard Smith60437622017-02-09 19:17:44 +00009125
Richard Smith1363e8f2017-09-07 07:22:36 +00009126/// Determine whether RD is, or is derived from, a specialization of CTD.
9127static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
9128 ClassTemplateDecl *CTD) {
9129 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9130 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9131 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9132 };
9133 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9134}
9135
Richard Smith60437622017-02-09 19:17:44 +00009136QualType Sema::DeduceTemplateSpecializationFromInitializer(
9137 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9138 const InitializationKind &Kind, MultiExprArg Inits) {
9139 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9140 TSInfo->getType()->getContainedDeducedType());
9141 assert(DeducedTST && "not a deduced template specialization type");
9142
Richard Smith60437622017-02-09 19:17:44 +00009143 auto TemplateName = DeducedTST->getTemplateName();
Richard Smithcff42012018-09-28 03:18:53 +00009144 if (TemplateName.isDependent())
9145 return Context.DependentTy;
9146
9147 // We can only perform deduction for class templates.
Richard Smith60437622017-02-09 19:17:44 +00009148 auto *Template =
9149 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
9150 if (!Template) {
9151 Diag(Kind.getLocation(),
9152 diag::err_deduced_non_class_template_specialization_type)
9153 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
9154 if (auto *TD = TemplateName.getAsTemplateDecl())
9155 Diag(TD->getLocation(), diag::note_template_decl_here);
9156 return QualType();
9157 }
9158
Richard Smith32918772017-02-14 00:25:28 +00009159 // Can't deduce from dependent arguments.
Richard Smith8eeb16f2018-09-10 20:31:03 +00009160 if (Expr::hasAnyTypeDependentArguments(Inits)) {
9161 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9162 diag::warn_cxx14_compat_class_template_argument_deduction)
9163 << TSInfo->getTypeLoc().getSourceRange() << 0;
Richard Smith32918772017-02-14 00:25:28 +00009164 return Context.DependentTy;
Richard Smith8eeb16f2018-09-10 20:31:03 +00009165 }
Richard Smith32918772017-02-14 00:25:28 +00009166
Richard Smith60437622017-02-09 19:17:44 +00009167 // FIXME: Perform "exact type" matching first, per CWG discussion?
9168 // Or implement this via an implied 'T(T) -> T' deduction guide?
9169
9170 // FIXME: Do we need/want a std::initializer_list<T> special case?
9171
Richard Smith32918772017-02-14 00:25:28 +00009172 // Look up deduction guides, including those synthesized from constructors.
9173 //
Richard Smith60437622017-02-09 19:17:44 +00009174 // C++1z [over.match.class.deduct]p1:
9175 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00009176 // - For each constructor of the class template designated by the
9177 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00009178 // - For each deduction-guide, a function or function template [...]
9179 DeclarationNameInfo NameInfo(
9180 Context.DeclarationNames.getCXXDeductionGuideName(Template),
9181 TSInfo->getTypeLoc().getEndLoc());
9182 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
9183 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00009184
9185 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9186 // clear on this, but they're not found by name so access does not apply.
9187 Guides.suppressDiagnostics();
9188
9189 // Figure out if this is list-initialization.
9190 InitListExpr *ListInit =
9191 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
9192 ? dyn_cast<InitListExpr>(Inits[0])
9193 : nullptr;
9194
9195 // C++1z [over.match.class.deduct]p1:
9196 // Initialization and overload resolution are performed as described in
9197 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9198 // (as appropriate for the type of initialization performed) for an object
9199 // of a hypothetical class type, where the selected functions and function
9200 // templates are considered to be the constructors of that class type
9201 //
9202 // Since we know we're initializing a class type of a type unrelated to that
9203 // of the initializer, this reduces to something fairly reasonable.
9204 OverloadCandidateSet Candidates(Kind.getLocation(),
9205 OverloadCandidateSet::CSK_Normal);
9206 OverloadCandidateSet::iterator Best;
9207 auto tryToResolveOverload =
9208 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00009209 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Richard Smith32918772017-02-14 00:25:28 +00009210 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
9211 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00009212 if (D->isInvalidDecl())
9213 continue;
9214
Richard Smithbc491202017-02-17 20:05:37 +00009215 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
9216 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
9217 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9218 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00009219 continue;
9220
9221 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9222 // For copy-initialization, the candidate functions are all the
9223 // converting constructors (12.3.1) of that class.
9224 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9225 // The converting constructors of T are candidate functions.
9226 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00009227 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00009228 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00009229 continue;
Richard Smith60437622017-02-09 19:17:44 +00009230
9231 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00009232 // could never be called with one argument are not interesting to
9233 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00009234 if (GD->getMinRequiredArguments() > 1 ||
9235 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00009236 continue;
9237 }
9238
9239 // C++ [over.match.list]p1.1: (first phase list initialization)
9240 // Initially, the candidate functions are the initializer-list
9241 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00009242 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00009243 continue;
9244
9245 // C++ [over.match.list]p1.2: (second phase list initialization)
9246 // the candidate functions are all the constructors of the class T
9247 // C++ [over.match.ctor]p1: (all other cases)
9248 // the candidate functions are all the constructors of the class of
9249 // the object being initialized
9250
9251 // C++ [over.best.ics]p4:
9252 // When [...] the constructor [...] is a candidate by
9253 // - [over.match.copy] (in all cases)
9254 // FIXME: The "second phase of [over.match.list] case can also
9255 // theoretically happen here, but it's not clear whether we can
9256 // ever have a parameter of the right type.
9257 bool SuppressUserConversions = Kind.isCopyInit();
9258
Richard Smith60437622017-02-09 19:17:44 +00009259 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00009260 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
9261 Inits, Candidates,
9262 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00009263 else
Richard Smithbc491202017-02-17 20:05:37 +00009264 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00009265 SuppressUserConversions);
9266 }
9267 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
9268 };
9269
9270 OverloadingResult Result = OR_No_Viable_Function;
9271
9272 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9273 // try initializer-list constructors.
9274 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00009275 bool TryListConstructors = true;
9276
9277 // Try list constructors unless the list is empty and the class has one or
9278 // more default constructors, in which case those constructors win.
9279 if (!ListInit->getNumInits()) {
9280 for (NamedDecl *D : Guides) {
9281 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9282 if (FD && FD->getMinRequiredArguments() == 0) {
9283 TryListConstructors = false;
9284 break;
9285 }
9286 }
Richard Smith1363e8f2017-09-07 07:22:36 +00009287 } else if (ListInit->getNumInits() == 1) {
9288 // C++ [over.match.class.deduct]:
9289 // As an exception, the first phase in [over.match.list] (considering
9290 // initializer-list constructors) is omitted if the initializer list
9291 // consists of a single expression of type cv U, where U is a
9292 // specialization of C or a class derived from a specialization of C.
9293 Expr *E = ListInit->getInit(0);
9294 auto *RD = E->getType()->getAsCXXRecordDecl();
9295 if (!isa<InitListExpr>(E) && RD &&
Erik Pilkingtondd0b3442018-07-26 23:40:42 +00009296 isCompleteType(Kind.getLocation(), E->getType()) &&
Richard Smith1363e8f2017-09-07 07:22:36 +00009297 isOrIsDerivedFromSpecializationOf(RD, Template))
9298 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00009299 }
9300
9301 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00009302 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
9303 // Then unwrap the initializer list and try again considering all
9304 // constructors.
9305 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
9306 }
9307
9308 // If list-initialization fails, or if we're doing any other kind of
9309 // initialization, we (eventually) consider constructors.
9310 if (Result == OR_No_Viable_Function)
9311 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
9312
9313 switch (Result) {
9314 case OR_Ambiguous:
9315 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
9316 << TemplateName;
9317 // FIXME: For list-initialization candidates, it'd usually be better to
9318 // list why they were not viable when given the initializer list itself as
9319 // an argument.
9320 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
9321 return QualType();
9322
Richard Smith32918772017-02-14 00:25:28 +00009323 case OR_No_Viable_Function: {
9324 CXXRecordDecl *Primary =
9325 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
9326 bool Complete =
9327 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00009328 Diag(Kind.getLocation(),
9329 Complete ? diag::err_deduced_class_template_ctor_no_viable
9330 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00009331 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00009332 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
9333 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00009334 }
Richard Smith60437622017-02-09 19:17:44 +00009335
9336 case OR_Deleted: {
9337 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
9338 << TemplateName;
9339 NoteDeletedFunction(Best->Function);
9340 return QualType();
9341 }
9342
9343 case OR_Success:
9344 // C++ [over.match.list]p1:
9345 // In copy-list-initialization, if an explicit constructor is chosen, the
9346 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00009347 if (Kind.isCopyInit() && ListInit &&
9348 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00009349 bool IsDeductionGuide = !Best->Function->isImplicit();
9350 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
9351 << TemplateName << IsDeductionGuide;
9352 Diag(Best->Function->getLocation(),
9353 diag::note_explicit_ctor_deduction_guide_here)
9354 << IsDeductionGuide;
9355 return QualType();
9356 }
9357
9358 // Make sure we didn't select an unusable deduction guide, and mark it
9359 // as referenced.
9360 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
9361 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
9362 break;
9363 }
9364
9365 // C++ [dcl.type.class.deduct]p1:
9366 // The placeholder is replaced by the return type of the function selected
9367 // by overload resolution for class template deduction.
Richard Smith8eeb16f2018-09-10 20:31:03 +00009368 QualType DeducedType =
9369 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
9370 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9371 diag::warn_cxx14_compat_class_template_argument_deduction)
9372 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
9373 return DeducedType;
Richard Smith60437622017-02-09 19:17:44 +00009374}