blob: 693d759db2151a49f3eef60e50c6b98f1c01593d [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Steve Narofff8ecff22008-05-01 22:18:59 +00006//
7//===----------------------------------------------------------------------===//
8//
Sebastian Redl26bcc942011-09-24 17:47:39 +00009// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000010//
Steve Narofff8ecff22008-05-01 22:18:59 +000011//===----------------------------------------------------------------------===//
12
Steve Narofff8ecff22008-05-01 22:18:59 +000013#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000014#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000015#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000016#include "clang/AST/ExprObjC.h"
Richard Smithafe48f92018-07-23 21:21:22 +000017#include "clang/AST/ExprOpenMP.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000018#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000019#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Designator.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000028
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000035/// Check whether T is compatible with a wide character type (wchar_t,
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000036/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38 if (Context.typesAreCompatible(Context.getWideCharType(), T))
39 return true;
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
43 }
44 return false;
45}
46
47enum StringInitFailureKind {
48 SIF_None,
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
Richard Smith3a8244d2018-05-01 05:02:45 +000052 SIF_UTF8StringIntoPlainChar,
53 SIF_PlainStringIntoUTF8Char,
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000054 SIF_Other
55};
56
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Check whether the array of type AT can be initialized by the Init
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000058/// expression by means of string initialization. Returns SIF_None if so,
59/// otherwise returns a StringInitFailureKind that describes why the
60/// initialization would not work.
61static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
62 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000063 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000064 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000065
Chris Lattnera9196812009-02-26 23:26:43 +000066 // See if this is a string literal or @encode.
67 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000068
Chris Lattnera9196812009-02-26 23:26:43 +000069 // Handle @encode, which is a narrow string.
70 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000071 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000072
73 // Otherwise we can only handle string literals.
74 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000075 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000076 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000077
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000078 const QualType ElemTy =
79 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000080
81 switch (SL->getKind()) {
Douglas Gregorfb65e592011-07-27 05:40:30 +000082 case StringLiteral::UTF8:
Richard Smith3a8244d2018-05-01 05:02:45 +000083 // char8_t array can be initialized with a UTF-8 string.
84 if (ElemTy->isChar8Type())
85 return SIF_None;
86 LLVM_FALLTHROUGH;
87 case StringLiteral::Ascii:
Douglas Gregorfb65e592011-07-27 05:40:30 +000088 // char array can be initialized with a narrow string.
89 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000090 if (ElemTy->isCharType())
Richard Smith3a8244d2018-05-01 05:02:45 +000091 return (SL->getKind() == StringLiteral::UTF8 &&
92 Context.getLangOpts().Char8)
93 ? SIF_UTF8StringIntoPlainChar
94 : SIF_None;
95 if (ElemTy->isChar8Type())
96 return SIF_PlainStringIntoUTF8Char;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000097 if (IsWideCharCompatible(ElemTy, Context))
98 return SIF_NarrowStringIntoWideChar;
99 return SIF_Other;
100 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
101 // "An array with element type compatible with a qualified or unqualified
102 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
103 // string literal with the corresponding encoding prefix (L, u, or U,
104 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +0000105 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000106 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
107 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000108 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000109 return SIF_WideStringIntoChar;
110 if (IsWideCharCompatible(ElemTy, Context))
111 return SIF_IncompatWideStringIntoWideChar;
112 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000113 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000114 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
115 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000116 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000117 return SIF_WideStringIntoChar;
118 if (IsWideCharCompatible(ElemTy, Context))
119 return SIF_IncompatWideStringIntoWideChar;
120 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000121 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000122 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
123 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000124 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000125 return SIF_WideStringIntoChar;
126 if (IsWideCharCompatible(ElemTy, Context))
127 return SIF_IncompatWideStringIntoWideChar;
128 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000129 }
Mike Stump11289f42009-09-09 15:08:12 +0000130
Douglas Gregorfb65e592011-07-27 05:40:30 +0000131 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000132}
133
Hans Wennborg950f3182013-05-16 09:22:40 +0000134static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
135 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000136 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000137 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000138 return SIF_Other;
139 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000140}
141
Richard Smith430c23b2013-05-05 16:40:13 +0000142/// Update the type of a string literal, including any surrounding parentheses,
143/// to match the type of the object which it is initializing.
144static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000145 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000146 E->setType(Ty);
Eli Friedman3bf72d72019-02-08 21:18:46 +0000147 E->setValueKind(VK_RValue);
Eli Friedman88fccbd2019-02-11 22:54:27 +0000148 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
Richard Smithd74b16062013-05-06 00:35:47 +0000149 break;
Eli Friedman88fccbd2019-02-11 22:54:27 +0000150 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Richard Smithd74b16062013-05-06 00:35:47 +0000151 E = PE->getSubExpr();
Eli Friedman88fccbd2019-02-11 22:54:27 +0000152 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
153 assert(UO->getOpcode() == UO_Extension);
Richard Smithd74b16062013-05-06 00:35:47 +0000154 E = UO->getSubExpr();
Eli Friedman88fccbd2019-02-11 22:54:27 +0000155 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
Richard Smithd74b16062013-05-06 00:35:47 +0000156 E = GSE->getResultExpr();
Eli Friedman88fccbd2019-02-11 22:54:27 +0000157 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
158 E = CE->getChosenSubExpr();
159 } else {
Richard Smithd74b16062013-05-06 00:35:47 +0000160 llvm_unreachable("unexpected expr in string literal init");
Eli Friedman88fccbd2019-02-11 22:54:27 +0000161 }
162 }
163}
164
165/// Fix a compound literal initializing an array so it's correctly marked
166/// as an rvalue.
167static void updateGNUCompoundLiteralRValue(Expr *E) {
168 while (true) {
169 E->setValueKind(VK_RValue);
170 if (isa<CompoundLiteralExpr>(E)) {
171 break;
172 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
173 E = PE->getSubExpr();
174 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
175 assert(UO->getOpcode() == UO_Extension);
176 E = UO->getSubExpr();
177 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
178 E = GSE->getResultExpr();
179 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
180 E = CE->getChosenSubExpr();
181 } else {
182 llvm_unreachable("unexpected expr in array compound literal init");
183 }
Richard Smith430c23b2013-05-05 16:40:13 +0000184 }
Richard Smith430c23b2013-05-05 16:40:13 +0000185}
186
John McCall5decec92011-02-21 07:57:55 +0000187static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
188 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000189 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000190 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000191 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000192 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattner0cb78032009-02-24 22:27:37 +0000194 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000195 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000196 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000197 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000198 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000199 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
200 ConstVal,
201 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000202 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000203 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000204 }
Mike Stump11289f42009-09-09 15:08:12 +0000205
Eli Friedman893abe42009-05-29 18:22:49 +0000206 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000207
Eli Friedman554eba92011-04-11 00:23:45 +0000208 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000209 // the size may be smaller or larger than the string we are initializing.
210 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000211 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000212 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000213 // For Pascal strings it's OK to strip off the terminating null character,
214 // so the example below is valid:
215 //
216 // unsigned char a[2] = "\pa";
217 if (SL->isPascal())
218 StrLength--;
219 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000220
Eli Friedman554eba92011-04-11 00:23:45 +0000221 // [dcl.init.string]p2
222 if (StrLength > CAT->getSize().getZExtValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000223 S.Diag(Str->getBeginLoc(),
Eli Friedman554eba92011-04-11 00:23:45 +0000224 diag::err_initializer_string_for_char_array_too_long)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000225 << Str->getSourceRange();
Eli Friedman554eba92011-04-11 00:23:45 +0000226 } else {
227 // C99 6.7.8p14.
228 if (StrLength-1 > CAT->getSize().getZExtValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000229 S.Diag(Str->getBeginLoc(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000230 diag::ext_initializer_string_for_char_array_too_long)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000231 << Str->getSourceRange();
Eli Friedman554eba92011-04-11 00:23:45 +0000232 }
Mike Stump11289f42009-09-09 15:08:12 +0000233
Eli Friedman893abe42009-05-29 18:22:49 +0000234 // Set the type to the actual size that we are initializing. If we have
235 // something like:
236 // char x[1] = "foo";
237 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000238 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000239}
240
Chris Lattner0cb78032009-02-24 22:27:37 +0000241//===----------------------------------------------------------------------===//
242// Semantic checking for initializer lists.
243//===----------------------------------------------------------------------===//
244
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000245namespace {
246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247/// Semantic checking for initializer lists.
Douglas Gregorcde232f2009-01-29 01:05:33 +0000248///
249/// The InitListChecker class contains a set of routines that each
250/// handle the initialization of a certain kind of entity, e.g.,
251/// arrays, vectors, struct/union types, scalars, etc. The
252/// InitListChecker itself performs a recursive walk of the subobject
253/// structure of the type to be initialized, while stepping through
254/// the initializer list one element at a time. The IList and Index
255/// parameters to each of the Check* routines contain the active
256/// (syntactic) initializer list and the index into that initializer
257/// list that represents the current initializer. Each routine is
258/// responsible for moving that Index forward as it consumes elements.
259///
260/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000261/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000262/// initializer list and the index into that initializer list where we
263/// are copying initializers as we map them over to the semantic
264/// list. Once we have completed our recursive walk of the subobject
265/// structure, we will have constructed a full semantic initializer
266/// list.
267///
268/// C99 designators cause changes in the initializer list traversal,
269/// because they make the initialization "jump" into a specific
270/// subobject and then continue the initialization from that
271/// point. CheckDesignatedInitializer() recursively steps into the
272/// designated subobject and manages backing out the recursion to
273/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000274class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000275 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000276 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000277 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000278 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000279 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000280 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000281
Anders Carlsson6cabf312010-01-23 23:23:01 +0000282 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000283 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000284 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000285 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000286 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000287 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000288 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000289 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000290 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000291 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000292 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000293 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000294 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000295 unsigned &StructuredIndex,
296 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000297 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000298 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000299 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000300 InitListExpr *StructuredList,
301 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000302 void CheckComplexType(const InitializedEntity &Entity,
303 InitListExpr *IList, QualType DeclType,
304 unsigned &Index,
305 InitListExpr *StructuredList,
306 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000307 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000308 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000309 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000310 InitListExpr *StructuredList,
311 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000312 void CheckReferenceType(const InitializedEntity &Entity,
313 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000314 unsigned &Index,
315 InitListExpr *StructuredList,
316 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000317 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000318 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000319 InitListExpr *StructuredList,
320 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000321 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000322 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000323 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000324 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000325 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000326 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000327 unsigned &StructuredIndex,
328 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000329 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000330 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000331 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000332 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000333 InitListExpr *StructuredList,
334 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000335 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000336 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000337 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000338 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000339 RecordDecl::field_iterator *NextField,
340 llvm::APSInt *NextElementIndex,
341 unsigned &Index,
342 InitListExpr *StructuredList,
343 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000344 bool FinishSubobjectInit,
345 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000346 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
347 QualType CurrentObjectType,
348 InitListExpr *StructuredList,
349 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000350 SourceRange InitRange,
351 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000352 void UpdateStructuredListElement(InitListExpr *StructuredList,
353 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000354 Expr *expr);
355 int numArrayElements(QualType DeclType);
356 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000357
Richard Smith454a7cd2014-06-03 08:26:00 +0000358 static ExprResult PerformEmptyInit(Sema &SemaRef,
359 SourceLocation Loc,
360 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000361 bool VerifyOnly,
362 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000363
364 // Explanation on the "FillWithNoInit" mode:
365 //
366 // Assume we have the following definitions (Case#1):
367 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
368 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
369 //
370 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
371 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
372 //
373 // But if we have (Case#2):
374 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
375 //
376 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
377 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
378 //
379 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
380 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
381 // initializers but with special "NoInitExpr" place holders, which tells the
382 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000383 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
384 const InitializedEntity &ParentEntity,
385 InitListExpr *ILE, bool &RequiresSecondPass,
386 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000387 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000388 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000389 InitListExpr *ILE, bool &RequiresSecondPass,
390 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000391 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000392 InitListExpr *ILE, bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000393 InitListExpr *OuterILE, unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000394 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000395 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
396 Expr *InitExpr, FieldDecl *Field,
397 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000398 void CheckEmptyInitializable(const InitializedEntity &Entity,
399 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000400
Douglas Gregor85df8d82009-01-29 00:45:39 +0000401public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000402 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000403 InitListExpr *IL, QualType &T, bool VerifyOnly,
404 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000405 bool HadError() { return hadError; }
406
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000407 // Retrieves the fully-structured initializer list used for
Douglas Gregor85df8d82009-01-29 00:45:39 +0000408 // semantic analysis and code generation.
409 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
410};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000411
Chris Lattner9ececce2009-02-24 22:48:58 +0000412} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000413
Richard Smith454a7cd2014-06-03 08:26:00 +0000414ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
415 SourceLocation Loc,
416 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000417 bool VerifyOnly,
418 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000419 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
420 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000421 MultiExprArg SubInit;
422 Expr *InitExpr;
423 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
424
425 // C++ [dcl.init.aggr]p7:
426 // If there are fewer initializer-clauses in the list than there are
427 // members in the aggregate, then each member not explicitly initialized
428 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000429 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
430 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
431 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000432 // C++1y / DR1070:
433 // shall be initialized [...] from an empty initializer list.
434 //
435 // We apply the resolution of this DR to C++11 but not C++98, since C++98
436 // does not have useful semantics for initialization from an init list.
437 // We treat this as copy-initialization, because aggregate initialization
438 // always performs copy-initialization on its elements.
439 //
440 // Only do this if we're initializing a class type, to avoid filling in
441 // the initializer list where possible.
442 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
443 InitListExpr(SemaRef.Context, Loc, None, Loc);
444 InitExpr->setType(SemaRef.Context.VoidTy);
445 SubInit = InitExpr;
446 Kind = InitializationKind::CreateCopy(Loc, Loc);
447 } else {
448 // C++03:
449 // shall be value-initialized.
450 }
451
452 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000453 // libstdc++4.6 marks the vector default constructor as explicit in
454 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
455 // stlport does so too. Look for std::__debug for libstdc++, and for
456 // std:: for stlport. This is effectively a compiler-side implementation of
457 // LWG2193.
458 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
459 InitializationSequence::FK_ExplicitConstructor) {
460 OverloadCandidateSet::iterator Best;
461 OverloadingResult O =
462 InitSeq.getFailedCandidateSet()
463 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
464 (void)O;
465 assert(O == OR_Success && "Inconsistent overload resolution");
466 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
467 CXXRecordDecl *R = CtorDecl->getParent();
468
469 if (CtorDecl->getMinRequiredArguments() == 0 &&
470 CtorDecl->isExplicit() && R->getDeclName() &&
471 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000472 bool IsInStd = false;
473 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000474 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000475 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
476 IsInStd = true;
477 }
478
Fangrui Song6907ce22018-07-30 19:24:48 +0000479 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
Nico Weberbcb70ee2014-07-02 23:51:09 +0000480 .Cases("basic_string", "deque", "forward_list", true)
481 .Cases("list", "map", "multimap", "multiset", true)
482 .Cases("priority_queue", "queue", "set", "stack", true)
483 .Cases("unordered_map", "unordered_set", "vector", true)
484 .Default(false)) {
485 InitSeq.InitializeFrom(
486 SemaRef, Entity,
487 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000488 MultiExprArg(), /*TopLevelOfInitList=*/false,
489 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000490 // Emit a warning for this. System header warnings aren't shown
491 // by default, but people working on system headers should see it.
492 if (!VerifyOnly) {
493 SemaRef.Diag(CtorDecl->getLocation(),
494 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000495 if (Entity.getKind() == InitializedEntity::EK_Member)
496 SemaRef.Diag(Entity.getDecl()->getLocation(),
497 diag::note_used_in_initialization_here);
498 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
499 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000500 }
501 }
502 }
503 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000504 if (!InitSeq) {
505 if (!VerifyOnly) {
506 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
507 if (Entity.getKind() == InitializedEntity::EK_Member)
508 SemaRef.Diag(Entity.getDecl()->getLocation(),
509 diag::note_in_omitted_aggregate_initializer)
510 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000511 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
512 bool IsTrailingArrayNewMember =
513 Entity.getParent() &&
514 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000515 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000516 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
517 << Entity.getElementIndex();
518 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000519 }
520 return ExprError();
521 }
522
523 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
524 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
525}
526
527void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
528 SourceLocation Loc) {
529 assert(VerifyOnly &&
530 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000531 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
532 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000533 hadError = true;
534}
535
Richard Smith872307e2016-03-08 22:17:41 +0000536void InitListChecker::FillInEmptyInitForBase(
537 unsigned Init, const CXXBaseSpecifier &Base,
538 const InitializedEntity &ParentEntity, InitListExpr *ILE,
539 bool &RequiresSecondPass, bool FillWithNoInit) {
540 assert(Init < ILE->getNumInits() && "should have been expanded");
541
542 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
543 SemaRef.Context, &Base, false, &ParentEntity);
544
545 if (!ILE->getInit(Init)) {
546 ExprResult BaseInit =
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000547 FillWithNoInit
548 ? new (SemaRef.Context) NoInitExpr(Base.getType())
549 : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
550 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000551 if (BaseInit.isInvalid()) {
552 hadError = true;
553 return;
554 }
555
556 ILE->setInit(Init, BaseInit.getAs<Expr>());
557 } else if (InitListExpr *InnerILE =
558 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
Richard Smithf3b4ca82018-02-07 22:25:16 +0000559 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
560 ILE, Init, FillWithNoInit);
Richard Smith872307e2016-03-08 22:17:41 +0000561 } else if (DesignatedInitUpdateExpr *InnerDIUE =
562 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
563 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000564 RequiresSecondPass, ILE, Init,
565 /*FillWithNoInit =*/true);
Richard Smith872307e2016-03-08 22:17:41 +0000566 }
567}
568
Richard Smith454a7cd2014-06-03 08:26:00 +0000569void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000570 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000572 bool &RequiresSecondPass,
573 bool FillWithNoInit) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000574 SourceLocation Loc = ILE->getEndLoc();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000575 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000577 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000578
579 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
580 if (!RType->getDecl()->isUnion())
581 assert(Init < NumInits && "This ILE should have been expanded");
582
Douglas Gregor2bb07652009-12-22 00:05:34 +0000583 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000584 if (FillWithNoInit) {
585 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
586 if (Init < NumInits)
587 ILE->setInit(Init, Filler);
588 else
589 ILE->updateInit(SemaRef.Context, Init, Filler);
590 return;
591 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000592 // C++1y [dcl.init.aggr]p7:
593 // If there are fewer initializer-clauses in the list than there are
594 // members in the aggregate, then each member not explicitly initialized
595 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000596 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000597 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
598 if (DIE.isInvalid()) {
599 hadError = true;
600 return;
601 }
Richard Smithd87aab92018-07-17 22:24:09 +0000602 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000603 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000604 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000605 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000606 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000607 RequiresSecondPass = true;
608 }
609 return;
610 }
611
Douglas Gregor2bb07652009-12-22 00:05:34 +0000612 if (Field->getType()->isReferenceType()) {
613 // C++ [dcl.init.aggr]p9:
614 // If an incomplete or empty initializer-list leaves a
615 // member of reference type uninitialized, the program is
616 // ill-formed.
617 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
618 << Field->getType()
619 << ILE->getSyntacticForm()->getSourceRange();
620 SemaRef.Diag(Field->getLocation(),
621 diag::note_uninit_reference_member);
622 hadError = true;
623 return;
624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Richard Smith454a7cd2014-06-03 08:26:00 +0000626 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000627 /*VerifyOnly*/false,
628 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000629 if (MemberInit.isInvalid()) {
630 hadError = true;
631 return;
632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633
Douglas Gregor2bb07652009-12-22 00:05:34 +0000634 if (hadError) {
635 // Do nothing
636 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000637 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000638 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
639 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000640 // extend the initializer list to include the constructor
641 // call and make a note that we'll need to take another pass
642 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000643 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000644 RequiresSecondPass = true;
645 }
646 } else if (InitListExpr *InnerILE
647 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000648 FillInEmptyInitializations(MemberEntity, InnerILE,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000649 RequiresSecondPass, ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000650 else if (DesignatedInitUpdateExpr *InnerDIUE
651 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
652 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000653 RequiresSecondPass, ILE, Init,
654 /*FillWithNoInit =*/true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000655}
656
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000657/// Recursively replaces NULL values within the given initializer list
658/// with expressions that perform value-initialization of the
Richard Smithf3b4ca82018-02-07 22:25:16 +0000659/// appropriate type, and finish off the InitListExpr formation.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000660void
Richard Smith454a7cd2014-06-03 08:26:00 +0000661InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000662 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000663 bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000664 InitListExpr *OuterILE,
665 unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000666 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000667 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000668 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000669
Richard Smithf3b4ca82018-02-07 22:25:16 +0000670 // If this is a nested initializer list, we might have changed its contents
671 // (and therefore some of its properties, such as instantiation-dependence)
672 // while filling it in. Inform the outer initializer list so that its state
673 // can be updated to match.
674 // FIXME: We should fully build the inner initializers before constructing
675 // the outer InitListExpr instead of mutating AST nodes after they have
676 // been used as subexpressions of other nodes.
677 struct UpdateOuterILEWithUpdatedInit {
678 InitListExpr *Outer;
679 unsigned OuterIndex;
680 ~UpdateOuterILEWithUpdatedInit() {
681 if (Outer)
682 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
683 }
684 } UpdateOuterRAII = {OuterILE, OuterIndex};
685
Richard Smith382bc512017-02-23 22:41:47 +0000686 // A transparent ILE is not performing aggregate initialization and should
687 // not be filled in.
688 if (ILE->isTransparent())
689 return;
690
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000691 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000692 const RecordDecl *RDecl = RType->getDecl();
693 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000694 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000695 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000696 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
697 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000698 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000699 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000700 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
701 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000702 break;
703 }
704 }
705 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000706 // The fields beyond ILE->getNumInits() are default initialized, so in
707 // order to leave them uninitialized, the ILE is expanded and the extra
708 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000709 unsigned NumElems = numStructUnionElements(ILE->getType());
710 if (RDecl->hasFlexibleArrayMember())
711 ++NumElems;
712 if (ILE->getNumInits() < NumElems)
713 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000714
Douglas Gregor2bb07652009-12-22 00:05:34 +0000715 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000716
717 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
718 for (auto &Base : CXXRD->bases()) {
719 if (hadError)
720 return;
721
722 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
723 FillWithNoInit);
724 ++Init;
725 }
726 }
727
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000728 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000729 if (Field->isUnnamedBitfield())
730 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000731
Douglas Gregor2bb07652009-12-22 00:05:34 +0000732 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000733 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000734
Yunzhong Gaocb779302015-06-10 00:27:52 +0000735 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
736 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000737 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000738 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000739
Douglas Gregor2bb07652009-12-22 00:05:34 +0000740 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000741
Douglas Gregor2bb07652009-12-22 00:05:34 +0000742 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000743 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000744 break;
745 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000746 }
747
748 return;
Mike Stump11289f42009-09-09 15:08:12 +0000749 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000750
751 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000752
Douglas Gregor723796a2009-12-16 06:35:08 +0000753 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000754 unsigned NumInits = ILE->getNumInits();
755 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000756 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000757 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000758 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000759 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000760 // For an array new with an unknown bound, ask for one additional element
761 // in order to populate the array filler.
762 if (Entity.isVariableLengthArrayNew())
763 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000765 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000766 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000767 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000768 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000770 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000771 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000772 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000773
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000774 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000775 if (hadError)
776 return;
777
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000778 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
779 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000780 ElementEntity.setElementIndex(Init);
781
Richard Smith3e268632018-05-23 23:41:38 +0000782 if (Init >= NumInits && ILE->hasArrayFiller())
783 return;
784
Craig Topperc3ec1492014-05-26 06:22:03 +0000785 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000786 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
787 ILE->setInit(Init, ILE->getArrayFiller());
788 else if (!InitExpr && !ILE->hasArrayFiller()) {
789 Expr *Filler = nullptr;
790
791 if (FillWithNoInit)
792 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
793 else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000794 ExprResult ElementInit =
795 PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
796 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000797 if (ElementInit.isInvalid()) {
798 hadError = true;
799 return;
800 }
801
802 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000803 }
804
805 if (hadError) {
806 // Do nothing
807 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000808 // For arrays, just set the expression used for value-initialization
809 // of the "holes" in the array.
810 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000811 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000812 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000813 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000814 } else {
815 // For arrays, just set the expression used for value-initialization
816 // of the rest of elements and exit.
817 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000818 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000819 return;
820 }
821
Yunzhong Gaocb779302015-06-10 00:27:52 +0000822 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000823 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000824 // extend the initializer list to include the constructor
825 // call and make a note that we'll need to take another pass
826 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000827 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000828 RequiresSecondPass = true;
829 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000830 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000831 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000832 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000833 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000834 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000835 else if (DesignatedInitUpdateExpr *InnerDIUE
836 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
837 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000838 RequiresSecondPass, ILE, Init,
839 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000840 }
841}
842
Douglas Gregor723796a2009-12-16 06:35:08 +0000843InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000844 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000845 bool VerifyOnly,
846 bool TreatUnavailableAsInvalid)
847 : SemaRef(S), VerifyOnly(VerifyOnly),
848 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000849 // FIXME: Check that IL isn't already the semantic form of some other
850 // InitListExpr. If it is, we'd create a broken AST.
851
Steve Narofff8ecff22008-05-01 22:18:59 +0000852 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000853
Richard Smith4e0d2e42013-09-20 20:10:22 +0000854 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000855 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000856 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000857 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000858
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000859 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000860 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000861 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
862 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000863 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000864 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000865 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000866 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000867}
868
869int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000870 // FIXME: use a proper constant
871 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000872 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000873 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000874 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
875 }
876 return maxElements;
877}
878
879int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000880 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000881 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000882 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
883 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000884 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000885 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000886 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000887
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000888 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000889 return std::min(InitializableMembers, 1);
890 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000891}
892
Richard Smith283e2072017-10-03 20:36:00 +0000893/// Determine whether Entity is an entity for which it is idiomatic to elide
894/// the braces in aggregate initialization.
895static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
896 // Recursive initialization of the one and only field within an aggregate
897 // class is considered idiomatic. This case arises in particular for
898 // initialization of std::array, where the C++ standard suggests the idiom of
899 //
900 // std::array<T, N> arr = {1, 2, 3};
901 //
902 // (where std::array is an aggregate struct containing a single array field.
903
904 // FIXME: Should aggregate initialization of a struct with a single
905 // base class and no members also suppress the warning?
906 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
907 return false;
908
909 auto *ParentRD =
910 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
911 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
912 if (CXXRD->getNumBases())
913 return false;
914
915 auto FieldIt = ParentRD->field_begin();
916 assert(FieldIt != ParentRD->field_end() &&
917 "no fields but have initializer for member?");
918 return ++FieldIt == ParentRD->field_end();
919}
920
Richard Smith4e0d2e42013-09-20 20:10:22 +0000921/// Check whether the range of the initializer \p ParentIList from element
922/// \p Index onwards can be used to initialize an object of type \p T. Update
923/// \p Index to indicate how many elements of the list were consumed.
924///
925/// This also fills in \p StructuredList, from element \p StructuredIndex
926/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000927void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000928 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000929 QualType T, unsigned &Index,
930 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000931 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000932 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000933
Steve Narofff8ecff22008-05-01 22:18:59 +0000934 if (T->isArrayType())
935 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000936 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000937 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000938 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000939 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000940 else
David Blaikie83d382b2011-09-23 05:06:16 +0000941 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000942
Eli Friedmane0f832b2008-05-25 13:49:22 +0000943 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000944 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000945 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000946 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000947 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000948 hadError = true;
949 return;
950 }
951
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000952 // Build a structured initializer list corresponding to this subobject.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000953 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
954 ParentIList, Index, T, StructuredList, StructuredIndex,
955 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
956 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000957 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000958
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000959 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000960 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000962 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000963 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000964 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000965
Richard Smithde229232013-06-06 11:41:05 +0000966 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000967 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000968
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000969 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000970 // Update the structured sub-object initializer so that it's ending
971 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000972 if (EndIndex < ParentIList->getNumInits() &&
973 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000974 SourceLocation EndLoc
975 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
976 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
977 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000978
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000979 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000980 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000981 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
982 !isIdiomaticBraceElisionEntity(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000983 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
Richard Smithde229232013-06-06 11:41:05 +0000984 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000985 << StructuredSubobjectInitList->getSourceRange()
986 << FixItHint::CreateInsertion(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000987 StructuredSubobjectInitList->getBeginLoc(), "{")
Alp Tokerb6cc5922014-05-03 03:45:55 +0000988 << FixItHint::CreateInsertion(
989 SemaRef.getLocForEndOfToken(
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000990 StructuredSubobjectInitList->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +0000991 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000992 }
Richard Smith79c88c32018-09-26 19:00:16 +0000993
994 // Warn if this type won't be an aggregate in future versions of C++.
995 auto *CXXRD = T->getAsCXXRecordDecl();
996 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
997 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
998 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
999 << StructuredSubobjectInitList->getSourceRange() << T;
1000 }
Tanya Lattner5029d562010-03-07 04:17:15 +00001001 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001002}
1003
Richard Smith420fa122015-02-12 01:50:05 +00001004/// Warn that \p Entity was of scalar type and was initialized by a
1005/// single-element braced initializer list.
1006static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1007 SourceRange Braces) {
1008 // Don't warn during template instantiation. If the initialization was
1009 // non-dependent, we warned during the initial parse; otherwise, the
1010 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +00001011 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +00001012 return;
1013
1014 unsigned DiagID = 0;
1015
1016 switch (Entity.getKind()) {
1017 case InitializedEntity::EK_VectorElement:
1018 case InitializedEntity::EK_ComplexElement:
1019 case InitializedEntity::EK_ArrayElement:
1020 case InitializedEntity::EK_Parameter:
1021 case InitializedEntity::EK_Parameter_CF_Audited:
1022 case InitializedEntity::EK_Result:
1023 // Extra braces here are suspicious.
1024 DiagID = diag::warn_braces_around_scalar_init;
1025 break;
1026
1027 case InitializedEntity::EK_Member:
1028 // Warn on aggregate initialization but not on ctor init list or
1029 // default member initializer.
1030 if (Entity.getParent())
1031 DiagID = diag::warn_braces_around_scalar_init;
1032 break;
1033
1034 case InitializedEntity::EK_Variable:
1035 case InitializedEntity::EK_LambdaCapture:
1036 // No warning, might be direct-list-initialization.
1037 // FIXME: Should we warn for copy-list-initialization in these cases?
1038 break;
1039
1040 case InitializedEntity::EK_New:
1041 case InitializedEntity::EK_Temporary:
1042 case InitializedEntity::EK_CompoundLiteralInit:
1043 // No warning, braces are part of the syntax of the underlying construct.
1044 break;
1045
1046 case InitializedEntity::EK_RelatedResult:
1047 // No warning, we already warned when initializing the result.
1048 break;
1049
1050 case InitializedEntity::EK_Exception:
1051 case InitializedEntity::EK_Base:
1052 case InitializedEntity::EK_Delegating:
1053 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001054 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001055 case InitializedEntity::EK_Binding:
Richard Smith67af95b2018-07-23 19:19:08 +00001056 case InitializedEntity::EK_StmtExprResult:
Richard Smith420fa122015-02-12 01:50:05 +00001057 llvm_unreachable("unexpected braced scalar init");
1058 }
1059
1060 if (DiagID) {
1061 S.Diag(Braces.getBegin(), DiagID)
1062 << Braces
1063 << FixItHint::CreateRemoval(Braces.getBegin())
1064 << FixItHint::CreateRemoval(Braces.getEnd());
1065 }
1066}
1067
Richard Smith4e0d2e42013-09-20 20:10:22 +00001068/// Check whether the initializer \p IList (that was written with explicit
1069/// braces) can be used to initialize an object of type \p T.
1070///
1071/// This also fills in \p StructuredList with the fully-braced, desugared
1072/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001073void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001074 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001075 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001076 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001077 if (!VerifyOnly) {
1078 SyntacticToSemantic[IList] = StructuredList;
1079 StructuredList->setSyntacticForm(IList);
1080 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001081
1082 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001084 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001085 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001086 QualType ExprTy = T;
1087 if (!ExprTy->isArrayType())
1088 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001089 IList->setType(ExprTy);
1090 StructuredList->setType(ExprTy);
1091 }
Eli Friedman85f54972008-05-25 13:22:35 +00001092 if (hadError)
1093 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001094
Eli Friedman85f54972008-05-25 13:22:35 +00001095 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001096 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001097 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001098 if (SemaRef.getLangOpts().CPlusPlus ||
1099 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001100 IList->getType()->isVectorType())) {
1101 hadError = true;
1102 }
1103 return;
1104 }
1105
Eli Friedmanbd327452009-05-29 20:20:05 +00001106 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001107 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1108 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001109 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001110 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001111 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001112 hadError = true;
1113 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001114 // Special-case
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001115 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1116 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001117 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001118 // Don't complain for incomplete types, since we'll get an error
1119 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001120 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001121 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001122 CurrentObjectType->isArrayType()? 0 :
1123 CurrentObjectType->isVectorType()? 1 :
1124 CurrentObjectType->isScalarType()? 2 :
1125 CurrentObjectType->isUnionType()? 3 :
1126 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001127
Richard Smith1b98ccc2014-07-19 01:39:17 +00001128 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001129 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001130 DK = diag::err_excess_initializers;
1131 hadError = true;
1132 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001133 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001134 DK = diag::err_excess_initializers;
1135 hadError = true;
1136 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001137
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001138 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1139 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001140 }
1141 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001142
Richard Smith79c88c32018-09-26 19:00:16 +00001143 if (!VerifyOnly) {
1144 if (T->isScalarType() && IList->getNumInits() == 1 &&
1145 !isa<InitListExpr>(IList->getInit(0)))
1146 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1147
1148 // Warn if this is a class type that won't be an aggregate in future
1149 // versions of C++.
1150 auto *CXXRD = T->getAsCXXRecordDecl();
1151 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1152 // Don't warn if there's an equivalent default constructor that would be
1153 // used instead.
1154 bool HasEquivCtor = false;
1155 if (IList->getNumInits() == 0) {
1156 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1157 HasEquivCtor = CD && !CD->isDeleted();
1158 }
1159
1160 if (!HasEquivCtor) {
1161 SemaRef.Diag(IList->getBeginLoc(),
1162 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1163 << IList->getSourceRange() << T;
1164 }
1165 }
1166 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001167}
1168
Anders Carlsson6cabf312010-01-23 23:23:01 +00001169void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001170 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001171 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001172 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001173 unsigned &Index,
1174 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001175 unsigned &StructuredIndex,
1176 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001177 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1178 // Explicitly braced initializer for complex type can be real+imaginary
1179 // parts.
1180 CheckComplexType(Entity, IList, DeclType, Index,
1181 StructuredList, StructuredIndex);
1182 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001183 CheckScalarType(Entity, IList, DeclType, Index,
1184 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001185 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001187 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001188 } else if (DeclType->isRecordType()) {
1189 assert(DeclType->isAggregateType() &&
1190 "non-aggregate records should be handed in CheckSubElementType");
1191 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001192 auto Bases =
1193 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1194 CXXRecordDecl::base_class_iterator());
1195 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1196 Bases = CXXRD->bases();
1197 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1198 SubobjectIsDesignatorContext, Index, StructuredList,
1199 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001200 } else if (DeclType->isArrayType()) {
1201 llvm::APSInt Zero(
1202 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1203 false);
1204 CheckArrayType(Entity, IList, DeclType, Zero,
1205 SubobjectIsDesignatorContext, Index,
1206 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001207 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1208 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001209 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001210 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001211 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1212 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001213 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001214 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001215 CheckReferenceType(Entity, IList, DeclType, Index,
1216 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001217 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001218 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001219 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001220 hadError = true;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001221 } else if (DeclType->isOCLIntelSubgroupAVCType()) {
1222 // Checks for scalar type are sufficient for these types too.
1223 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1224 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001225 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001226 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001227 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1228 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001229 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001230 }
1231}
1232
Anders Carlsson6cabf312010-01-23 23:23:01 +00001233void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001234 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001235 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001236 unsigned &Index,
1237 InitListExpr *StructuredList,
1238 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001239 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001240
1241 if (ElemType->isReferenceType())
1242 return CheckReferenceType(Entity, IList, ElemType, Index,
1243 StructuredList, StructuredIndex);
1244
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001245 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001246 if (SubInitList->getNumInits() == 1 &&
1247 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1248 SIF_None) {
1249 expr = SubInitList->getInit(0);
1250 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001251 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001252 = getStructuredSubobjectInit(IList, Index, ElemType,
1253 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001254 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001255 CheckExplicitInitList(Entity, SubInitList, ElemType,
1256 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001257
1258 if (!hadError && !VerifyOnly) {
1259 bool RequiresSecondPass = false;
1260 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001261 RequiresSecondPass, StructuredList,
1262 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001263 if (RequiresSecondPass && !hadError)
1264 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001265 RequiresSecondPass, StructuredList,
1266 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001267 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001268 ++StructuredIndex;
1269 ++Index;
1270 return;
1271 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001272 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001273 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001274 // This happens during template instantiation when we see an InitListExpr
1275 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001276 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001277 "found implicit initialization for the wrong type");
1278 if (!VerifyOnly)
1279 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1280 ++Index;
1281 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001282 }
1283
Richard Smith3c567fc2015-02-12 01:55:09 +00001284 if (SemaRef.getLangOpts().CPlusPlus) {
1285 // C++ [dcl.init.aggr]p2:
1286 // Each member is copy-initialized from the corresponding
1287 // initializer-clause.
1288
1289 // FIXME: Better EqualLoc?
1290 InitializationKind Kind =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001291 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
Anastasia Stulova8d99a5c02019-08-02 11:19:35 +00001292
1293 // Vector elements can be initialized from other vectors in which case
1294 // we need initialization entity with a type of a vector (and not a vector
1295 // element!) initializing multiple vector elements.
1296 auto TmpEntity =
1297 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1298 ? InitializedEntity::InitializeTemporary(ElemType)
1299 : Entity;
1300
1301 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
Richard Smith3c567fc2015-02-12 01:55:09 +00001302 /*TopLevelOfInitList*/ true);
1303
1304 // C++14 [dcl.init.aggr]p13:
1305 // If the assignment-expression can initialize a member, the member is
1306 // initialized. Otherwise [...] brace elision is assumed
1307 //
1308 // Brace elision is never performed if the element is not an
1309 // assignment-expression.
1310 if (Seq || isa<InitListExpr>(expr)) {
1311 if (!VerifyOnly) {
Anastasia Stulova8d99a5c02019-08-02 11:19:35 +00001312 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
Richard Smith3c567fc2015-02-12 01:55:09 +00001313 if (Result.isInvalid())
1314 hadError = true;
1315
1316 UpdateStructuredListElement(StructuredList, StructuredIndex,
1317 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001318 } else if (!Seq)
1319 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001320 ++Index;
1321 return;
1322 }
1323
1324 // Fall through for subaggregate initialization
1325 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1326 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001327 return CheckScalarType(Entity, IList, ElemType, Index,
1328 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001329 } else if (const ArrayType *arrayType =
1330 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001331 // arrayType can be incomplete if we're initializing a flexible
1332 // array member. There's nothing we can do with the completed
1333 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001335 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001336 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001337 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1338 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001339 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001340 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001341 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001342 }
John McCall5decec92011-02-21 07:57:55 +00001343
1344 // Fall through for subaggregate initialization.
1345
John McCall5decec92011-02-21 07:57:55 +00001346 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001347 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001348 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001349
John McCall5decec92011-02-21 07:57:55 +00001350 // C99 6.7.8p13:
1351 //
1352 // The initializer for a structure or union object that has
1353 // automatic storage duration shall be either an initializer
1354 // list as described below, or a single expression that has
1355 // compatible structure or union type. In the latter case, the
1356 // initial value of the object, including unnamed members, is
1357 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001358 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001359 if (SemaRef.CheckSingleAssignmentConstraints(
1360 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001361 if (ExprRes.isInvalid())
1362 hadError = true;
1363 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001364 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001365 if (ExprRes.isInvalid())
1366 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001367 }
1368 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001369 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001370 ++Index;
1371 return;
1372 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001373 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001374 // Fall through for subaggregate initialization
1375 }
1376
1377 // C++ [dcl.init.aggr]p12:
1378 //
1379 // [...] Otherwise, if the member is itself a non-empty
1380 // subaggregate, brace elision is assumed and the initializer is
1381 // considered for the initialization of the first member of
1382 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001383 // OpenCL vector initializer is handled elsewhere.
1384 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1385 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001386 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1387 StructuredIndex);
1388 ++StructuredIndex;
1389 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001390 if (!VerifyOnly) {
1391 // We cannot initialize this element, so let
1392 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001393 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001394 /*TopLevelOfInitList=*/true);
1395 }
John McCall5decec92011-02-21 07:57:55 +00001396 hadError = true;
1397 ++Index;
1398 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001399 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001400}
1401
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001402void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1403 InitListExpr *IList, QualType DeclType,
1404 unsigned &Index,
1405 InitListExpr *StructuredList,
1406 unsigned &StructuredIndex) {
1407 assert(Index == 0 && "Index in explicit init list must be zero");
1408
1409 // As an extension, clang supports complex initializers, which initialize
1410 // a complex number component-wise. When an explicit initializer list for
1411 // a complex number contains two two initializers, this extension kicks in:
1412 // it exepcts the initializer list to contain two elements convertible to
1413 // the element type of the complex type. The first element initializes
1414 // the real part, and the second element intitializes the imaginary part.
1415
1416 if (IList->getNumInits() != 2)
1417 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1418 StructuredIndex);
1419
1420 // This is an extension in C. (The builtin _Complex type does not exist
1421 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001422 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001423 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1424 << IList->getSourceRange();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001425
1426 // Initialize the complex number.
1427 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1428 InitializedEntity ElementEntity =
1429 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1430
1431 for (unsigned i = 0; i < 2; ++i) {
1432 ElementEntity.setElementIndex(Index);
1433 CheckSubElementType(ElementEntity, IList, elementType, Index,
1434 StructuredList, StructuredIndex);
1435 }
1436}
1437
Anders Carlsson6cabf312010-01-23 23:23:01 +00001438void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001439 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001440 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001441 InitListExpr *StructuredList,
1442 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001443 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001444 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001445 SemaRef.Diag(IList->getBeginLoc(),
1446 SemaRef.getLangOpts().CPlusPlus11
1447 ? diag::warn_cxx98_compat_empty_scalar_initializer
1448 : diag::err_empty_scalar_initializer)
1449 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001450 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001451 ++Index;
1452 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001453 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001454 }
John McCall643169b2010-11-11 00:46:36 +00001455
1456 Expr *expr = IList->getInit(Index);
1457 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001458 // FIXME: This is invalid, and accepting it causes overload resolution
1459 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001460 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001461 SemaRef.Diag(SubIList->getBeginLoc(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001462 diag::ext_many_braces_around_scalar_init)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001463 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001464
1465 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1466 StructuredIndex);
1467 return;
1468 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001469 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001470 SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
1471 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001472 hadError = true;
1473 ++Index;
1474 ++StructuredIndex;
1475 return;
1476 }
1477
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001478 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001479 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001480 hadError = true;
1481 ++Index;
1482 return;
1483 }
1484
John McCall643169b2010-11-11 00:46:36 +00001485 ExprResult Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001486 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1487 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001488
Craig Topperc3ec1492014-05-26 06:22:03 +00001489 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001490
1491 if (Result.isInvalid())
1492 hadError = true; // types weren't compatible.
1493 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001494 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
John McCall643169b2010-11-11 00:46:36 +00001496 if (ResultExpr != expr) {
1497 // The type was promoted, update initializer list.
1498 IList->setInit(Index, ResultExpr);
1499 }
1500 }
1501 if (hadError)
1502 ++StructuredIndex;
1503 else
1504 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1505 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001506}
1507
Anders Carlsson6cabf312010-01-23 23:23:01 +00001508void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1509 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001510 unsigned &Index,
1511 InitListExpr *StructuredList,
1512 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001513 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001514 // FIXME: It would be wonderful if we could point at the actual member. In
1515 // general, it would be useful to pass location information down the stack,
1516 // so that we know the location (or decl) of the "current object" being
1517 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001518 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001519 SemaRef.Diag(IList->getBeginLoc(),
1520 diag::err_init_reference_member_uninitialized)
1521 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001522 hadError = true;
1523 ++Index;
1524 ++StructuredIndex;
1525 return;
1526 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001527
1528 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001529 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001530 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001531 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1532 << DeclType << IList->getSourceRange();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001533 hadError = true;
1534 ++Index;
1535 ++StructuredIndex;
1536 return;
1537 }
1538
1539 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001540 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001541 hadError = true;
1542 ++Index;
1543 return;
1544 }
1545
1546 ExprResult Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001547 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001548 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001549
1550 if (Result.isInvalid())
1551 hadError = true;
1552
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001553 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001554 IList->setInit(Index, expr);
1555
1556 if (hadError)
1557 ++StructuredIndex;
1558 else
1559 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1560 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001561}
1562
Anders Carlsson6cabf312010-01-23 23:23:01 +00001563void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001564 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001565 unsigned &Index,
1566 InitListExpr *StructuredList,
1567 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001568 const VectorType *VT = DeclType->getAs<VectorType>();
1569 unsigned maxElements = VT->getNumElements();
1570 unsigned numEltsInit = 0;
1571 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001572
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001573 if (Index >= IList->getNumInits()) {
1574 // Make sure the element type can be value-initialized.
1575 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001576 CheckEmptyInitializable(
1577 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001578 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001579 return;
1580 }
1581
David Blaikiebbafb8a2012-03-11 07:00:24 +00001582 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001583 // If the initializing element is a vector, try to copy-initialize
1584 // instead of breaking it apart (which is doomed to failure anyway).
1585 Expr *Init = IList->getInit(Index);
1586 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001587 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001588 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001589 hadError = true;
1590 ++Index;
1591 return;
1592 }
1593
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001594 ExprResult Result =
1595 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1596 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001597
Craig Topperc3ec1492014-05-26 06:22:03 +00001598 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001599 if (Result.isInvalid())
1600 hadError = true; // types weren't compatible.
1601 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001602 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001603
John McCall6a16b2f2010-10-30 00:11:39 +00001604 if (ResultExpr != Init) {
1605 // The type was promoted, update initializer list.
1606 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001607 }
1608 }
John McCall6a16b2f2010-10-30 00:11:39 +00001609 if (hadError)
1610 ++StructuredIndex;
1611 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001612 UpdateStructuredListElement(StructuredList, StructuredIndex,
1613 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001614 ++Index;
1615 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001616 }
Mike Stump11289f42009-09-09 15:08:12 +00001617
John McCall6a16b2f2010-10-30 00:11:39 +00001618 InitializedEntity ElementEntity =
1619 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001620
John McCall6a16b2f2010-10-30 00:11:39 +00001621 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1622 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001623 if (Index >= IList->getNumInits()) {
1624 if (VerifyOnly)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001625 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
John McCall6a16b2f2010-10-30 00:11:39 +00001626 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001628
John McCall6a16b2f2010-10-30 00:11:39 +00001629 ElementEntity.setElementIndex(Index);
1630 CheckSubElementType(ElementEntity, IList, elementType, Index,
1631 StructuredList, StructuredIndex);
1632 }
James Molloy9eef2652014-06-20 14:35:13 +00001633
1634 if (VerifyOnly)
1635 return;
1636
1637 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1638 const VectorType *T = Entity.getType()->getAs<VectorType>();
1639 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1640 T->getVectorKind() == VectorType::NeonPolyVector)) {
1641 // The ability to use vector initializer lists is a GNU vector extension
1642 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
Fangrui Song6907ce22018-07-30 19:24:48 +00001643 // endian machines it works fine, however on big endian machines it
James Molloy9eef2652014-06-20 14:35:13 +00001644 // exhibits surprising behaviour:
1645 //
1646 // uint32x2_t x = {42, 64};
1647 // return vget_lane_u32(x, 0); // Will return 64.
1648 //
1649 // Because of this, explicitly call out that it is non-portable.
1650 //
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001651 SemaRef.Diag(IList->getBeginLoc(),
James Molloy9eef2652014-06-20 14:35:13 +00001652 diag::warn_neon_vector_initializer_non_portable);
1653
1654 const char *typeCode;
1655 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1656
1657 if (elementType->isFloatingType())
1658 typeCode = "f";
1659 else if (elementType->isSignedIntegerType())
1660 typeCode = "s";
1661 else if (elementType->isUnsignedIntegerType())
1662 typeCode = "u";
1663 else
1664 llvm_unreachable("Invalid element type!");
1665
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001666 SemaRef.Diag(IList->getBeginLoc(),
1667 SemaRef.Context.getTypeSize(VT) > 64
1668 ? diag::note_neon_vector_initializer_non_portable_q
1669 : diag::note_neon_vector_initializer_non_portable)
1670 << typeCode << typeSize;
James Molloy9eef2652014-06-20 14:35:13 +00001671 }
1672
John McCall6a16b2f2010-10-30 00:11:39 +00001673 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001674 }
John McCall6a16b2f2010-10-30 00:11:39 +00001675
1676 InitializedEntity ElementEntity =
1677 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678
John McCall6a16b2f2010-10-30 00:11:39 +00001679 // OpenCL initializers allows vectors to be constructed from vectors.
1680 for (unsigned i = 0; i < maxElements; ++i) {
1681 // Don't attempt to go past the end of the init list
1682 if (Index >= IList->getNumInits())
1683 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001684
John McCall6a16b2f2010-10-30 00:11:39 +00001685 ElementEntity.setElementIndex(Index);
1686
1687 QualType IType = IList->getInit(Index)->getType();
1688 if (!IType->isVectorType()) {
1689 CheckSubElementType(ElementEntity, IList, elementType, Index,
1690 StructuredList, StructuredIndex);
1691 ++numEltsInit;
1692 } else {
1693 QualType VecType;
1694 const VectorType *IVT = IType->getAs<VectorType>();
1695 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001696
John McCall6a16b2f2010-10-30 00:11:39 +00001697 if (IType->isExtVectorType())
1698 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1699 else
1700 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001701 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001702 CheckSubElementType(ElementEntity, IList, VecType, Index,
1703 StructuredList, StructuredIndex);
1704 numEltsInit += numIElts;
1705 }
1706 }
1707
1708 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001709 if (numEltsInit != maxElements) {
1710 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001711 SemaRef.Diag(IList->getBeginLoc(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001712 diag::err_vector_incorrect_num_initializers)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001713 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001714 hadError = true;
1715 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001716}
1717
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00001718/// Check if the type of a class element has an accessible destructor, and marks
1719/// it referenced. Returns true if we shouldn't form a reference to the
1720/// destructor.
1721///
1722/// Aggregate initialization requires a class element's destructor be
1723/// accessible per 11.6.1 [dcl.init.aggr]:
1724///
1725/// The destructor for each element of class type is potentially invoked
1726/// (15.4 [class.dtor]) from the context where the aggregate initialization
1727/// occurs.
1728static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1729 Sema &SemaRef) {
1730 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1731 if (!CXXRD)
1732 return false;
1733
1734 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1735 SemaRef.CheckDestructorAccess(Loc, Destructor,
1736 SemaRef.PDiag(diag::err_access_dtor_temp)
1737 << ElementType);
1738 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1739 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1740}
1741
Anders Carlsson6cabf312010-01-23 23:23:01 +00001742void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001743 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001744 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001745 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001746 unsigned &Index,
1747 InitListExpr *StructuredList,
1748 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001749 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1750
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00001751 if (!VerifyOnly) {
1752 if (checkDestructorReference(arrayType->getElementType(),
1753 IList->getEndLoc(), SemaRef)) {
1754 hadError = true;
1755 return;
1756 }
1757 }
1758
Steve Narofff8ecff22008-05-01 22:18:59 +00001759 // Check for the special-case of initializing an array with a string.
1760 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001761 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1762 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001763 // We place the string literal directly into the resulting
1764 // initializer list. This is the only place where the structure
1765 // of the structured initializer list doesn't match exactly,
1766 // because doing so would involve allocating one character
1767 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001768 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001769 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1770 UpdateStructuredListElement(StructuredList, StructuredIndex,
1771 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001772 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1773 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001774 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001775 return;
1776 }
1777 }
John McCall66884dd2011-02-21 07:22:22 +00001778 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001779 // Check for VLAs; in standard C it would be possible to check this
1780 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1781 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001782 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001783 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1784 diag::err_variable_object_no_init)
1785 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001786 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001787 ++Index;
1788 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001789 return;
1790 }
1791
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001792 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001793 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1794 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001795 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001796 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001797 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001798 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001799 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001800 maxElementsKnown = true;
1801 }
1802
John McCall66884dd2011-02-21 07:22:22 +00001803 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001804 while (Index < IList->getNumInits()) {
1805 Expr *Init = IList->getInit(Index);
1806 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001807 // If we're not the subobject that matches up with the '{' for
1808 // the designator, we shouldn't be handling the
1809 // designator. Return immediately.
1810 if (!SubobjectIsDesignatorContext)
1811 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001812
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001813 // Handle this designated initializer. elementIndex will be
1814 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001815 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001816 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001817 StructuredList, StructuredIndex, true,
1818 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001819 hadError = true;
1820 continue;
1821 }
1822
Douglas Gregor033d1252009-01-23 16:54:12 +00001823 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001824 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001825 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001826 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001827 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001828
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001829 // If the array is of incomplete type, keep track of the number of
1830 // elements in the initializer.
1831 if (!maxElementsKnown && elementIndex > maxElements)
1832 maxElements = elementIndex;
1833
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001834 continue;
1835 }
1836
1837 // If we know the maximum number of elements, and we've already
1838 // hit it, stop consuming elements in the initializer list.
1839 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001840 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001841
Anders Carlsson6cabf312010-01-23 23:23:01 +00001842 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001843 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001844 Entity);
1845 // Check this element.
1846 CheckSubElementType(ElementEntity, IList, elementType, Index,
1847 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001848 ++elementIndex;
1849
1850 // If the array is of incomplete type, keep track of the number of
1851 // elements in the initializer.
1852 if (!maxElementsKnown && elementIndex > maxElements)
1853 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001854 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001855 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001856 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001857 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001858 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001859 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001860 // Sizing an array implicitly to zero is not allowed by ISO C,
1861 // but is supported by GNU.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001862 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001863 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001864
Mike Stump11289f42009-09-09 15:08:12 +00001865 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001866 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001867 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001868 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001869 // If there are any members of the array that get value-initialized, check
1870 // that is possible. That happens if we know the bound and don't have
1871 // enough elements, or if we're performing an array new with an unknown
1872 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001873 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001874 if ((maxElementsKnown && elementIndex < maxElements) ||
1875 Entity.isVariableLengthArrayNew())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001876 CheckEmptyInitializable(
1877 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1878 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001879 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001880}
1881
Eli Friedman3fa64df2011-08-23 22:24:57 +00001882bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1883 Expr *InitExpr,
1884 FieldDecl *Field,
1885 bool TopLevelObject) {
1886 // Handle GNU flexible array initializers.
1887 unsigned FlexArrayDiag;
1888 if (isa<InitListExpr>(InitExpr) &&
1889 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1890 // Empty flexible array init always allowed as an extension
1891 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001892 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001893 // Disallow flexible array init in C++; it is not required for gcc
1894 // compatibility, and it needs work to IRGen correctly in general.
1895 FlexArrayDiag = diag::err_flexible_array_init;
1896 } else if (!TopLevelObject) {
1897 // Disallow flexible array init on non-top-level object
1898 FlexArrayDiag = diag::err_flexible_array_init;
1899 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1900 // Disallow flexible array init on anything which is not a variable.
1901 FlexArrayDiag = diag::err_flexible_array_init;
1902 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1903 // Disallow flexible array init on local variables.
1904 FlexArrayDiag = diag::err_flexible_array_init;
1905 } else {
1906 // Allow other cases.
1907 FlexArrayDiag = diag::ext_flexible_array_init;
1908 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001909
1910 if (!VerifyOnly) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001911 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
1912 << InitExpr->getBeginLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001913 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1914 << Field;
1915 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001916
1917 return FlexArrayDiag != diag::ext_flexible_array_init;
1918}
1919
Richard Smith872307e2016-03-08 22:17:41 +00001920void InitListChecker::CheckStructUnionTypes(
1921 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1922 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1923 bool SubobjectIsDesignatorContext, unsigned &Index,
1924 InitListExpr *StructuredList, unsigned &StructuredIndex,
1925 bool TopLevelObject) {
1926 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001927
Eli Friedman23a9e312008-05-19 19:16:24 +00001928 // If the record is invalid, some of it's members are invalid. To avoid
1929 // confusion, we forgo checking the intializer for the entire record.
1930 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001931 // Assume it was supposed to consume a single initializer.
1932 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001933 hadError = true;
1934 return;
Mike Stump11289f42009-09-09 15:08:12 +00001935 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001936
1937 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001938 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001939
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001940 if (!VerifyOnly)
1941 for (FieldDecl *FD : RD->fields()) {
1942 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00001943 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001944 hadError = true;
1945 return;
1946 }
1947 }
1948
Richard Smith852c9db2013-04-20 22:23:05 +00001949 // If there's a default initializer, use it.
1950 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1951 if (VerifyOnly)
1952 return;
1953 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1954 Field != FieldEnd; ++Field) {
1955 if (Field->hasInClassInitializer()) {
1956 StructuredList->setInitializedFieldInUnion(*Field);
1957 // FIXME: Actually build a CXXDefaultInitExpr?
1958 return;
1959 }
1960 }
1961 }
1962
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001963 // Value-initialize the first member of the union that isn't an unnamed
1964 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001965 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1966 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001967 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001968 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001969 CheckEmptyInitializable(
1970 InitializedEntity::InitializeMember(*Field, &Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001971 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001972 else
David Blaikie40ed2972012-06-06 20:45:41 +00001973 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001974 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001975 }
1976 }
1977 return;
1978 }
1979
Richard Smith872307e2016-03-08 22:17:41 +00001980 bool InitializedSomething = false;
1981
1982 // If we have any base classes, they are initialized prior to the fields.
1983 for (auto &Base : Bases) {
1984 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
Richard Smith872307e2016-03-08 22:17:41 +00001985
1986 // Designated inits always initialize fields, so if we see one, all
1987 // remaining base classes have no explicit initializer.
1988 if (Init && isa<DesignatedInitExpr>(Init))
1989 Init = nullptr;
1990
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001991 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
Richard Smith872307e2016-03-08 22:17:41 +00001992 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1993 SemaRef.Context, &Base, false, &Entity);
1994 if (Init) {
1995 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1996 StructuredList, StructuredIndex);
1997 InitializedSomething = true;
1998 } else if (VerifyOnly) {
1999 CheckEmptyInitializable(BaseEntity, InitLoc);
2000 }
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002001
2002 if (!VerifyOnly)
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00002003 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002004 hadError = true;
2005 return;
2006 }
Richard Smith872307e2016-03-08 22:17:41 +00002007 }
2008
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002009 // If structDecl is a forward declaration, this loop won't do
2010 // anything except look at designated initializers; That's okay,
2011 // because an error should get printed out elsewhere. It might be
2012 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002013 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002014 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002015 bool CheckForMissingFields =
2016 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002017 bool HasDesignatedInit = false;
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002018
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002019 while (Index < IList->getNumInits()) {
2020 Expr *Init = IList->getInit(Index);
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002021 SourceLocation InitLoc = Init->getBeginLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002022
2023 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002024 // If we're not the subobject that matches up with the '{' for
2025 // the designator, we shouldn't be handling the
2026 // designator. Return immediately.
2027 if (!SubobjectIsDesignatorContext)
2028 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002029
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002030 HasDesignatedInit = true;
2031
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002032 // Handle this designated initializer. Field will be updated to
2033 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002034 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00002035 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002036 StructuredList, StructuredIndex,
2037 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002038 hadError = true;
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002039 else if (!VerifyOnly) {
2040 // Find the field named by the designated initializer.
2041 RecordDecl::field_iterator F = RD->field_begin();
2042 while (std::next(F) != Field)
2043 ++F;
2044 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00002045 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002046 hadError = true;
2047 return;
2048 }
2049 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002050
Douglas Gregora9add4e2009-02-12 19:00:39 +00002051 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00002052
2053 // Disable check for missing fields when designators are used.
2054 // This matches gcc behaviour.
2055 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002056 continue;
2057 }
2058
2059 if (Field == FieldEnd) {
2060 // We've run out of fields. We're done.
2061 break;
2062 }
2063
Douglas Gregora9add4e2009-02-12 19:00:39 +00002064 // We've already initialized a member of a union. We're done.
2065 if (InitializedSomething && DeclType->isUnionType())
2066 break;
2067
Douglas Gregor91f84212008-12-11 16:49:14 +00002068 // If we've hit the flexible array member at the end, we're done.
2069 if (Field->getType()->isIncompleteArrayType())
2070 break;
2071
Douglas Gregor51695702009-01-29 16:53:55 +00002072 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002073 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002074 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00002075 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00002076 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002077
Douglas Gregora82064c2011-06-29 21:51:31 +00002078 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002079 bool InvalidUse;
2080 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002081 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002082 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002083 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2084 *Field, IList->getInit(Index)->getBeginLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002085 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002086 ++Index;
2087 ++Field;
2088 hadError = true;
2089 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002090 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002091
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002092 if (!VerifyOnly) {
2093 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00002094 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002095 hadError = true;
2096 return;
2097 }
2098 }
2099
Anders Carlsson6cabf312010-01-23 23:23:01 +00002100 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002101 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002102 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2103 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00002104 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00002105
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002106 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00002107 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00002108 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00002109 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002110
2111 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00002112 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002113
John McCalle40b58e2010-03-11 19:32:38 +00002114 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002115 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2116 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2117 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00002118 // It is possible we have one or more unnamed bitfields remaining.
2119 // Find first (if any) named field and emit warning.
2120 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2121 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00002122 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00002123 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00002124 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00002125 break;
2126 }
2127 }
2128 }
2129
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002130 // Check that any remaining fields can be value-initialized.
2131 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2132 !Field->getType()->isIncompleteArrayType()) {
2133 // FIXME: Should check for holes left by designated initializers too.
2134 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00002135 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00002136 CheckEmptyInitializable(
2137 InitializedEntity::InitializeMember(*Field, &Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002138 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002139 }
2140 }
2141
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002142 // Check that the types of the remaining fields have accessible destructors.
2143 if (!VerifyOnly) {
2144 // If the initializer expression has a designated initializer, check the
2145 // elements for which a designated initializer is not provided too.
2146 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2147 : Field;
2148 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2149 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00002150 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002151 hadError = true;
2152 return;
2153 }
2154 }
2155 }
2156
Mike Stump11289f42009-09-09 15:08:12 +00002157 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002158 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002159 return;
2160
David Blaikie40ed2972012-06-06 20:45:41 +00002161 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002162 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002163 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002164 ++Index;
2165 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002166 }
2167
Anders Carlsson6cabf312010-01-23 23:23:01 +00002168 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002169 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002170
Anders Carlsson6cabf312010-01-23 23:23:01 +00002171 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002172 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002173 StructuredList, StructuredIndex);
2174 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002176 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002177}
Steve Narofff8ecff22008-05-01 22:18:59 +00002178
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002179/// Expand a field designator that refers to a member of an
Douglas Gregord5846a12009-04-15 06:41:24 +00002180/// anonymous struct or union into a series of field designators that
2181/// refers to the field within the appropriate subobject.
2182///
Douglas Gregord5846a12009-04-15 06:41:24 +00002183static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002184 DesignatedInitExpr *DIE,
2185 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002186 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002187 typedef DesignatedInitExpr::Designator Designator;
2188
Douglas Gregord5846a12009-04-15 06:41:24 +00002189 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002190 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002191 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2192 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2193 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002194 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002195 DIE->getDesignator(DesigIdx)->getDotLoc(),
2196 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2197 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002198 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2199 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002200 assert(isa<FieldDecl>(*PI));
2201 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002202 }
2203
2204 // Expand the current designator into the set of replacement
2205 // designators, so we have a full subobject path down to where the
2206 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002207 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002208 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002209}
Mike Stump11289f42009-09-09 15:08:12 +00002210
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002211static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2212 DesignatedInitExpr *DIE) {
2213 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2214 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2215 for (unsigned I = 0; I < NumIndexExprs; ++I)
2216 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002217 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2218 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002219 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002220 DIE->usesGNUSyntax(), DIE->getInit());
2221}
2222
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002223namespace {
2224
2225// Callback to only accept typo corrections that are for field members of
2226// the given struct or union.
Bruno Ricci70ad3962019-03-25 17:08:51 +00002227class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002228 public:
2229 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2230 : Record(RD) {}
2231
Craig Toppere14c0f82014-03-12 04:55:44 +00002232 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002233 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2234 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2235 }
2236
Bruno Ricci70ad3962019-03-25 17:08:51 +00002237 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2238 return llvm::make_unique<FieldInitializerValidatorCCC>(*this);
2239 }
2240
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002241 private:
2242 RecordDecl *Record;
2243};
2244
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002245} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002247/// Check the well-formedness of a C99 designated initializer.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002248///
2249/// Determines whether the designated initializer @p DIE, which
2250/// resides at the given @p Index within the initializer list @p
2251/// IList, is well-formed for a current object of type @p DeclType
2252/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002253/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002254/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002255///
2256/// @param IList The initializer list in which this designated
2257/// initializer occurs.
2258///
Douglas Gregora5324162009-04-15 04:56:10 +00002259/// @param DIE The designated initializer expression.
2260///
2261/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002262///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002263/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002264/// into which the designation in @p DIE should refer.
2265///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002266/// @param NextField If non-NULL and the first designator in @p DIE is
2267/// a field, this will be set to the field declaration corresponding
2268/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002269///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002270/// @param NextElementIndex If non-NULL and the first designator in @p
2271/// DIE is an array designator or GNU array-range designator, this
2272/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002273///
2274/// @param Index Index into @p IList where the designated initializer
2275/// @p DIE occurs.
2276///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002277/// @param StructuredList The initializer list expression that
2278/// describes all of the subobject initializers in the order they'll
2279/// actually be initialized.
2280///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002281/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002282bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002283InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002284 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002285 DesignatedInitExpr *DIE,
2286 unsigned DesigIdx,
2287 QualType &CurrentObjectType,
2288 RecordDecl::field_iterator *NextField,
2289 llvm::APSInt *NextElementIndex,
2290 unsigned &Index,
2291 InitListExpr *StructuredList,
2292 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002293 bool FinishSubobjectInit,
2294 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002295 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002296 // Check the actual initialization for the designated object type.
2297 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002298
2299 // Temporarily remove the designator expression from the
2300 // initializer list that the child calls see, so that we don't try
2301 // to re-process the designator.
2302 unsigned OldIndex = Index;
2303 IList->setInit(OldIndex, DIE->getInit());
2304
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002305 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002306 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002307
2308 // Restore the designated initializer expression in the syntactic
2309 // form of the initializer list.
2310 if (IList->getInit(OldIndex) != DIE->getInit())
2311 DIE->setInit(IList->getInit(OldIndex));
2312 IList->setInit(OldIndex, DIE);
2313
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002314 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002315 }
2316
Douglas Gregora5324162009-04-15 04:56:10 +00002317 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002318 bool IsFirstDesignator = (DesigIdx == 0);
2319 if (!VerifyOnly) {
2320 assert((IsFirstDesignator || StructuredList) &&
2321 "Need a non-designated initializer list to start from");
2322
2323 // Determine the structural initializer list that corresponds to the
2324 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002325 if (IsFirstDesignator)
2326 StructuredList = SyntacticToSemantic.lookup(IList);
2327 else {
2328 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2329 StructuredList->getInit(StructuredIndex) : nullptr;
2330 if (!ExistingInit && StructuredList->hasArrayFiller())
2331 ExistingInit = StructuredList->getArrayFiller();
2332
2333 if (!ExistingInit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002334 StructuredList = getStructuredSubobjectInit(
2335 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002336 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
Yunzhong Gaocb779302015-06-10 00:27:52 +00002337 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2338 StructuredList = Result;
2339 else {
2340 if (DesignatedInitUpdateExpr *E =
2341 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2342 StructuredList = E->getUpdater();
2343 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002344 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2345 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002346 ExistingInit, DIE->getEndLoc());
Yunzhong Gaocb779302015-06-10 00:27:52 +00002347 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2348 StructuredList = DIUE->getUpdater();
2349 }
2350
2351 // We need to check on source range validity because the previous
2352 // initializer does not have to be an explicit initializer. e.g.,
2353 //
2354 // struct P { int a, b; };
2355 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2356 //
2357 // There is an overwrite taking place because the first braced initializer
2358 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2359 if (ExistingInit->getSourceRange().isValid()) {
2360 // We are creating an initializer list that initializes the
2361 // subobjects of the current object, but there was already an
2362 // initialization that completely initialized the current
2363 // subobject, e.g., by a compound literal:
2364 //
2365 // struct X { int a, b; };
2366 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2367 //
2368 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2369 // designated initializer re-initializes the whole
2370 // subobject [0], overwriting previous initializers.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002371 SemaRef.Diag(D->getBeginLoc(),
Yunzhong Gaocb779302015-06-10 00:27:52 +00002372 diag::warn_subobject_initializer_overrides)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002373 << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00002374
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002375 SemaRef.Diag(ExistingInit->getBeginLoc(),
Yunzhong Gaocb779302015-06-10 00:27:52 +00002376 diag::note_previous_initializer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002377 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002378 }
2379 }
2380 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002381 assert(StructuredList && "Expected a structured initializer list");
2382 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002383
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002384 if (D->isFieldDesignator()) {
2385 // C99 6.7.8p7:
2386 //
2387 // If a designator has the form
2388 //
2389 // . identifier
2390 //
2391 // then the current object (defined below) shall have
2392 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002393 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002394 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002395 if (!RT) {
2396 SourceLocation Loc = D->getDotLoc();
2397 if (Loc.isInvalid())
2398 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002399 if (!VerifyOnly)
2400 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002401 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002402 ++Index;
2403 return true;
2404 }
2405
Douglas Gregord5846a12009-04-15 06:41:24 +00002406 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002407 if (!KnownField) {
2408 IdentifierInfo *FieldName = D->getFieldName();
2409 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2410 for (NamedDecl *ND : Lookup) {
2411 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2412 KnownField = FD;
2413 break;
2414 }
2415 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002416 // In verify mode, don't modify the original.
2417 if (VerifyOnly)
2418 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002419 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002420 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002421 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002422 break;
2423 }
2424 }
David Majnemer36ef8982014-08-11 18:33:59 +00002425 if (!KnownField) {
2426 if (VerifyOnly) {
2427 ++Index;
2428 return true; // No typo correction when just trying this out.
2429 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002430
David Majnemer36ef8982014-08-11 18:33:59 +00002431 // Name lookup found something, but it wasn't a field.
2432 if (!Lookup.empty()) {
2433 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2434 << FieldName;
2435 SemaRef.Diag(Lookup.front()->getLocation(),
2436 diag::note_field_designator_found);
2437 ++Index;
2438 return true;
2439 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002440
David Majnemer36ef8982014-08-11 18:33:59 +00002441 // Name lookup didn't find anything.
2442 // Determine whether this was a typo for another field name.
Bruno Ricci70ad3962019-03-25 17:08:51 +00002443 FieldInitializerValidatorCCC CCC(RT->getDecl());
Richard Smithf9b15102013-08-17 00:46:16 +00002444 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2445 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Bruno Ricci70ad3962019-03-25 17:08:51 +00002446 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002447 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002448 SemaRef.diagnoseTypo(
2449 Corrected,
2450 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002451 << FieldName << CurrentObjectType);
2452 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002453 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002454 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002455 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002456 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2457 << FieldName << CurrentObjectType;
2458 ++Index;
2459 return true;
2460 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002461 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002462 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002463
David Majnemer58e4ea92014-08-23 01:48:50 +00002464 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002465
2466 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2467 FieldIndex = CXXRD->getNumBases();
2468
David Majnemer58e4ea92014-08-23 01:48:50 +00002469 for (auto *FI : RT->getDecl()->fields()) {
2470 if (FI->isUnnamedBitfield())
2471 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002472 if (declaresSameEntity(KnownField, FI)) {
2473 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002474 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002475 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002476 ++FieldIndex;
2477 }
2478
David Majnemer36ef8982014-08-11 18:33:59 +00002479 RecordDecl::field_iterator Field =
2480 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2481
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002482 // All of the fields of a union are located at the same place in
2483 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002484 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002485 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002486 if (!VerifyOnly) {
2487 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002488 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002489 assert(StructuredList->getNumInits() == 1
2490 && "A union should never have more than one initializer!");
2491
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002492 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002493 if (ExistingInit) {
2494 // We're about to throw away an initializer, emit warning.
2495 SemaRef.Diag(D->getFieldLoc(),
2496 diag::warn_initializer_overrides)
2497 << D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002498 SemaRef.Diag(ExistingInit->getBeginLoc(),
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002499 diag::note_previous_initializer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002500 << /*FIXME:has side effects=*/0
2501 << ExistingInit->getSourceRange();
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002502 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002503
2504 // remove existing initializer
2505 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002506 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002507 }
2508
David Blaikie40ed2972012-06-06 20:45:41 +00002509 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002510 }
Douglas Gregor51695702009-01-29 16:53:55 +00002511 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002512
Douglas Gregora82064c2011-06-29 21:51:31 +00002513 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002514 bool InvalidUse;
2515 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002516 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002517 else
David Blaikie40ed2972012-06-06 20:45:41 +00002518 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002519 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002520 ++Index;
2521 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002522 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002523
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002524 if (!VerifyOnly) {
2525 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002526 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002527
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002528 // Make sure that our non-designated initializer list has space
2529 // for a subobject corresponding to this field.
2530 if (FieldIndex >= StructuredList->getNumInits())
2531 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2532 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002533
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002534 // This designator names a flexible array member.
2535 if (Field->getType()->isIncompleteArrayType()) {
2536 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002537 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002538 // We can't designate an object within the flexible array
2539 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002540 if (!VerifyOnly) {
2541 DesignatedInitExpr::Designator *NextD
2542 = DIE->getDesignator(DesigIdx + 1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002543 SemaRef.Diag(NextD->getBeginLoc(),
2544 diag::err_designator_into_flexible_array_member)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002545 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002546 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002547 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002548 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002549 Invalid = true;
2550 }
2551
Chris Lattner001b29c2010-10-10 17:49:49 +00002552 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2553 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002554 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002555 if (!VerifyOnly) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002556 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2557 diag::err_flexible_array_init_needs_braces)
2558 << DIE->getInit()->getSourceRange();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002559 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002560 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002561 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002562 Invalid = true;
2563 }
2564
Eli Friedman3fa64df2011-08-23 22:24:57 +00002565 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002566 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002567 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002568 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002569
2570 if (Invalid) {
2571 ++Index;
2572 return true;
2573 }
2574
2575 // Initialize the array.
2576 bool prevHadError = hadError;
2577 unsigned newStructuredIndex = FieldIndex;
2578 unsigned OldIndex = Index;
2579 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002580
2581 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002582 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002583 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002584 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002585
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002586 IList->setInit(OldIndex, DIE);
2587 if (hadError && !prevHadError) {
2588 ++Field;
2589 ++FieldIndex;
2590 if (NextField)
2591 *NextField = Field;
2592 StructuredIndex = FieldIndex;
2593 return true;
2594 }
2595 } else {
2596 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002597 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002598 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002599
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002600 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002601 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002602 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002603 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002604 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002605 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002606 return true;
2607 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002608
2609 // Find the position of the next field to be initialized in this
2610 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002611 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002612 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002613
2614 // If this the first designator, our caller will continue checking
2615 // the rest of this struct/class/union subobject.
2616 if (IsFirstDesignator) {
2617 if (NextField)
2618 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002619 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002620 return false;
2621 }
2622
Douglas Gregor17bd0942009-01-28 23:36:17 +00002623 if (!FinishSubobjectInit)
2624 return false;
2625
Douglas Gregord5846a12009-04-15 06:41:24 +00002626 // We've already initialized something in the union; we're done.
2627 if (RT->getDecl()->isUnion())
2628 return hadError;
2629
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002630 // Check the remaining fields within this class/struct/union subobject.
2631 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002632
Richard Smith872307e2016-03-08 22:17:41 +00002633 auto NoBases =
2634 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2635 CXXRecordDecl::base_class_iterator());
2636 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2637 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002638 return hadError && !prevHadError;
2639 }
2640
2641 // C99 6.7.8p6:
2642 //
2643 // If a designator has the form
2644 //
2645 // [ constant-expression ]
2646 //
2647 // then the current object (defined below) shall have array
2648 // type and the expression shall be an integer constant
2649 // expression. If the array is of unknown size, any
2650 // nonnegative value is valid.
2651 //
2652 // Additionally, cope with the GNU extension that permits
2653 // designators of the form
2654 //
2655 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002656 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002657 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002658 if (!VerifyOnly)
2659 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2660 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002661 ++Index;
2662 return true;
2663 }
2664
Craig Topperc3ec1492014-05-26 06:22:03 +00002665 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002666 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2667 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002668 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002669 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002670 DesignatedEndIndex = DesignatedStartIndex;
2671 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002672 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002673
Mike Stump11289f42009-09-09 15:08:12 +00002674 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002675 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002676 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002677 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002678 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002679
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002680 // Codegen can't handle evaluating array range designators that have side
2681 // effects, because we replicate the AST value for each initialized element.
2682 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2683 // elements with something that has a side effect, so codegen can emit an
2684 // "error unsupported" error instead of miscompiling the app.
2685 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002686 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002687 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002688 }
2689
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002690 if (isa<ConstantArrayType>(AT)) {
2691 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002692 DesignatedStartIndex
2693 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002694 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002695 DesignatedEndIndex
2696 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002697 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2698 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002699 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002700 SemaRef.Diag(IndexExpr->getBeginLoc(),
2701 diag::err_array_designator_too_large)
2702 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2703 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002704 ++Index;
2705 return true;
2706 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002707 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002708 unsigned DesignatedIndexBitWidth =
2709 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2710 DesignatedStartIndex =
2711 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2712 DesignatedEndIndex =
2713 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002714 DesignatedStartIndex.setIsUnsigned(true);
2715 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Eli Friedman1f16b742013-06-11 21:48:11 +00002718 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2719 // We're modifying a string literal init; we have to decompose the string
2720 // so we can modify the individual characters.
2721 ASTContext &Context = SemaRef.Context;
2722 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2723
2724 // Compute the character type
2725 QualType CharTy = AT->getElementType();
2726
2727 // Compute the type of the integer literals.
2728 QualType PromotedCharTy = CharTy;
2729 if (CharTy->isPromotableIntegerType())
2730 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2731 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2732
2733 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2734 // Get the length of the string.
2735 uint64_t StrLen = SL->getLength();
2736 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2737 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2738 StructuredList->resizeInits(Context, StrLen);
2739
2740 // Build a literal for each character in the string, and put them into
2741 // the init list.
2742 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2743 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2744 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002745 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002746 if (CharTy != PromotedCharTy)
2747 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002748 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002749 StructuredList->updateInit(Context, i, Init);
2750 }
2751 } else {
2752 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2753 std::string Str;
2754 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2755
2756 // Get the length of the string.
2757 uint64_t StrLen = Str.size();
2758 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2759 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2760 StructuredList->resizeInits(Context, StrLen);
2761
2762 // Build a literal for each character in the string, and put them into
2763 // the init list.
2764 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2765 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2766 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002767 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002768 if (CharTy != PromotedCharTy)
2769 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002770 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002771 StructuredList->updateInit(Context, i, Init);
2772 }
2773 }
2774 }
2775
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002776 // Make sure that our non-designated initializer list has space
2777 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002778 if (!VerifyOnly &&
2779 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002780 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002781 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002782
Douglas Gregor17bd0942009-01-28 23:36:17 +00002783 // Repeatedly perform subobject initializations in the range
2784 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002785
Douglas Gregor17bd0942009-01-28 23:36:17 +00002786 // Move to the next designator
2787 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2788 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002789
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002790 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002791 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002792
Douglas Gregor17bd0942009-01-28 23:36:17 +00002793 while (DesignatedStartIndex <= DesignatedEndIndex) {
2794 // Recurse to check later designated subobjects.
2795 QualType ElementType = AT->getElementType();
2796 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002797
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002798 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002799 if (CheckDesignatedInitializer(
2800 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2801 nullptr, Index, StructuredList, ElementIndex,
2802 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2803 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002804 return true;
2805
2806 // Move to the next index in the array that we'll be initializing.
2807 ++DesignatedStartIndex;
2808 ElementIndex = DesignatedStartIndex.getZExtValue();
2809 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002810
2811 // If this the first designator, our caller will continue checking
2812 // the rest of this array subobject.
2813 if (IsFirstDesignator) {
2814 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002815 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002816 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002817 return false;
2818 }
Mike Stump11289f42009-09-09 15:08:12 +00002819
Douglas Gregor17bd0942009-01-28 23:36:17 +00002820 if (!FinishSubobjectInit)
2821 return false;
2822
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002823 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002824 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002826 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002827 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002828 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002829}
2830
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002831// Get the structured initializer list for a subobject of type
2832// @p CurrentObjectType.
2833InitListExpr *
2834InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2835 QualType CurrentObjectType,
2836 InitListExpr *StructuredList,
2837 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002838 SourceRange InitRange,
2839 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002840 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002841 return nullptr; // No structured list in verification-only mode.
2842 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002843 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002844 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002845 else if (StructuredIndex < StructuredList->getNumInits())
2846 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002847
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002848 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002849 // There might have already been initializers for subobjects of the current
2850 // object, but a subsequent initializer list will overwrite the entirety
2851 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2852 //
2853 // struct P { char x[6]; };
2854 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2855 //
2856 // The first designated initializer is ignored, and l.x is just "f".
2857 if (!IsFullyOverwritten)
2858 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002859
2860 if (ExistingInit) {
2861 // We are creating an initializer list that initializes the
2862 // subobjects of the current object, but there was already an
2863 // initialization that completely initialized the current
2864 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002865 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002866 // struct X { int a, b; };
2867 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002868 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002869 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2870 // designated initializer re-initializes the whole
2871 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002872 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002873 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002874 << InitRange;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002875 SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
2876 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002877 }
2878
Mike Stump11289f42009-09-09 15:08:12 +00002879 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002880 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002881 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002882 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002883
Eli Friedman91f5ae52012-02-23 02:25:10 +00002884 QualType ResultType = CurrentObjectType;
2885 if (!ResultType->isArrayType())
2886 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2887 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002888
Douglas Gregor6d00c992009-03-20 23:58:33 +00002889 // Pre-allocate storage for the structured initializer list.
2890 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002891 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002892 bool GotNumInits = false;
2893 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002894 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002895 GotNumInits = true;
2896 } else if (Index < IList->getNumInits()) {
2897 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002898 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002899 GotNumInits = true;
2900 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002901 }
2902
Mike Stump11289f42009-09-09 15:08:12 +00002903 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002904 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2905 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2906 NumElements = CAType->getSize().getZExtValue();
2907 // Simple heuristic so that we don't allocate a very large
2908 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002909 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002910 NumElements = 0;
2911 }
John McCall9dd450b2009-09-21 23:43:11 +00002912 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002913 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002914 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002915 RecordDecl *RDecl = RType->getDecl();
2916 if (RDecl->isUnion())
2917 NumElements = 1;
2918 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002919 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002920 }
2921
Ted Kremenekac034612010-04-13 23:39:13 +00002922 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002923
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002924 // Link this new initializer list into the structured initializer
2925 // lists.
2926 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002927 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002928 else {
2929 Result->setSyntacticForm(IList);
2930 SyntacticToSemantic[IList] = Result;
2931 }
2932
2933 return Result;
2934}
2935
2936/// Update the initializer at index @p StructuredIndex within the
2937/// structured initializer list to the value @p expr.
2938void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2939 unsigned &StructuredIndex,
2940 Expr *expr) {
2941 // No structured initializer list to update
2942 if (!StructuredList)
2943 return;
2944
Ted Kremenekac034612010-04-13 23:39:13 +00002945 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2946 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002947 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002948 // We need to check on source range validity because the previous
2949 // initializer does not have to be an explicit initializer.
2950 // struct P { int a, b; };
2951 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2952 // There is an overwrite taking place because the first braced initializer
2953 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2954 if (PrevInit->getSourceRange().isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002955 SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
2956 << expr->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002957
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002958 SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
2959 << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002960 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002961 }
Mike Stump11289f42009-09-09 15:08:12 +00002962
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002963 ++StructuredIndex;
2964}
2965
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002966/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002967/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002968/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002969/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002970/// failure. Returns the index expression, possibly with an implicit cast
2971/// added, on success. If everything went okay, Value will receive the
2972/// value of the constant expression.
2973static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002974CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002975 SourceLocation Loc = Index->getBeginLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002976
2977 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002978 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2979 if (Result.isInvalid())
2980 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002981
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002982 if (Value.isSigned() && Value.isNegative())
2983 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002984 << Value.toString(10) << Index->getSourceRange();
2985
Douglas Gregor51650d32009-01-23 21:04:18 +00002986 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002987 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002988}
2989
John McCalldadc5752010-08-24 06:29:42 +00002990ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002991 SourceLocation Loc,
2992 bool GNUSyntax,
2993 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002994 typedef DesignatedInitExpr::Designator ASTDesignator;
2995
2996 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002997 SmallVector<ASTDesignator, 32> Designators;
2998 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002999
3000 // Build designators and check array designator expressions.
3001 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3002 const Designator &D = Desig.getDesignator(Idx);
3003 switch (D.getKind()) {
3004 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00003005 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003006 D.getFieldLoc()));
3007 break;
3008
3009 case Designator::ArrayDesignator: {
3010 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3011 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00003012 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003013 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00003014 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003015 Invalid = true;
3016 else {
3017 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00003018 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003019 D.getRBracketLoc()));
3020 InitExpressions.push_back(Index);
3021 }
3022 break;
3023 }
3024
3025 case Designator::ArrayRangeDesignator: {
3026 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3027 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3028 llvm::APSInt StartValue;
3029 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003030 bool StartDependent = StartIndex->isTypeDependent() ||
3031 StartIndex->isValueDependent();
3032 bool EndDependent = EndIndex->isTypeDependent() ||
3033 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00003034 if (!StartDependent)
3035 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003036 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00003037 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003038 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00003039
3040 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003041 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00003042 else {
3043 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003044 if (StartDependent || EndDependent) {
3045 // Nothing to compute.
3046 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00003047 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00003048 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00003049 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00003050
Douglas Gregor0f9d4002009-05-21 23:30:39 +00003051 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00003052 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00003053 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00003054 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3055 Invalid = true;
3056 } else {
3057 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00003058 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00003059 D.getEllipsisLoc(),
3060 D.getRBracketLoc()));
3061 InitExpressions.push_back(StartIndex);
3062 InitExpressions.push_back(EndIndex);
3063 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003064 }
3065 break;
3066 }
3067 }
3068 }
3069
3070 if (Invalid || Init.isInvalid())
3071 return ExprError();
3072
3073 // Clear out the expressions within the designation.
3074 Desig.ClearExprs(*this);
3075
3076 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00003077 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00003078 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003079 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003080 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081
David Blaikiebbafb8a2012-03-11 07:00:24 +00003082 if (!getLangOpts().C99)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003083 Diag(DIE->getBeginLoc(), diag::ext_designated_init)
3084 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003085
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003086 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003087}
Douglas Gregor85df8d82009-01-29 00:45:39 +00003088
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003089//===----------------------------------------------------------------------===//
3090// Initialization entity
3091//===----------------------------------------------------------------------===//
3092
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003093InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00003094 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00003096{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003097 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3098 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00003099 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003100 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003101 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003102 Type = VT->getElementType();
3103 } else {
3104 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3105 assert(CT && "Unexpected type");
3106 Kind = EK_ComplexElement;
3107 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003108 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003109}
3110
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003111InitializedEntity
3112InitializedEntity::InitializeBase(ASTContext &Context,
3113 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00003114 bool IsInheritedVirtualBase,
3115 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003116 InitializedEntity Result;
3117 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00003118 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00003119 Result.Base = reinterpret_cast<uintptr_t>(Base);
3120 if (IsInheritedVirtualBase)
3121 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122
Douglas Gregor1b303932009-12-22 15:35:07 +00003123 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003124 return Result;
3125}
3126
Douglas Gregor85dabae2009-12-16 01:38:02 +00003127DeclarationName InitializedEntity::getName() const {
3128 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003129 case EK_Parameter:
3130 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00003131 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3132 return (D ? D->getDeclName() : DeclarationName());
3133 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003134
3135 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003136 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003137 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003138 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003139
Douglas Gregor19666fb2012-02-15 16:57:26 +00003140 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003141 return DeclarationName(Capture.VarID);
Fangrui Song6907ce22018-07-30 19:24:48 +00003142
Douglas Gregor85dabae2009-12-16 01:38:02 +00003143 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003144 case EK_StmtExprResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003145 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003146 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003147 case EK_Temporary:
3148 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003149 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003150 case EK_ArrayElement:
3151 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003152 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003153 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003154 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003155 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003156 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003157 return DeclarationName();
3158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159
David Blaikie8a40f702012-01-17 06:56:22 +00003160 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003161}
3162
Richard Smith7873de02016-08-11 22:25:46 +00003163ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003164 switch (getKind()) {
3165 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003166 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003167 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003168 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003169
John McCall31168b02011-06-15 23:02:42 +00003170 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003171 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003172 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3173
Douglas Gregora4b592a2009-12-19 03:01:41 +00003174 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003175 case EK_StmtExprResult:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003176 case EK_Exception:
3177 case EK_New:
3178 case EK_Temporary:
3179 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003180 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003181 case EK_ArrayElement:
3182 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003183 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003184 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003185 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003186 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003187 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003188 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003189 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191
David Blaikie8a40f702012-01-17 06:56:22 +00003192 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003193}
3194
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003195bool InitializedEntity::allowsNRVO() const {
3196 switch (getKind()) {
3197 case EK_Result:
3198 case EK_Exception:
3199 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200
Richard Smith67af95b2018-07-23 19:19:08 +00003201 case EK_StmtExprResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003202 case EK_Variable:
3203 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003204 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003205 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003206 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003207 case EK_New:
3208 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003209 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003210 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003211 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003212 case EK_ArrayElement:
3213 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003214 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003215 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003216 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003217 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003218 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003219 break;
3220 }
3221
3222 return false;
3223}
3224
Richard Smithe6c01442013-06-05 00:46:14 +00003225unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003226 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003227 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3228 for (unsigned I = 0; I != Depth; ++I)
3229 OS << "`-";
3230
3231 switch (getKind()) {
3232 case EK_Variable: OS << "Variable"; break;
3233 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003234 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3235 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003236 case EK_Result: OS << "Result"; break;
Richard Smith67af95b2018-07-23 19:19:08 +00003237 case EK_StmtExprResult: OS << "StmtExprResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003238 case EK_Exception: OS << "Exception"; break;
3239 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003240 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003241 case EK_New: OS << "New"; break;
3242 case EK_Temporary: OS << "Temporary"; break;
3243 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003244 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003245 case EK_Base: OS << "Base"; break;
3246 case EK_Delegating: OS << "Delegating"; break;
3247 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3248 case EK_VectorElement: OS << "VectorElement " << Index; break;
3249 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3250 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003251 case EK_LambdaToBlockConversionBlockElement:
3252 OS << "Block (lambda)";
3253 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003254 case EK_LambdaCapture:
3255 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003256 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003257 break;
3258 }
3259
Richard Smith7873de02016-08-11 22:25:46 +00003260 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003261 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003262 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003263 }
3264
3265 OS << " '" << getType().getAsString() << "'\n";
3266
3267 return Depth + 1;
3268}
3269
Yaron Kerencdae9412016-01-29 19:38:18 +00003270LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003271 dumpImpl(llvm::errs());
3272}
3273
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003274//===----------------------------------------------------------------------===//
3275// Initialization sequence
3276//===----------------------------------------------------------------------===//
3277
3278void InitializationSequence::Step::Destroy() {
3279 switch (Kind) {
3280 case SK_ResolveAddressOfOverloadedFunction:
3281 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003282 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003283 case SK_CastDerivedToBaseLValue:
3284 case SK_BindReference:
3285 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003286 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003287 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003288 case SK_UserConversion:
3289 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003290 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003291 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003292 case SK_AtomicConversion:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003293 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003294 case SK_UnwrapInitList:
3295 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003296 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003297 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003298 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003299 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003300 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003301 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003302 case SK_ArrayLoopIndex:
3303 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003304 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003305 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003306 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003307 case SK_PassByIndirectCopyRestore:
3308 case SK_PassByIndirectRestore:
3309 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003310 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003311 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003312 case SK_OCLSamplerInit:
Andrew Savonichevb555b762018-10-23 15:19:20 +00003313 case SK_OCLZeroOpaqueType:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003314 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003316 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003317 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003318 delete ICS;
3319 }
3320}
3321
Douglas Gregor838fcc32010-03-26 20:14:36 +00003322bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003323 // There can be some lvalue adjustments after the SK_BindReference step.
3324 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3325 if (I->Kind == SK_BindReference)
3326 return true;
3327 if (I->Kind == SK_BindReferenceToTemporary)
3328 return false;
3329 }
3330 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003331}
3332
3333bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003334 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003335 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
Douglas Gregor838fcc32010-03-26 20:14:36 +00003337 switch (getFailureKind()) {
3338 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003339 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003340 case FK_ArrayNeedsInitList:
3341 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003342 case FK_ArrayNeedsInitListOrWideStringLiteral:
3343 case FK_NarrowStringIntoWideCharArray:
3344 case FK_WideStringIntoCharArray:
3345 case FK_IncompatWideStringIntoWideChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00003346 case FK_PlainStringIntoUTF8Char:
3347 case FK_UTF8StringIntoPlainChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003348 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3349 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003350 case FK_NonConstLValueReferenceBindingToBitfield:
3351 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003352 case FK_NonConstLValueReferenceBindingToUnrelated:
3353 case FK_RValueReferenceBindingToLValue:
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00003354 case FK_ReferenceAddrspaceMismatchTemporary:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003355 case FK_ReferenceInitDropsQualifiers:
3356 case FK_ReferenceInitFailed:
3357 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003358 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003359 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003360 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003361 case FK_ReferenceBindingToInitList:
3362 case FK_InitListBadDestinationType:
3363 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003364 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003365 case FK_ArrayTypeMismatch:
3366 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003367 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003368 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003369 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003370 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003371 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003372 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373
Douglas Gregor838fcc32010-03-26 20:14:36 +00003374 case FK_ReferenceInitOverloadFailed:
3375 case FK_UserConversionOverloadFailed:
3376 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003377 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003378 return FailedOverloadResult == OR_Ambiguous;
3379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003380
David Blaikie8a40f702012-01-17 06:56:22 +00003381 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003382}
3383
Douglas Gregorb33eed02010-04-16 22:09:46 +00003384bool InitializationSequence::isConstructorInitialization() const {
3385 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3386}
3387
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003388void
3389InitializationSequence
3390::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3391 DeclAccessPair Found,
3392 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003393 Step S;
3394 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3395 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003396 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003397 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003398 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003399 Steps.push_back(S);
3400}
3401
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003403 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003404 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003405 switch (VK) {
3406 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3407 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3408 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003409 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003410 S.Type = BaseType;
3411 Steps.push_back(S);
3412}
3413
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003415 bool BindingTemporary) {
3416 Step S;
3417 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3418 S.Type = T;
3419 Steps.push_back(S);
3420}
3421
Richard Smithb8c0f552016-12-09 18:49:13 +00003422void InitializationSequence::AddFinalCopy(QualType T) {
3423 Step S;
3424 S.Kind = SK_FinalCopy;
3425 S.Type = T;
3426 Steps.push_back(S);
3427}
3428
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003429void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3430 Step S;
3431 S.Kind = SK_ExtraneousCopyToTemporary;
3432 S.Type = T;
3433 Steps.push_back(S);
3434}
3435
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003436void
3437InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3438 DeclAccessPair FoundDecl,
3439 QualType T,
3440 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003441 Step S;
3442 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003443 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003444 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003445 S.Function.Function = Function;
3446 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003447 Steps.push_back(S);
3448}
3449
3450void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003451 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003452 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003453 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003454 switch (VK) {
3455 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003456 S.Kind = SK_QualificationConversionRValue;
3457 break;
John McCall2536c6d2010-08-25 10:28:54 +00003458 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003459 S.Kind = SK_QualificationConversionXValue;
3460 break;
John McCall2536c6d2010-08-25 10:28:54 +00003461 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003462 S.Kind = SK_QualificationConversionLValue;
3463 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003464 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003465 S.Type = Ty;
3466 Steps.push_back(S);
3467}
3468
Richard Smith77be48a2014-07-31 06:31:19 +00003469void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3470 Step S;
3471 S.Kind = SK_AtomicConversion;
3472 S.Type = Ty;
3473 Steps.push_back(S);
3474}
3475
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003476void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003477 const ImplicitConversionSequence &ICS, QualType T,
3478 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003479 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003480 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3481 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003482 S.Type = T;
3483 S.ICS = new ImplicitConversionSequence(ICS);
3484 Steps.push_back(S);
3485}
3486
Douglas Gregor51e77d52009-12-10 17:56:55 +00003487void InitializationSequence::AddListInitializationStep(QualType T) {
3488 Step S;
3489 S.Kind = SK_ListInitialization;
3490 S.Type = T;
3491 Steps.push_back(S);
3492}
3493
Richard Smith55c28882016-05-12 23:45:49 +00003494void InitializationSequence::AddConstructorInitializationStep(
3495 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3496 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003497 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003498 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003499 : SK_ConstructorInitializationFromList
3500 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003501 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003502 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003503 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003504 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003505 Steps.push_back(S);
3506}
3507
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003508void InitializationSequence::AddZeroInitializationStep(QualType T) {
3509 Step S;
3510 S.Kind = SK_ZeroInitialization;
3511 S.Type = T;
3512 Steps.push_back(S);
3513}
3514
Douglas Gregore1314a62009-12-18 05:02:21 +00003515void InitializationSequence::AddCAssignmentStep(QualType T) {
3516 Step S;
3517 S.Kind = SK_CAssignment;
3518 S.Type = T;
3519 Steps.push_back(S);
3520}
3521
Eli Friedman78275202009-12-19 08:11:05 +00003522void InitializationSequence::AddStringInitStep(QualType T) {
3523 Step S;
3524 S.Kind = SK_StringInit;
3525 S.Type = T;
3526 Steps.push_back(S);
3527}
3528
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003529void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3530 Step S;
3531 S.Kind = SK_ObjCObjectConversion;
3532 S.Type = T;
3533 Steps.push_back(S);
3534}
3535
Richard Smith378b8c82016-12-14 03:22:16 +00003536void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003537 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003538 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003539 S.Type = T;
3540 Steps.push_back(S);
3541}
3542
Richard Smith410306b2016-12-12 02:53:20 +00003543void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3544 Step S;
3545 S.Kind = SK_ArrayLoopIndex;
3546 S.Type = EltT;
3547 Steps.insert(Steps.begin(), S);
3548
3549 S.Kind = SK_ArrayLoopInit;
3550 S.Type = T;
3551 Steps.push_back(S);
3552}
3553
Richard Smithebeed412012-02-15 22:38:09 +00003554void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3555 Step S;
3556 S.Kind = SK_ParenthesizedArrayInit;
3557 S.Type = T;
3558 Steps.push_back(S);
3559}
3560
John McCall31168b02011-06-15 23:02:42 +00003561void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3562 bool shouldCopy) {
3563 Step s;
3564 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3565 : SK_PassByIndirectRestore);
3566 s.Type = type;
3567 Steps.push_back(s);
3568}
3569
3570void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3571 Step S;
3572 S.Kind = SK_ProduceObjCObject;
3573 S.Type = T;
3574 Steps.push_back(S);
3575}
3576
Sebastian Redlc1839b12012-01-17 22:49:42 +00003577void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3578 Step S;
3579 S.Kind = SK_StdInitializerList;
3580 S.Type = T;
3581 Steps.push_back(S);
3582}
3583
Guy Benyei61054192013-02-07 10:55:47 +00003584void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3585 Step S;
3586 S.Kind = SK_OCLSamplerInit;
3587 S.Type = T;
3588 Steps.push_back(S);
3589}
3590
Andrew Savonichevb555b762018-10-23 15:19:20 +00003591void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003592 Step S;
Andrew Savonichevb555b762018-10-23 15:19:20 +00003593 S.Kind = SK_OCLZeroOpaqueType;
Egor Churaev89831422016-12-23 14:55:49 +00003594 S.Type = T;
3595 Steps.push_back(S);
3596}
3597
Sebastian Redl29526f02011-11-27 16:50:07 +00003598void InitializationSequence::RewrapReferenceInitList(QualType T,
3599 InitListExpr *Syntactic) {
3600 assert(Syntactic->getNumInits() == 1 &&
3601 "Can only rewrap trivial init lists.");
3602 Step S;
3603 S.Kind = SK_UnwrapInitList;
3604 S.Type = Syntactic->getInit(0)->getType();
3605 Steps.insert(Steps.begin(), S);
3606
3607 S.Kind = SK_RewrapInitList;
3608 S.Type = T;
3609 S.WrappingSyntacticList = Syntactic;
3610 Steps.push_back(S);
3611}
3612
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003614 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003615 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003616 this->Failure = Failure;
3617 this->FailedOverloadResult = Result;
3618}
3619
3620//===----------------------------------------------------------------------===//
3621// Attempt initialization
3622//===----------------------------------------------------------------------===//
3623
Nico Weber337d5aa2015-04-17 08:32:38 +00003624/// Tries to add a zero initializer. Returns true if that worked.
3625static bool
3626maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3627 const InitializedEntity &Entity) {
3628 if (Entity.getKind() != InitializedEntity::EK_Variable)
3629 return false;
3630
3631 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003632 if (VD->getInit() || VD->getEndLoc().isMacroID())
Nico Weber337d5aa2015-04-17 08:32:38 +00003633 return false;
3634
3635 QualType VariableTy = VD->getType().getCanonicalType();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003636 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
Nico Weber337d5aa2015-04-17 08:32:38 +00003637 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3638 if (!Init.empty()) {
3639 Sequence.AddZeroInitializationStep(Entity.getType());
3640 Sequence.SetZeroInitializationFixit(Init, Loc);
3641 return true;
3642 }
3643 return false;
3644}
3645
John McCall31168b02011-06-15 23:02:42 +00003646static void MaybeProduceObjCObject(Sema &S,
3647 InitializationSequence &Sequence,
3648 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003649 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003650
3651 /// When initializing a parameter, produce the value if it's marked
3652 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003653 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003654 if (!Entity.isParameterConsumed())
3655 return;
3656
3657 assert(Entity.getType()->isObjCRetainableType() &&
3658 "consuming an object of unretainable type?");
3659 Sequence.AddProduceObjCObjectStep(Entity.getType());
3660
3661 /// When initializing a return value, if the return type is a
3662 /// retainable type, then returns need to immediately retain the
3663 /// object. If an autorelease is required, it will be done at the
3664 /// last instant.
Richard Smith67af95b2018-07-23 19:19:08 +00003665 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3666 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
John McCall31168b02011-06-15 23:02:42 +00003667 if (!Entity.getType()->isObjCRetainableType())
3668 return;
3669
3670 Sequence.AddProduceObjCObjectStep(Entity.getType());
3671 }
3672}
3673
Richard Smithcc1b96d2013-06-12 22:31:48 +00003674static void TryListInitialization(Sema &S,
3675 const InitializedEntity &Entity,
3676 const InitializationKind &Kind,
3677 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003678 InitializationSequence &Sequence,
3679 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003680
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003681/// When initializing from init list via constructor, handle
Richard Smithd86812d2012-07-05 08:39:21 +00003682/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003683///
Richard Smithd86812d2012-07-05 08:39:21 +00003684/// \return true if we have handled initialization of an object of type
3685/// std::initializer_list<T>, false otherwise.
3686static bool TryInitializerListConstruction(Sema &S,
3687 InitListExpr *List,
3688 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003689 InitializationSequence &Sequence,
3690 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003691 QualType E;
3692 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003693 return false;
3694
Richard Smithdb0ac552015-12-18 22:40:25 +00003695 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003696 Sequence.setIncompleteTypeFailure(E);
3697 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003698 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003699
3700 // Try initializing a temporary array from the init list.
3701 QualType ArrayType = S.Context.getConstantArrayType(
3702 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3703 List->getNumInits()),
3704 clang::ArrayType::Normal, 0);
3705 InitializedEntity HiddenArray =
3706 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003707 InitializationKind Kind = InitializationKind::CreateDirectList(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003708 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
Manman Ren073db022016-03-10 18:53:19 +00003709 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3710 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003711 if (Sequence)
3712 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003713 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003714}
3715
Richard Smith7c2bcc92016-09-07 02:14:33 +00003716/// Determine if the constructor has the signature of a copy or move
3717/// constructor for the type T of the class in which it was found. That is,
3718/// determine if its first parameter is of type T or reference to (possibly
3719/// cv-qualified) T.
3720static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3721 const ConstructorInfo &Info) {
3722 if (Info.Constructor->getNumParams() == 0)
3723 return false;
3724
3725 QualType ParmT =
3726 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3727 QualType ClassT =
3728 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3729
3730 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3731}
3732
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003733static OverloadingResult
3734ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003735 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003736 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003737 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003738 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003739 OverloadCandidateSet::iterator &Best,
3740 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003741 bool OnlyListConstructors, bool IsListInit,
3742 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003743 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Anastasia Stulovac25ea862019-06-20 16:23:28 +00003744 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003745
Richard Smith40c78062015-02-21 02:31:57 +00003746 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003747 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003748 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003749 continue;
3750
Richard Smith7c2bcc92016-09-07 02:14:33 +00003751 if (!AllowExplicit && Info.Constructor->isExplicit())
3752 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003753
Richard Smith7c2bcc92016-09-07 02:14:33 +00003754 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3755 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003756
Richard Smith7c2bcc92016-09-07 02:14:33 +00003757 // C++11 [over.best.ics]p4:
3758 // ... and the constructor or user-defined conversion function is a
3759 // candidate by
3760 // - 13.3.1.3, when the argument is the temporary in the second step
3761 // of a class copy-initialization, or
3762 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3763 // - the second phase of 13.3.1.7 when the initializer list has exactly
3764 // one element that is itself an initializer list, and the target is
3765 // the first parameter of a constructor of class X, and the conversion
3766 // is to X or reference to (possibly cv-qualified X),
3767 // user-defined conversion sequences are not considered.
3768 bool SuppressUserConversions =
3769 SecondStepOfCopyInit ||
3770 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3771 hasCopyOrMoveCtorParam(S.Context, Info));
3772
3773 if (Info.ConstructorTmpl)
Richard Smith76b90272019-05-09 03:59:21 +00003774 S.AddTemplateOverloadCandidate(
3775 Info.ConstructorTmpl, Info.FoundDecl,
3776 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
3777 /*PartialOverloading=*/false, AllowExplicit);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003778 else {
3779 // C++ [over.match.copy]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00003780 // - When initializing a temporary to be bound to the first parameter
Richard Smith7c2bcc92016-09-07 02:14:33 +00003781 // of a constructor [for type T] that takes a reference to possibly
3782 // cv-qualified T as its first argument, called with a single
3783 // argument in the context of direct-initialization, explicit
3784 // conversion functions are also considered.
3785 // FIXME: What if a constructor template instantiates to such a signature?
Fangrui Song6907ce22018-07-30 19:24:48 +00003786 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Richard Smith7c2bcc92016-09-07 02:14:33 +00003787 Args.size() == 1 &&
3788 hasCopyOrMoveCtorParam(S.Context, Info);
3789 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3790 CandidateSet, SuppressUserConversions,
Richard Smith76b90272019-05-09 03:59:21 +00003791 /*PartialOverloading=*/false, AllowExplicit,
3792 AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003793 }
3794 }
3795
Richard Smith67ef14f2017-09-26 18:37:55 +00003796 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3797 //
3798 // When initializing an object of class type T by constructor
3799 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3800 // from a single expression of class type U, conversion functions of
3801 // U that convert to the non-reference type cv T are candidates.
3802 // Explicit conversion functions are only candidates during
3803 // direct-initialization.
3804 //
3805 // Note: SecondStepOfCopyInit is only ever true in this case when
3806 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003807 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003808 !SecondStepOfCopyInit) {
3809 Expr *Initializer = Args[0];
3810 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3811 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3812 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3813 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3814 NamedDecl *D = *I;
3815 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3816 D = D->getUnderlyingDecl();
3817
3818 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3819 CXXConversionDecl *Conv;
3820 if (ConvTemplate)
3821 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3822 else
3823 Conv = cast<CXXConversionDecl>(D);
3824
Richard Smith76b90272019-05-09 03:59:21 +00003825 if (AllowExplicit || !Conv->isExplicit()) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003826 if (ConvTemplate)
Richard Smith76b90272019-05-09 03:59:21 +00003827 S.AddTemplateConversionCandidate(
3828 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
3829 CandidateSet, AllowExplicit, AllowExplicit,
3830 /*AllowResultConversion*/ false);
Richard Smith67ef14f2017-09-26 18:37:55 +00003831 else
3832 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3833 DestType, CandidateSet, AllowExplicit,
Richard Smith76b90272019-05-09 03:59:21 +00003834 AllowExplicit,
3835 /*AllowResultConversion*/ false);
Richard Smith67ef14f2017-09-26 18:37:55 +00003836 }
3837 }
3838 }
3839 }
3840
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003841 // Perform overload resolution and return the result.
3842 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3843}
3844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003845/// Attempt initialization by constructor (C++ [dcl.init]), which
Sebastian Redled2e5322011-12-22 14:44:04 +00003846/// enumerates the constructors of the initialized entity and performs overload
3847/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003848/// \param DestType The destination class type.
3849/// \param DestArrayType The destination type, which is either DestType or
3850/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003851/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003852/// \param IsInitListCopy Is this non-list-initialization resulting from a
3853/// list-initialization from {x} where x is the same
3854/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003855static void TryConstructorInitialization(Sema &S,
3856 const InitializedEntity &Entity,
3857 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003858 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003859 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003860 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003861 bool IsListInit = false,
3862 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003863 assert(((!IsListInit && !IsInitListCopy) ||
3864 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3865 "IsListInit/IsInitListCopy must come with a single initializer list "
3866 "argument.");
3867 InitListExpr *ILE =
3868 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3869 MultiExprArg UnwrappedArgs =
3870 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003871
Sebastian Redled2e5322011-12-22 14:44:04 +00003872 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003873 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003874 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003875 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003876 }
3877
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003878 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003879 // - If the initializer expression is a prvalue and the cv-unqualified
3880 // version of the source type is the same class as the class of the
3881 // destination, the initializer expression is used to initialize the
3882 // destination object.
3883 // Per DR (no number yet), this does not apply when initializing a base
3884 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003885 // ObjC++: Lambda captured by the block in the lambda to block conversion
3886 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003887 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003888 Entity.getKind() != InitializedEntity::EK_Base &&
3889 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003890 Entity.getKind() !=
3891 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003892 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3893 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3894 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003895 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003896 if (ILE)
3897 Sequence.RewrapReferenceInitList(DestType, ILE);
3898 return;
3899 }
3900
Sebastian Redled2e5322011-12-22 14:44:04 +00003901 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3902 assert(DestRecordType && "Constructor initialization requires record type");
3903 CXXRecordDecl *DestRecordDecl
3904 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3905
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003906 // Build the candidate set directly in the initialization sequence
3907 // structure, so that it will persist if we fail.
3908 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3909
3910 // Determine whether we are allowed to call explicit constructors or
3911 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003912 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003913 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003914
Sebastian Redled2e5322011-12-22 14:44:04 +00003915 // - Otherwise, if T is a class type, constructors are considered. The
3916 // applicable constructors are enumerated, and the best one is chosen
3917 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003918 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003919
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003920 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003921 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003922 bool AsInitializerList = false;
3923
Larisse Voufo19d08672015-01-27 18:47:05 +00003924 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003925 // When objects of non-aggregate type T are list-initialized, such that
3926 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3927 // according to the rules in this section, overload resolution selects
3928 // the constructor in two phases:
3929 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003930 // - Initially, the candidate functions are the initializer-list
3931 // constructors of the class T and the argument list consists of the
3932 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003933 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003934 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003935
3936 // If the initializer list has no elements and T has a default constructor,
3937 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003938 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003939 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003940 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003941 CopyInitialization, AllowExplicit,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003942 /*OnlyListConstructors=*/true,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003943 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003944 }
3945
3946 // C++11 [over.match.list]p1:
3947 // - If no viable initializer-list constructor is found, overload resolution
3948 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003949 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003950 // elements of the initializer list.
3951 if (Result == OR_No_Viable_Function) {
3952 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003953 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003954 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003955 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003956 /*OnlyListConstructors=*/false,
3957 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003958 }
3959 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003960 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003961 InitializationSequence::FK_ListConstructorOverloadFailed :
3962 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003963 Result);
3964 return;
3965 }
3966
Richard Smith67ef14f2017-09-26 18:37:55 +00003967 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3968
3969 // In C++17, ResolveConstructorOverload can select a conversion function
3970 // instead of a constructor.
3971 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3972 // Add the user-defined conversion step that calls the conversion function.
3973 QualType ConvType = CD->getConversionType();
3974 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3975 "should not have selected this conversion function");
3976 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3977 HadMultipleCandidates);
3978 if (!S.Context.hasSameType(ConvType, DestType))
3979 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3980 if (IsListInit)
3981 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3982 return;
3983 }
3984
Richard Smithd86812d2012-07-05 08:39:21 +00003985 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003986 // If a program calls for the default initialization of an object
3987 // of a const-qualified type T, T shall be a class type with a
3988 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003989 // C++ core issue 253 proposal:
3990 // If the implicit default constructor initializes all subobjects, no
3991 // initializer should be required.
3992 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3993 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003994 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003995 Entity.getType().isConstQualified()) {
3996 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3997 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3998 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3999 return;
4000 }
Sebastian Redled2e5322011-12-22 14:44:04 +00004001 }
4002
Sebastian Redl048a6d72012-04-01 19:54:59 +00004003 // C++11 [over.match.list]p1:
4004 // In copy-list-initialization, if an explicit constructor is chosen, the
4005 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00004006 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00004007 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4008 return;
4009 }
4010
Sebastian Redled2e5322011-12-22 14:44:04 +00004011 // Add the constructor initialization step. Any cv-qualification conversion is
4012 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00004013 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00004014 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00004015 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00004016}
4017
Sebastian Redl29526f02011-11-27 16:50:07 +00004018static bool
4019ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4020 Expr *Initializer,
4021 QualType &SourceType,
4022 QualType &UnqualifiedSourceType,
4023 QualType UnqualifiedTargetType,
4024 InitializationSequence &Sequence) {
4025 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4026 S.Context.OverloadTy) {
4027 DeclAccessPair Found;
4028 bool HadMultipleCandidates = false;
4029 if (FunctionDecl *Fn
4030 = S.ResolveAddressOfOverloadedFunction(Initializer,
4031 UnqualifiedTargetType,
4032 false, Found,
4033 &HadMultipleCandidates)) {
4034 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4035 HadMultipleCandidates);
4036 SourceType = Fn->getType();
4037 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4038 } else if (!UnqualifiedTargetType->isRecordType()) {
4039 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4040 return true;
4041 }
4042 }
4043 return false;
4044}
4045
4046static void TryReferenceInitializationCore(Sema &S,
4047 const InitializedEntity &Entity,
4048 const InitializationKind &Kind,
4049 Expr *Initializer,
4050 QualType cv1T1, QualType T1,
4051 Qualifiers T1Quals,
4052 QualType cv2T2, QualType T2,
4053 Qualifiers T2Quals,
4054 InitializationSequence &Sequence);
4055
Richard Smithd86812d2012-07-05 08:39:21 +00004056static void TryValueInitialization(Sema &S,
4057 const InitializedEntity &Entity,
4058 const InitializationKind &Kind,
4059 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00004060 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00004061
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004062/// Attempt list initialization of a reference.
Sebastian Redl29526f02011-11-27 16:50:07 +00004063static void TryReferenceListInitialization(Sema &S,
4064 const InitializedEntity &Entity,
4065 const InitializationKind &Kind,
4066 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004067 InitializationSequence &Sequence,
4068 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00004069 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004070 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00004071 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4072 return;
4073 }
David Majnemer9370dc22015-04-26 07:35:03 +00004074 // Can't reference initialize a compound literal.
4075 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4076 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4077 return;
4078 }
Sebastian Redl29526f02011-11-27 16:50:07 +00004079
4080 QualType DestType = Entity.getType();
4081 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4082 Qualifiers T1Quals;
4083 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4084
4085 // Reference initialization via an initializer list works thus:
4086 // If the initializer list consists of a single element that is
4087 // reference-related to the referenced type, bind directly to that element
4088 // (possibly creating temporaries).
4089 // Otherwise, initialize a temporary with the initializer list and
4090 // bind to that.
4091 if (InitList->getNumInits() == 1) {
4092 Expr *Initializer = InitList->getInit(0);
4093 QualType cv2T2 = Initializer->getType();
4094 Qualifiers T2Quals;
4095 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4096
4097 // If this fails, creating a temporary wouldn't work either.
4098 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4099 T1, Sequence))
4100 return;
4101
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004102 SourceLocation DeclLoc = Initializer->getBeginLoc();
Sebastian Redl29526f02011-11-27 16:50:07 +00004103 bool dummy1, dummy2, dummy3;
4104 Sema::ReferenceCompareResult RefRelationship
4105 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
4106 dummy2, dummy3);
4107 if (RefRelationship >= Sema::Ref_Related) {
4108 // Try to bind the reference here.
4109 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4110 T1Quals, cv2T2, T2, T2Quals, Sequence);
4111 if (Sequence)
4112 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4113 return;
4114 }
Richard Smith03d93932013-01-15 07:58:29 +00004115
4116 // Update the initializer if we've resolved an overloaded function.
4117 if (Sequence.step_begin() != Sequence.step_end())
4118 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00004119 }
4120
4121 // Not reference-related. Create a temporary and bind to that.
4122 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4123
Manman Ren073db022016-03-10 18:53:19 +00004124 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4125 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00004126 if (Sequence) {
4127 if (DestType->isRValueReferenceType() ||
4128 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004129 Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
Sebastian Redl29526f02011-11-27 16:50:07 +00004130 else
4131 Sequence.SetFailed(
4132 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4133 }
4134}
4135
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004136/// Attempt list initialization (C++0x [dcl.init.list])
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004137static void TryListInitialization(Sema &S,
4138 const InitializedEntity &Entity,
4139 const InitializationKind &Kind,
4140 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004141 InitializationSequence &Sequence,
4142 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004143 QualType DestType = Entity.getType();
4144
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004145 // C++ doesn't allow scalar initialization with more than one argument.
4146 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004147 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004148 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4149 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4150 return;
4151 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004152 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004153 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4154 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004155 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004156 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004157
Larisse Voufod2010992015-01-24 23:09:54 +00004158 if (DestType->isRecordType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004159 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004160 Sequence.setIncompleteTypeFailure(DestType);
4161 return;
4162 }
Richard Smithd86812d2012-07-05 08:39:21 +00004163
Larisse Voufo19d08672015-01-27 18:47:05 +00004164 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004165 // - If T is a class type and the initializer list has a single element of
4166 // type cv U, where U is T or a class derived from T, the object is
4167 // initialized from that element (by copy-initialization for
4168 // copy-list-initialization, or by direct-initialization for
4169 // direct-list-initialization).
4170 // - Otherwise, if T is a character array and the initializer list has a
4171 // single element that is an appropriately-typed string literal
4172 // (8.5.2 [dcl.init.string]), initialization is performed as described
4173 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004174 // - Otherwise, if T is an aggregate, [...] (continue below).
4175 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004176 if (DestType->isRecordType()) {
4177 QualType InitType = InitList->getInit(0)->getType();
4178 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004179 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004180 Expr *InitListAsExpr = InitList;
4181 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004182 DestType, Sequence,
4183 /*InitListSyntax*/false,
4184 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004185 return;
4186 }
4187 }
4188 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4189 Expr *SubInit[1] = {InitList->getInit(0)};
4190 if (!isa<VariableArrayType>(DestAT) &&
4191 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4192 InitializationKind SubKind =
4193 Kind.getKind() == InitializationKind::IK_DirectList
4194 ? InitializationKind::CreateDirect(Kind.getLocation(),
4195 InitList->getLBraceLoc(),
4196 InitList->getRBraceLoc())
4197 : Kind;
4198 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004199 /*TopLevelOfInitList*/ true,
4200 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004201
4202 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4203 // the element is not an appropriately-typed string literal, in which
4204 // case we should proceed as in C++11 (below).
4205 if (Sequence) {
4206 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4207 return;
4208 }
4209 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004210 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004211 }
Larisse Voufod2010992015-01-24 23:09:54 +00004212
4213 // C++11 [dcl.init.list]p3:
4214 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004215 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4216 (S.getLangOpts().CPlusPlus11 &&
4217 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004218 if (S.getLangOpts().CPlusPlus11) {
4219 // - Otherwise, if the initializer list has no elements and T is a
4220 // class type with a default constructor, the object is
4221 // value-initialized.
4222 if (InitList->getNumInits() == 0) {
4223 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4224 if (RD->hasDefaultConstructor()) {
4225 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4226 return;
4227 }
4228 }
4229
4230 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4231 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004232 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4233 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004234 return;
4235
4236 // - Otherwise, if T is a class type, constructors are considered.
4237 Expr *InitListAsExpr = InitList;
4238 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004239 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004240 } else
4241 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4242 return;
4243 }
4244
Richard Smith089c3162013-09-21 21:55:46 +00004245 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004246 InitList->getNumInits() == 1) {
4247 Expr *E = InitList->getInit(0);
4248
4249 // - Otherwise, if T is an enumeration with a fixed underlying type,
4250 // the initializer-list has a single element v, and the initialization
4251 // is direct-list-initialization, the object is initialized with the
4252 // value T(v); if a narrowing conversion is required to convert v to
4253 // the underlying type of T, the program is ill-formed.
4254 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004255 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004256 Kind.getKind() == InitializationKind::IK_DirectList &&
4257 ET && ET->getDecl()->isFixed() &&
4258 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4259 (E->getType()->isIntegralOrEnumerationType() ||
4260 E->getType()->isFloatingType())) {
4261 // There are two ways that T(v) can work when T is an enumeration type.
4262 // If there is either an implicit conversion sequence from v to T or
4263 // a conversion function that can convert from v to T, then we use that.
4264 // Otherwise, if v is of integral, enumeration, or floating-point type,
4265 // it is converted to the enumeration type via its underlying type.
4266 // There is no overlap possible between these two cases (except when the
4267 // source value is already of the destination type), and the first
4268 // case is handled by the general case for single-element lists below.
4269 ImplicitConversionSequence ICS;
4270 ICS.setStandard();
4271 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004272 if (!E->isRValue())
4273 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004274 // If E is of a floating-point type, then the conversion is ill-formed
4275 // due to narrowing, but go through the motions in order to produce the
4276 // right diagnostic.
4277 ICS.Standard.Second = E->getType()->isFloatingType()
4278 ? ICK_Floating_Integral
4279 : ICK_Integral_Conversion;
4280 ICS.Standard.setFromType(E->getType());
4281 ICS.Standard.setToType(0, E->getType());
4282 ICS.Standard.setToType(1, DestType);
4283 ICS.Standard.setToType(2, DestType);
4284 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4285 /*TopLevelOfInitList*/true);
4286 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4287 return;
4288 }
4289
Richard Smith089c3162013-09-21 21:55:46 +00004290 // - Otherwise, if the initializer list has a single element of type E
4291 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004292 // initialized from that element (by copy-initialization for
4293 // copy-list-initialization, or by direct-initialization for
4294 // direct-list-initialization); if a narrowing conversion is required
4295 // to convert the element to T, the program is ill-formed.
4296 //
Richard Smith089c3162013-09-21 21:55:46 +00004297 // Per core-24034, this is direct-initialization if we were performing
4298 // direct-list-initialization and copy-initialization otherwise.
4299 // We can't use InitListChecker for this, because it always performs
4300 // copy-initialization. This only matters if we might use an 'explicit'
4301 // conversion operator, so we only need to handle the cases where the source
4302 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004303 if (InitList->getInit(0)->getType()->isRecordType()) {
4304 InitializationKind SubKind =
4305 Kind.getKind() == InitializationKind::IK_DirectList
4306 ? InitializationKind::CreateDirect(Kind.getLocation(),
4307 InitList->getLBraceLoc(),
4308 InitList->getRBraceLoc())
4309 : Kind;
4310 Expr *SubInit[1] = { InitList->getInit(0) };
4311 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4312 /*TopLevelOfInitList*/true,
4313 TreatUnavailableAsInvalid);
4314 if (Sequence)
4315 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4316 return;
4317 }
Richard Smith089c3162013-09-21 21:55:46 +00004318 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004319
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004320 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004321 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004322 if (CheckInitList.HadError()) {
4323 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4324 return;
4325 }
4326
4327 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004328 Sequence.AddListInitializationStep(DestType);
4329}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004330
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004331/// Try a reference initialization that involves calling a conversion
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004332/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004333static OverloadingResult TryRefInitWithConversionFunction(
4334 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4335 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4336 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004337 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004338 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4339 QualType T1 = cv1T1.getUnqualifiedType();
4340 QualType cv2T2 = Initializer->getType();
4341 QualType T2 = cv2T2.getUnqualifiedType();
4342
4343 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004344 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004345 bool ObjCLifetimeConversion;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004346 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
4347 DerivedToBase, ObjCConversion,
John McCall31168b02011-06-15 23:02:42 +00004348 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004349 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004350 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004351 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004352 (void)ObjCLifetimeConversion;
Fangrui Song6907ce22018-07-30 19:24:48 +00004353
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004354 // Build the candidate set directly in the initialization sequence
4355 // structure, so that it will persist if we fail.
4356 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004357 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004358
Richard Smithb368ea82018-07-02 23:25:22 +00004359 // Determine whether we are allowed to call explicit conversion operators.
4360 // Note that none of [over.match.copy], [over.match.conv], nor
4361 // [over.match.ref] permit an explicit constructor to be chosen when
4362 // initializing a reference, not even for direct-initialization.
4363 bool AllowExplicitCtors = false;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004364 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4365
Craig Topperc3ec1492014-05-26 06:22:03 +00004366 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004367 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004368 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004369 // The type we're converting to is a class type. Enumerate its constructors
4370 // to see if there is a suitable conversion.
4371 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004372
Richard Smith40c78062015-02-21 02:31:57 +00004373 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004374 auto Info = getConstructorInfo(D);
4375 if (!Info.Constructor)
4376 continue;
John McCalla0296f72010-03-19 07:35:19 +00004377
Richard Smithc2bebe92016-05-11 20:37:46 +00004378 if (!Info.Constructor->isInvalidDecl() &&
Richard Smithb368ea82018-07-02 23:25:22 +00004379 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004380 if (Info.ConstructorTmpl)
Richard Smith76b90272019-05-09 03:59:21 +00004381 S.AddTemplateOverloadCandidate(
4382 Info.ConstructorTmpl, Info.FoundDecl,
4383 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4384 /*SuppressUserConversions=*/true,
4385 /*PartialOverloading*/ false, AllowExplicitCtors);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004386 else
Richard Smith76b90272019-05-09 03:59:21 +00004387 S.AddOverloadCandidate(
4388 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4389 /*SuppressUserConversions=*/true,
4390 /*PartialOverloading*/ false, AllowExplicitCtors);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004391 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004393 }
John McCall3696dcb2010-08-17 07:23:57 +00004394 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4395 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396
Craig Topperc3ec1492014-05-26 06:22:03 +00004397 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004398 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004399 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004400 // The type we're converting from is a class type, enumerate its conversion
4401 // functions.
4402 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4403
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004404 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4405 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004406 NamedDecl *D = *I;
4407 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4408 if (isa<UsingShadowDecl>(D))
4409 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004411 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4412 CXXConversionDecl *Conv;
4413 if (ConvTemplate)
4414 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4415 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004416 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004418 // If the conversion function doesn't return a reference type,
4419 // it can't be considered for this conversion unless we're allowed to
4420 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421 // FIXME: Do we need to make sure that we only consider conversion
4422 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004423 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004424 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Richard Smith76b90272019-05-09 03:59:21 +00004425 (AllowRValues ||
4426 Conv->getConversionType()->isLValueReferenceType())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004427 if (ConvTemplate)
Richard Smith76b90272019-05-09 03:59:21 +00004428 S.AddTemplateConversionCandidate(
4429 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4430 CandidateSet,
4431 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004432 else
Richard Smith76b90272019-05-09 03:59:21 +00004433 S.AddConversionCandidate(
4434 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4435 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004436 }
4437 }
4438 }
John McCall3696dcb2010-08-17 07:23:57 +00004439 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4440 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004442 SourceLocation DeclLoc = Initializer->getBeginLoc();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004443
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004445 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004447 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004448 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004449
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004450 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004451 // This is the overload that will be used for this initialization step if we
4452 // use this initialization. Mark it as referenced.
4453 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004454
Richard Smithb8c0f552016-12-09 18:49:13 +00004455 // Compute the returned type and value kind of the conversion.
4456 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004457 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004458 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004459 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004460 cv3T3 = T1;
4461
4462 ExprValueKind VK = VK_RValue;
4463 if (cv3T3->isLValueReferenceType())
4464 VK = VK_LValue;
4465 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4466 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4467 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004468
4469 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004470 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004471 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004472 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004473
Richard Smithb8c0f552016-12-09 18:49:13 +00004474 // Determine whether we'll need to perform derived-to-base adjustments or
4475 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004476 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004477 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004478 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004479 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004480 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004481 NewDerivedToBase, NewObjCConversion,
4482 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004483
4484 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004485 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004486 assert(!isa<CXXConstructorDecl>(Function) &&
4487 "should not have conversion after constructor");
4488
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004489 ImplicitConversionSequence ICS;
4490 ICS.setStandard();
4491 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004492 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4493
4494 // Every implicit conversion results in a prvalue, except for a glvalue
4495 // derived-to-base conversion, which we handle below.
4496 cv3T3 = ICS.Standard.getToType(2);
4497 VK = VK_RValue;
4498 }
4499
4500 // If the converted initializer is a prvalue, its type T4 is adjusted to
4501 // type "cv1 T4" and the temporary materialization conversion is applied.
4502 //
4503 // We adjust the cv-qualifications to match the reference regardless of
4504 // whether we have a prvalue so that the AST records the change. In this
4505 // case, T4 is "cv3 T3".
4506 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4507 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4508 Sequence.AddQualificationConversionStep(cv1T4, VK);
4509 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4510 VK = IsLValueRef ? VK_LValue : VK_XValue;
4511
4512 if (NewDerivedToBase)
4513 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004514 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004515 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004516
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004517 return OR_Success;
4518}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519
Richard Smithc620f552011-10-19 16:55:56 +00004520static void CheckCXX98CompatAccessibleCopy(Sema &S,
4521 const InitializedEntity &Entity,
4522 Expr *CurInitExpr);
4523
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004524/// Attempt reference initialization (C++0x [dcl.init.ref])
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004526 const InitializedEntity &Entity,
4527 const InitializationKind &Kind,
4528 Expr *Initializer,
4529 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004530 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004531 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004532 Qualifiers T1Quals;
4533 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004534 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004535 Qualifiers T2Quals;
4536 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004537
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004538 // If the initializer is the address of an overloaded function, try
4539 // to resolve the overloaded function. If all goes well, T2 is the
4540 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004541 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4542 T1, Sequence))
4543 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004544
Sebastian Redl29526f02011-11-27 16:50:07 +00004545 // Delegate everything else to a subfunction.
4546 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4547 T1Quals, cv2T2, T2, T2Quals, Sequence);
4548}
4549
Richard Smithb8c0f552016-12-09 18:49:13 +00004550/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004551/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004552/// such a glvalue will always create a temporary.
4553static bool isNonReferenceableGLValue(Expr *E) {
4554 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004555}
4556
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004557/// Reference initialization without resolving overloaded functions.
Sebastian Redl29526f02011-11-27 16:50:07 +00004558static void TryReferenceInitializationCore(Sema &S,
4559 const InitializedEntity &Entity,
4560 const InitializationKind &Kind,
4561 Expr *Initializer,
4562 QualType cv1T1, QualType T1,
4563 Qualifiers T1Quals,
4564 QualType cv2T2, QualType T2,
4565 Qualifiers T2Quals,
4566 InitializationSequence &Sequence) {
4567 QualType DestType = Entity.getType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004568 SourceLocation DeclLoc = Initializer->getBeginLoc();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004569 // Compute some basic properties of the types and the initializer.
4570 bool isLValueRef = DestType->isLValueReferenceType();
4571 bool isRValueRef = !isLValueRef;
4572 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004573 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004574 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004575 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004576 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004577 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004578 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004579
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004580 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004582 // "cv2 T2" as follows:
4583 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004585 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004586 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004587 // there are no function rvalues in C++, rvalue refs to functions are treated
4588 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004589 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004590 bool T1Function = T1->isFunctionType();
4591 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004592 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004593 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004595 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004596 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004597 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004598 if (T1Quals != T2Quals)
4599 // Convert to cv1 T2. This should only add qualifiers unless this is a
4600 // c-style cast. The removal of qualifiers in that case notionally
4601 // happens after the reference binding, but that doesn't matter.
4602 Sequence.AddQualificationConversionStep(
4603 S.Context.getQualifiedType(T2, T1Quals),
4604 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004605 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004606 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004607 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004608 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004609
Richard Smithb8c0f552016-12-09 18:49:13 +00004610 // We only create a temporary here when binding a reference to a
4611 // bit-field or vector element. Those cases are't supposed to be
4612 // handled by this bullet, but the outcome is the same either way.
4613 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004614 return;
4615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
4617 // - has a class type (i.e., T2 is a class type), where T1 is not
4618 // reference-related to T2, and can be implicitly converted to an
4619 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4620 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004621 // applicable conversion functions (13.3.1.6) and choosing the best
4622 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004623 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004624 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004625 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4626 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004627 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004628 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4629 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004630 if (ConvOvlResult == OR_Success)
4631 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004632 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004633 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004634 InitializationSequence::FK_ReferenceInitOverloadFailed,
4635 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004636 }
4637 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004638
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004640 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004641 // shall be an rvalue reference.
Anastasia Stulova3562edb2019-06-21 11:36:15 +00004642 // For address spaces, we interpret this to mean that an addr space
4643 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4644 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
4645 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004646 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4647 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4648 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004649 Sequence.SetOverloadFailure(
4650 InitializationSequence::FK_ReferenceInitOverloadFailed,
4651 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004652 else if (!InitCategory.isLValue())
4653 Sequence.SetFailed(
Anastasia Stulova3562edb2019-06-21 11:36:15 +00004654 T1Quals.isAddressSpaceSupersetOf(T2Quals)
4655 ? InitializationSequence::
4656 FK_NonConstLValueReferenceBindingToTemporary
4657 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
Richard Smithb8c0f552016-12-09 18:49:13 +00004658 else {
4659 InitializationSequence::FailureKind FK;
4660 switch (RefRelationship) {
4661 case Sema::Ref_Compatible:
4662 if (Initializer->refersToBitField())
4663 FK = InitializationSequence::
4664 FK_NonConstLValueReferenceBindingToBitfield;
4665 else if (Initializer->refersToVectorElement())
4666 FK = InitializationSequence::
4667 FK_NonConstLValueReferenceBindingToVectorElement;
4668 else
4669 llvm_unreachable("unexpected kind of compatible initializer");
4670 break;
4671 case Sema::Ref_Related:
4672 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4673 break;
4674 case Sema::Ref_Incompatible:
4675 FK = InitializationSequence::
4676 FK_NonConstLValueReferenceBindingToUnrelated;
4677 break;
4678 }
4679 Sequence.SetFailed(FK);
4680 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004681 return;
4682 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004683
Douglas Gregor92e460e2011-01-20 16:44:54 +00004684 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004685 // - is an
4686 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4687 // [1z] rvalue (but not a bit-field) or
4688 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4689 //
4690 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004691 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004692 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004693 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004694 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004695 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004696 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004697 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004698 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004699 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004700 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004701 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4702 // compiler the freedom to perform a copy here or bind to the
4703 // object, while C++0x requires that we bind directly to the
4704 // object. Hence, we always bind to the object without making an
4705 // extra copy. However, in C++03 requires that we check for the
4706 // presence of a suitable copy constructor:
4707 //
4708 // The constructor that would be used to make the copy shall
4709 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004710 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004711 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004712 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004713 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004715
Richard Smithb8c0f552016-12-09 18:49:13 +00004716 // C++1z [dcl.init.ref]/5.2.1.2:
4717 // If the converted initializer is a prvalue, its type T4 is adjusted
4718 // to type "cv1 T4" and the temporary materialization conversion is
4719 // applied.
Anastasia Stulovad1986d12019-01-14 11:44:22 +00004720 // Postpone address space conversions to after the temporary materialization
4721 // conversion to allow creating temporaries in the alloca address space.
Anastasia Stulovae368e4d2019-02-05 11:32:58 +00004722 auto T1QualsIgnoreAS = T1Quals;
4723 auto T2QualsIgnoreAS = T2Quals;
4724 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4725 T1QualsIgnoreAS.removeAddressSpace();
4726 T2QualsIgnoreAS.removeAddressSpace();
4727 }
4728 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
4729 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
Richard Smithb8c0f552016-12-09 18:49:13 +00004730 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4731 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4732 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
Anastasia Stulovae368e4d2019-02-05 11:32:58 +00004733 // Add addr space conversion if required.
4734 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4735 auto T4Quals = cv1T4.getQualifiers();
4736 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
4737 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
4738 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
Anastasia Stulovad1986d12019-01-14 11:44:22 +00004739 }
Richard Smithb8c0f552016-12-09 18:49:13 +00004740
4741 // In any case, the reference is bound to the resulting glvalue (or to
4742 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004743 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004744 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004745 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004746 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004747 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004749
4750 // - has a class type (i.e., T2 is a class type), where T1 is not
4751 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004752 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4753 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004754 //
4755 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004756 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004757 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004758 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004759 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4760 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004761 if (ConvOvlResult)
4762 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004763 InitializationSequence::FK_ReferenceInitOverloadFailed,
4764 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004766 return;
4767 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
Richard Smithce766292016-10-21 23:01:55 +00004769 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004770 isRValueRef && InitCategory.isLValue()) {
4771 Sequence.SetFailed(
4772 InitializationSequence::FK_RValueReferenceBindingToLValue);
4773 return;
4774 }
4775
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004776 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4777 return;
4778 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004779
4780 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004781 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004782 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004783 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004784
Anastasia Stulovad3ae87e2019-03-06 13:02:41 +00004785 // Ignore address space of reference type at this point and perform address
4786 // space conversion after the reference binding step.
4787 QualType cv1T1IgnoreAS =
4788 T1Quals.hasAddressSpace()
4789 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
4790 : cv1T1;
4791
4792 InitializedEntity TempEntity =
4793 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
John McCallec6f4e92010-06-04 02:29:22 +00004794
Richard Smith2eabf782013-06-13 00:57:57 +00004795 // FIXME: Why do we use an implicit conversion here rather than trying
4796 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004797 ImplicitConversionSequence ICS
4798 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004799 /*SuppressUserConversions=*/false,
4800 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004801 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004802 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4803 /*AllowObjCWritebackConversion=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00004804
John McCall31168b02011-06-15 23:02:42 +00004805 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004806 // FIXME: Use the conversion function set stored in ICS to turn
4807 // this into an overloading ambiguity diagnostic. However, we need
4808 // to keep that set as an OverloadCandidateSet rather than as some
4809 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004810 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4811 Sequence.SetOverloadFailure(
4812 InitializationSequence::FK_ReferenceInitOverloadFailed,
4813 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004814 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4815 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004816 else
4817 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004818 return;
John McCall31168b02011-06-15 23:02:42 +00004819 } else {
4820 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004821 }
4822
4823 // [...] If T1 is reference-related to T2, cv1 must be the
4824 // same cv-qualification as, or greater cv-qualification
4825 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004826 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4827 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Anastasia Stulovad3ae87e2019-03-06 13:02:41 +00004828 if ((RefRelationship == Sema::Ref_Related &&
4829 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) ||
4830 !T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004831 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4832 return;
4833 }
4834
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004836 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004837 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004838 InitCategory.isLValue()) {
4839 Sequence.SetFailed(
4840 InitializationSequence::FK_RValueReferenceBindingToLValue);
4841 return;
4842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004844 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
Anastasia Stulovad3ae87e2019-03-06 13:02:41 +00004845
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00004846 if (T1Quals.hasAddressSpace()) {
4847 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
4848 LangAS::Default)) {
4849 Sequence.SetFailed(
4850 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
4851 return;
4852 }
Anastasia Stulovad3ae87e2019-03-06 13:02:41 +00004853 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
4854 : VK_XValue);
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00004855 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004856}
4857
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004858/// Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859/// (C++ [dcl.init.string], C99 6.7.8).
4860static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004861 const InitializedEntity &Entity,
4862 const InitializationKind &Kind,
4863 Expr *Initializer,
4864 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004865 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004866}
4867
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004868/// Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004870 const InitializedEntity &Entity,
4871 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004872 InitializationSequence &Sequence,
4873 InitListExpr *InitList) {
4874 assert((!InitList || InitList->getNumInits() == 0) &&
4875 "Shouldn't use value-init for non-empty init lists");
4876
Richard Smith1bfe0682012-02-14 21:14:13 +00004877 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004878 //
4879 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004880 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004882 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004883 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004885 if (const RecordType *RT = T->getAs<RecordType>()) {
4886 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004887 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004888 // C++98:
4889 // -- if T is a class type (clause 9) with a user-declared constructor
4890 // (12.1), then the default constructor for T is called (and the
4891 // initialization is ill-formed if T has no accessible default
4892 // constructor);
4893 // C++11:
4894 // -- if T is a class type (clause 9) with either no default constructor
4895 // (12.1 [class.ctor]) or a default constructor that is user-provided
4896 // or deleted, then the object is default-initialized;
4897 //
4898 // Note that the C++11 rule is the same as the C++98 rule if there are no
4899 // defaulted or deleted constructors, so we just use it unconditionally.
4900 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4901 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4902 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903
Richard Smith1bfe0682012-02-14 21:14:13 +00004904 // -- if T is a (possibly cv-qualified) non-union class type without a
4905 // user-provided or deleted default constructor, then the object is
4906 // zero-initialized and, if T has a non-trivial default constructor,
4907 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004908 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4909 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004910 if (NeedZeroInitialization)
4911 Sequence.AddZeroInitializationStep(Entity.getType());
4912
Richard Smith593f9932012-12-08 02:01:17 +00004913 // C++03:
4914 // -- if T is a non-union class type without a user-declared constructor,
4915 // then every non-static data member and base class component of T is
4916 // value-initialized;
4917 // [...] A program that calls for [...] value-initialization of an
4918 // entity of reference type is ill-formed.
4919 //
4920 // C++11 doesn't need this handling, because value-initialization does not
4921 // occur recursively there, and the implicit default constructor is
4922 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004923 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004924 ClassDecl->hasUninitializedReferenceMember()) {
4925 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4926 return;
4927 }
4928
Richard Smithd86812d2012-07-05 08:39:21 +00004929 // If this is list-value-initialization, pass the empty init list on when
4930 // building the constructor call. This affects the semantics of a few
4931 // things (such as whether an explicit default constructor can be called).
4932 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004933 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004934 bool InitListSyntax = InitList;
4935
Richard Smith81f5ade2016-12-15 02:28:18 +00004936 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004937 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4938 return TryConstructorInitialization(
4939 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004940 }
4941 }
4942
Douglas Gregor1b303932009-12-22 15:35:07 +00004943 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004944}
4945
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004946/// Attempt default initialization (C++ [dcl.init]p6).
Douglas Gregor85dabae2009-12-16 01:38:02 +00004947static void TryDefaultInitialization(Sema &S,
4948 const InitializedEntity &Entity,
4949 const InitializationKind &Kind,
4950 InitializationSequence &Sequence) {
4951 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004952
Douglas Gregor85dabae2009-12-16 01:38:02 +00004953 // C++ [dcl.init]p6:
4954 // To default-initialize an object of type T means:
4955 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004956 QualType DestType = S.Context.getBaseElementType(Entity.getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00004957
Douglas Gregor85dabae2009-12-16 01:38:02 +00004958 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4959 // constructor for T is called (and the initialization is ill-formed if
4960 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004961 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004962 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4963 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004964 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966
Douglas Gregor85dabae2009-12-16 01:38:02 +00004967 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968
Douglas Gregor85dabae2009-12-16 01:38:02 +00004969 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004971 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004972 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004973 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4974 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004975 return;
4976 }
4977
4978 // If the destination type has a lifetime property, zero-initialize it.
4979 if (DestType.getQualifiers().hasObjCLifetime()) {
4980 Sequence.AddZeroInitializationStep(Entity.getType());
4981 return;
4982 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004983}
4984
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004985/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004986/// which enumerates all conversion functions and performs overload resolution
4987/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004989 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004990 const InitializationKind &Kind,
4991 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004992 InitializationSequence &Sequence,
4993 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004994 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4995 QualType SourceType = Initializer->getType();
4996 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4997 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
Douglas Gregor540c3b02009-12-14 17:27:33 +00004999 // Build the candidate set directly in the initialization sequence
5000 // structure, so that it will persist if we fail.
5001 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00005002 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Anastasia Stulovac25ea862019-06-20 16:23:28 +00005003 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005004
Douglas Gregor540c3b02009-12-14 17:27:33 +00005005 // Determine whether we are allowed to call explicit constructors or
5006 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00005007 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008
Douglas Gregor540c3b02009-12-14 17:27:33 +00005009 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5010 // The type we're converting to is a class type. Enumerate its constructors
5011 // to see if there is a suitable conversion.
5012 CXXRecordDecl *DestRecordDecl
5013 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014
Douglas Gregord9848152010-04-26 14:36:57 +00005015 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00005016 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00005017 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00005018 auto Info = getConstructorInfo(D);
5019 if (!Info.Constructor)
5020 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005021
Richard Smithc2bebe92016-05-11 20:37:46 +00005022 if (!Info.Constructor->isInvalidDecl() &&
5023 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
5024 if (Info.ConstructorTmpl)
Richard Smith76b90272019-05-09 03:59:21 +00005025 S.AddTemplateOverloadCandidate(
5026 Info.ConstructorTmpl, Info.FoundDecl,
5027 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5028 /*SuppressUserConversions=*/true,
5029 /*PartialOverloading*/ false, AllowExplicit);
Douglas Gregord9848152010-04-26 14:36:57 +00005030 else
Richard Smithc2bebe92016-05-11 20:37:46 +00005031 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005032 Initializer, CandidateSet,
Richard Smith76b90272019-05-09 03:59:21 +00005033 /*SuppressUserConversions=*/true,
5034 /*PartialOverloading*/ false, AllowExplicit);
Douglas Gregord9848152010-04-26 14:36:57 +00005035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036 }
Douglas Gregord9848152010-04-26 14:36:57 +00005037 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00005038 }
Eli Friedman78275202009-12-19 08:11:05 +00005039
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005040 SourceLocation DeclLoc = Initializer->getBeginLoc();
Eli Friedman78275202009-12-19 08:11:05 +00005041
Douglas Gregor540c3b02009-12-14 17:27:33 +00005042 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5043 // The type we're converting from is a class type, enumerate its conversion
5044 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00005045
Eli Friedman4afe9a32009-12-20 22:12:03 +00005046 // We can only enumerate the conversion functions for a complete type; if
5047 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00005048 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00005049 CXXRecordDecl *SourceRecordDecl
5050 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005052 const auto &Conversions =
5053 SourceRecordDecl->getVisibleConversionFunctions();
5054 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00005055 NamedDecl *D = *I;
5056 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5057 if (isa<UsingShadowDecl>(D))
5058 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059
Eli Friedman4afe9a32009-12-20 22:12:03 +00005060 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5061 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00005062 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00005063 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00005064 else
John McCallda4458e2010-03-31 01:36:47 +00005065 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005066
Eli Friedman4afe9a32009-12-20 22:12:03 +00005067 if (AllowExplicit || !Conv->isExplicit()) {
5068 if (ConvTemplate)
Richard Smith76b90272019-05-09 03:59:21 +00005069 S.AddTemplateConversionCandidate(
5070 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5071 CandidateSet, AllowExplicit, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00005072 else
Richard Smith76b90272019-05-09 03:59:21 +00005073 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5074 DestType, CandidateSet, AllowExplicit,
Douglas Gregor68782142013-12-18 21:46:16 +00005075 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00005076 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00005077 }
5078 }
5079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080
5081 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00005082 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00005083 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00005084 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00005085 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00005087 Result);
5088 return;
5089 }
John McCall0d1da222010-01-12 00:44:57 +00005090
Douglas Gregor540c3b02009-12-14 17:27:33 +00005091 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00005092 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005093 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005094
Douglas Gregor540c3b02009-12-14 17:27:33 +00005095 if (isa<CXXConstructorDecl>(Function)) {
5096 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00005097 // subsumed by the initialization. Per DR5, the created temporary is of the
5098 // cv-unqualified type of the destination.
5099 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5100 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005101 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00005102
5103 // C++14 and before:
5104 // - if the function is a constructor, the call initializes a temporary
5105 // of the cv-unqualified version of the destination type. The [...]
5106 // temporary [...] is then used to direct-initialize, according to the
5107 // rules above, the object that is the destination of the
5108 // copy-initialization.
5109 // Note that this just performs a simple object copy from the temporary.
5110 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005111 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00005112 // - if the function is a constructor, the call is a prvalue of the
5113 // cv-unqualified version of the destination type whose return object
5114 // is initialized by the constructor. The call is used to
5115 // direct-initialize, according to the rules above, the object that
5116 // is the destination of the copy-initialization.
5117 // Therefore we need to do nothing further.
5118 //
5119 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005120 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00005121 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00005122 else if (DestType.hasQualifiers())
5123 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00005124 return;
5125 }
5126
5127 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005128 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005129 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5130 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005131
Richard Smithb8c0f552016-12-09 18:49:13 +00005132 if (ConvType->getAs<RecordType>()) {
5133 // The call is used to direct-initialize [...] the object that is the
5134 // destination of the copy-initialization.
5135 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005136 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00005137 // - If the initializer expression is a prvalue and the cv-unqualified
5138 // version of the source type is the same as the class of the
5139 // destination [... do not make an extra copy]
5140 //
5141 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005142 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00005143 Function->getReturnType()->isReferenceType() ||
5144 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5145 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00005146 else if (!S.Context.hasSameType(ConvType, DestType))
5147 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00005148 return;
5149 }
5150
Douglas Gregor5ab11652010-04-17 22:01:05 +00005151 // If the conversion following the call to the conversion function
5152 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00005153 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5154 Best->FinalConversion.Third) {
5155 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00005156 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00005157 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005158 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00005159 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005160}
5161
Richard Smithf032001b2013-06-20 02:18:31 +00005162/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5163/// a function with a pointer return type contains a 'return false;' statement.
5164/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5165/// code using that header.
5166///
5167/// Work around this by treating 'return false;' as zero-initializing the result
5168/// if it's used in a pointer-returning function in a system header.
5169static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5170 const InitializedEntity &Entity,
5171 const Expr *Init) {
5172 return S.getLangOpts().CPlusPlus11 &&
5173 Entity.getKind() == InitializedEntity::EK_Result &&
5174 Entity.getType()->isPointerType() &&
5175 isa<CXXBoolLiteralExpr>(Init) &&
5176 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5177 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5178}
5179
John McCall31168b02011-06-15 23:02:42 +00005180/// The non-zero enum values here are indexes into diagnostic alternatives.
5181enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5182
5183/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00005184static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005185 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00005186 // Skip parens.
5187 e = e->IgnoreParens();
5188
5189 // Skip address-of nodes.
5190 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5191 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005192 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5193 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005194
5195 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005196 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5197 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005198 case CK_Dependent:
5199 case CK_BitCast:
5200 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005201 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005202 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005203
5204 case CK_ArrayToPointerDecay:
5205 return IIK_nonscalar;
5206
5207 case CK_NullToPointer:
5208 return IIK_okay;
5209
5210 default:
5211 break;
5212 }
5213
5214 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005215 } else if (isa<DeclRefExpr>(e)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005216 // set isWeakAccess to true, to mean that there will be an implicit
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005217 // load which requires a cleanup.
5218 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5219 isWeakAccess = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00005220
John McCall63f84442011-06-27 23:59:58 +00005221 if (!isAddressOf) return IIK_nonlocal;
5222
John McCall113bee02012-03-10 09:33:50 +00005223 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5224 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005225
5226 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005227
5228 // If we have a conditional operator, check both sides.
5229 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005230 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5231 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005232 return iik;
5233
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005234 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005235
5236 // These are never scalar.
5237 } else if (isa<ArraySubscriptExpr>(e)) {
5238 return IIK_nonscalar;
5239
5240 // Otherwise, it needs to be a null pointer constant.
5241 } else {
5242 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5243 ? IIK_okay : IIK_nonlocal);
5244 }
5245
5246 return IIK_nonlocal;
5247}
5248
5249/// Check whether the given expression is a valid operand for an
5250/// indirect copy/restore.
5251static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5252 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005253 bool isWeakAccess = false;
5254 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
Fangrui Song6907ce22018-07-30 19:24:48 +00005255 // If isWeakAccess to true, there will be an implicit
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005256 // load which requires a cleanup.
5257 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005258 S.Cleanup.setExprNeedsCleanups(true);
5259
John McCall31168b02011-06-15 23:02:42 +00005260 if (iik == IIK_okay) return;
5261
5262 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5263 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5264 << src->getSourceRange();
5265}
5266
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005267/// Determine whether we have compatible array types for the
Douglas Gregore2f943b2011-02-22 18:29:51 +00005268/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005269static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005270 const ArrayType *Source) {
5271 // If the source and destination array types are equivalent, we're
5272 // done.
5273 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5274 return true;
5275
5276 // Make sure that the element types are the same.
5277 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5278 return false;
5279
5280 // The only mismatch we allow is when the destination is an
5281 // incomplete array type and the source is a constant array type.
5282 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5283}
5284
John McCall31168b02011-06-15 23:02:42 +00005285static bool tryObjCWritebackConversion(Sema &S,
5286 InitializationSequence &Sequence,
5287 const InitializedEntity &Entity,
5288 Expr *Initializer) {
5289 bool ArrayDecay = false;
5290 QualType ArgType = Initializer->getType();
5291 QualType ArgPointee;
5292 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5293 ArrayDecay = true;
5294 ArgPointee = ArgArrayType->getElementType();
5295 ArgType = S.Context.getPointerType(ArgPointee);
5296 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005297
John McCall31168b02011-06-15 23:02:42 +00005298 // Handle write-back conversion.
5299 QualType ConvertedArgType;
5300 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5301 ConvertedArgType))
5302 return false;
5303
5304 // We should copy unless we're passing to an argument explicitly
5305 // marked 'out'.
5306 bool ShouldCopy = true;
5307 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5308 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5309
5310 // Do we need an lvalue conversion?
5311 if (ArrayDecay || Initializer->isGLValue()) {
5312 ImplicitConversionSequence ICS;
5313 ICS.setStandard();
5314 ICS.Standard.setAsIdentityConversion();
5315
5316 QualType ResultType;
5317 if (ArrayDecay) {
5318 ICS.Standard.First = ICK_Array_To_Pointer;
5319 ResultType = S.Context.getPointerType(ArgPointee);
5320 } else {
5321 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5322 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5323 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005324
John McCall31168b02011-06-15 23:02:42 +00005325 Sequence.AddConversionSequenceStep(ICS, ResultType);
5326 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005327
John McCall31168b02011-06-15 23:02:42 +00005328 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5329 return true;
5330}
5331
Guy Benyei61054192013-02-07 10:55:47 +00005332static bool TryOCLSamplerInitialization(Sema &S,
5333 InitializationSequence &Sequence,
5334 QualType DestType,
5335 Expr *Initializer) {
5336 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005337 (!Initializer->isIntegerConstantExpr(S.Context) &&
5338 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005339 return false;
5340
5341 Sequence.AddOCLSamplerInitStep(DestType);
5342 return true;
5343}
5344
Andrew Savonichev3fee3512018-11-08 11:25:41 +00005345static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5346 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5347 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5348}
5349
Andrew Savonichevb555b762018-10-23 15:19:20 +00005350static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5351 InitializationSequence &Sequence,
5352 QualType DestType,
5353 Expr *Initializer) {
5354 if (!S.getLangOpts().OpenCL)
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005355 return false;
5356
Andrew Savonichevb555b762018-10-23 15:19:20 +00005357 //
5358 // OpenCL 1.2 spec, s6.12.10
5359 //
5360 // The event argument can also be used to associate the
5361 // async_work_group_copy with a previous async copy allowing
5362 // an event to be shared by multiple async copies; otherwise
5363 // event should be zero.
5364 //
5365 if (DestType->isEventT() || DestType->isQueueT()) {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00005366 if (!IsZeroInitializer(Initializer, S))
5367 return false;
5368
5369 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5370 return true;
5371 }
5372
5373 // We should allow zero initialization for all types defined in the
5374 // cl_intel_device_side_avc_motion_estimation extension, except
5375 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5376 if (S.getOpenCLOptions().isEnabled(
5377 "cl_intel_device_side_avc_motion_estimation") &&
5378 DestType->isOCLIntelSubgroupAVCType()) {
5379 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5380 DestType->isOCLIntelSubgroupAVCMceResultType())
5381 return false;
5382 if (!IsZeroInitializer(Initializer, S))
Andrew Savonichevb555b762018-10-23 15:19:20 +00005383 return false;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005384
Andrew Savonichevb555b762018-10-23 15:19:20 +00005385 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5386 return true;
5387 }
Egor Churaev89831422016-12-23 14:55:49 +00005388
Andrew Savonichevb555b762018-10-23 15:19:20 +00005389 return false;
Egor Churaev89831422016-12-23 14:55:49 +00005390}
5391
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005392InitializationSequence::InitializationSequence(Sema &S,
5393 const InitializedEntity &Entity,
5394 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005395 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005396 bool TopLevelOfInitList,
5397 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005398 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005399 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5400 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005401}
5402
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005403/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5404/// address of that function, this returns true. Otherwise, it returns false.
5405static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5406 auto *DRE = dyn_cast<DeclRefExpr>(E);
5407 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5408 return false;
5409
5410 return !S.checkAddressOfFunctionIsAvailable(
5411 cast<FunctionDecl>(DRE->getDecl()));
5412}
5413
Richard Smith410306b2016-12-12 02:53:20 +00005414/// Determine whether we can perform an elementwise array copy for this kind
5415/// of entity.
5416static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5417 switch (Entity.getKind()) {
5418 case InitializedEntity::EK_LambdaCapture:
5419 // C++ [expr.prim.lambda]p24:
5420 // For array members, the array elements are direct-initialized in
5421 // increasing subscript order.
5422 return true;
5423
5424 case InitializedEntity::EK_Variable:
5425 // C++ [dcl.decomp]p1:
5426 // [...] each element is copy-initialized or direct-initialized from the
5427 // corresponding element of the assignment-expression [...]
5428 return isa<DecompositionDecl>(Entity.getDecl());
5429
5430 case InitializedEntity::EK_Member:
5431 // C++ [class.copy.ctor]p14:
5432 // - if the member is an array, each element is direct-initialized with
5433 // the corresponding subobject of x
5434 return Entity.isImplicitMemberInitializer();
5435
5436 case InitializedEntity::EK_ArrayElement:
5437 // All the above cases are intended to apply recursively, even though none
5438 // of them actually say that.
5439 if (auto *E = Entity.getParent())
5440 return canPerformArrayCopy(*E);
5441 break;
5442
5443 default:
5444 break;
5445 }
5446
5447 return false;
5448}
5449
Richard Smith089c3162013-09-21 21:55:46 +00005450void InitializationSequence::InitializeFrom(Sema &S,
5451 const InitializedEntity &Entity,
5452 const InitializationKind &Kind,
5453 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005454 bool TopLevelOfInitList,
5455 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005456 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005457
John McCall5e77d762013-04-16 07:28:30 +00005458 // Eliminate non-overload placeholder types in the arguments. We
5459 // need to do this before checking whether types are dependent
5460 // because lowering a pseudo-object expression might well give us
5461 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005462 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005463 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5464 // FIXME: should we be doing this here?
5465 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5466 if (result.isInvalid()) {
5467 SetFailed(FK_PlaceholderType);
5468 return;
5469 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005470 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005471 }
5472
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005473 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005474 // The semantics of initializers are as follows. The destination type is
5475 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005476 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005477 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005478 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005479 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005480
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005481 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005482 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005483 SequenceKind = DependentSequence;
5484 return;
5485 }
5486
Sebastian Redld201edf2011-06-05 13:59:11 +00005487 // Almost everything is a normal sequence.
5488 setSequenceKind(NormalSequence);
5489
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005490 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005491 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005492 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005493 Initializer = Args[0];
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005494 if (S.getLangOpts().ObjC) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005495 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005496 DestType, Initializer->getType(),
5497 Initializer) ||
5498 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5499 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005500 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005501 if (!isa<InitListExpr>(Initializer))
5502 SourceType = Initializer->getType();
5503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005504
Sebastian Redl0501c632012-02-12 16:37:36 +00005505 // - If the initializer is a (non-parenthesized) braced-init-list, the
5506 // object is list-initialized (8.5.4).
5507 if (Kind.getKind() != InitializationKind::IK_Direct) {
5508 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005509 TryListInitialization(S, Entity, Kind, InitList, *this,
5510 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005511 return;
5512 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005515 // - If the destination type is a reference type, see 8.5.3.
5516 if (DestType->isReferenceType()) {
5517 // C++0x [dcl.init.ref]p1:
5518 // A variable declared to be a T& or T&&, that is, "reference to type T"
5519 // (8.3.2), shall be initialized by an object, or function, of type T or
5520 // by an object that can be converted into a T.
5521 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005522 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005523 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005524 // C++17 [dcl.init.ref]p5:
5525 // A reference [...] is initialized by an expression [...] as follows:
5526 // If the initializer is not an expression, presumably we should reject,
5527 // but the standard fails to actually say so.
5528 else if (isa<InitListExpr>(Args[0]))
5529 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005530 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005531 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005532 return;
5533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005535 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005536 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005537 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005538 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005539 return;
5540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005541
Douglas Gregor85dabae2009-12-16 01:38:02 +00005542 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005543 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005544 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005545 return;
5546 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005547
John McCall66884dd2011-02-21 07:22:22 +00005548 // - If the destination type is an array of characters, an array of
5549 // char16_t, an array of char32_t, or an array of wchar_t, and the
5550 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005551 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005552 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005553 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005554 if (Initializer && isa<VariableArrayType>(DestAT)) {
5555 SetFailed(FK_VariableLengthArrayHasInitializer);
5556 return;
5557 }
5558
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005559 if (Initializer) {
5560 switch (IsStringInit(Initializer, DestAT, Context)) {
5561 case SIF_None:
5562 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5563 return;
5564 case SIF_NarrowStringIntoWideChar:
5565 SetFailed(FK_NarrowStringIntoWideCharArray);
5566 return;
5567 case SIF_WideStringIntoChar:
5568 SetFailed(FK_WideStringIntoCharArray);
5569 return;
5570 case SIF_IncompatWideStringIntoWideChar:
5571 SetFailed(FK_IncompatWideStringIntoWideChar);
5572 return;
Richard Smith3a8244d2018-05-01 05:02:45 +00005573 case SIF_PlainStringIntoUTF8Char:
5574 SetFailed(FK_PlainStringIntoUTF8Char);
5575 return;
5576 case SIF_UTF8StringIntoPlainChar:
5577 SetFailed(FK_UTF8StringIntoPlainChar);
5578 return;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005579 case SIF_Other:
5580 break;
5581 }
John McCall66884dd2011-02-21 07:22:22 +00005582 }
5583
Richard Smith410306b2016-12-12 02:53:20 +00005584 // Some kinds of initialization permit an array to be initialized from
5585 // another array of the same type, and perform elementwise initialization.
5586 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5587 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5588 Entity.getType()) &&
5589 canPerformArrayCopy(Entity)) {
5590 // If source is a prvalue, use it directly.
5591 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005592 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005593 return;
5594 }
5595
5596 // Emit element-at-a-time copy loop.
5597 InitializedEntity Element =
5598 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5599 QualType InitEltT =
5600 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005601 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5602 Initializer->getValueKind(),
5603 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005604 Expr *OVEAsExpr = &OVE;
5605 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5606 TreatUnavailableAsInvalid);
5607 if (!Failed())
5608 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5609 return;
5610 }
5611
Douglas Gregore2f943b2011-02-22 18:29:51 +00005612 // Note: as an GNU C extension, we allow initialization of an
5613 // array from a compound literal that creates an array of the same
5614 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005615 if (!S.getLangOpts().CPlusPlus && Initializer &&
Eli Friedman88fccbd2019-02-11 22:54:27 +00005616 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005617 Initializer->getType()->isArrayType()) {
5618 const ArrayType *SourceAT
5619 = Context.getAsArrayType(Initializer->getType());
5620 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005621 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005622 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005623 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005624 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005625 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005626 }
Richard Smithebeed412012-02-15 22:38:09 +00005627 }
Richard Smithd86812d2012-07-05 08:39:21 +00005628 // Note: as a GNU C++ extension, we allow list-initialization of a
5629 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005630 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005631 Entity.getKind() == InitializedEntity::EK_Member &&
5632 Initializer && isa<InitListExpr>(Initializer)) {
5633 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005634 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005635 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005636 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005637 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005638 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5639 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005640 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005641 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005642
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005643 return;
5644 }
Eli Friedman78275202009-12-19 08:11:05 +00005645
Larisse Voufod2010992015-01-24 23:09:54 +00005646 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005647 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005648 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005649 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005650
Neil Hickey8ece3b62019-07-16 14:57:32 +00005651 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5652 return;
5653
John McCall31168b02011-06-15 23:02:42 +00005654 // We're at the end of the line for C: it's either a write-back conversion
5655 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005656 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005657 // If allowed, check whether this is an Objective-C writeback conversion.
5658 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005659 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005660 return;
5661 }
Guy Benyei61054192013-02-07 10:55:47 +00005662
Andrew Savonichevb555b762018-10-23 15:19:20 +00005663 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005664 return;
5665
John McCall31168b02011-06-15 23:02:42 +00005666 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005667 AddCAssignmentStep(DestType);
5668 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005669 return;
5670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671
David Blaikiebbafb8a2012-03-11 07:00:24 +00005672 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005673
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005674 // - If the destination type is a (possibly cv-qualified) class type:
5675 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005676 // - If the initialization is direct-initialization, or if it is
5677 // copy-initialization where the cv-unqualified version of the
5678 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005679 // class of the destination, constructors are considered. [...]
5680 if (Kind.getKind() == InitializationKind::IK_Direct ||
5681 (Kind.getKind() == InitializationKind::IK_Copy &&
5682 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005683 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005684 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005685 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005687 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005688 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005689 // used) to a derived class thereof are enumerated as described in
5690 // 13.3.1.4, and the best one is chosen through overload resolution
5691 // (13.3).
5692 else
Richard Smith77be48a2014-07-31 06:31:19 +00005693 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005694 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005695 return;
5696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005697
Richard Smith49a6b6e2017-03-24 01:14:25 +00005698 assert(Args.size() >= 1 && "Zero-argument case handled above");
5699
5700 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005701 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005702 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005703 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005704 } else if (isa<InitListExpr>(Args[0])) {
5705 SetFailed(FK_ParenthesizedListInitForScalar);
5706 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005708
5709 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005710 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005711 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005712 // For a conversion to _Atomic(T) from either T or a class type derived
5713 // from T, initialize the T object then convert to _Atomic type.
5714 bool NeedAtomicConversion = false;
5715 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5716 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005717 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
Richard Smith0f59cb32015-12-18 21:45:41 +00005718 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005719 DestType = Atomic->getValueType();
5720 NeedAtomicConversion = true;
5721 }
5722 }
5723
5724 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005725 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005726 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005727 if (!Failed() && NeedAtomicConversion)
5728 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005729 return;
5730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005731
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005732 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005733 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005734 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005735 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005736 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005737
John McCall31168b02011-06-15 23:02:42 +00005738 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005739 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005740 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005741 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005742 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005743 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5744 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005745
5746 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005747 ICS.Standard.Second == ICK_Writeback_Conversion) {
5748 // Objective-C ARC writeback conversion.
Fangrui Song6907ce22018-07-30 19:24:48 +00005749
John McCall31168b02011-06-15 23:02:42 +00005750 // We should copy unless we're passing to an argument explicitly
5751 // marked 'out'.
5752 bool ShouldCopy = true;
5753 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5754 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
Fangrui Song6907ce22018-07-30 19:24:48 +00005755
John McCall31168b02011-06-15 23:02:42 +00005756 // If there was an lvalue adjustment, add it as a separate conversion.
5757 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5758 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5759 ImplicitConversionSequence LvalueICS;
5760 LvalueICS.setStandard();
5761 LvalueICS.Standard.setAsIdentityConversion();
5762 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5763 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005764 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005765 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005766
Richard Smith77be48a2014-07-31 06:31:19 +00005767 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005768 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005769 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005770 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5771 AddZeroInitializationStep(Entity.getType());
5772 } else if (Initializer->getType() == Context.OverloadTy &&
5773 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5774 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005775 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005776 else if (Initializer->getType()->isFunctionType() &&
5777 isExprAnUnaddressableFunction(S, Initializer))
5778 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005779 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005780 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005781 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005782 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005783
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005784 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005785 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005786}
5787
5788InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005789 for (auto &S : Steps)
5790 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005791}
5792
5793//===----------------------------------------------------------------------===//
5794// Perform initialization
5795//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005796static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005797getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005798 switch(Entity.getKind()) {
5799 case InitializedEntity::EK_Variable:
5800 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005801 case InitializedEntity::EK_Exception:
5802 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005803 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005804 return Sema::AA_Initializing;
5805
5806 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005807 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005808 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5809 return Sema::AA_Sending;
5810
Douglas Gregore1314a62009-12-18 05:02:21 +00005811 return Sema::AA_Passing;
5812
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005813 case InitializedEntity::EK_Parameter_CF_Audited:
5814 if (Entity.getDecl() &&
5815 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5816 return Sema::AA_Sending;
Fangrui Song6907ce22018-07-30 19:24:48 +00005817
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005818 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
Fangrui Song6907ce22018-07-30 19:24:48 +00005819
Douglas Gregore1314a62009-12-18 05:02:21 +00005820 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005821 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
Douglas Gregore1314a62009-12-18 05:02:21 +00005822 return Sema::AA_Returning;
5823
Douglas Gregore1314a62009-12-18 05:02:21 +00005824 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005825 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005826 // FIXME: Can we tell apart casting vs. converting?
5827 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005828
Douglas Gregore1314a62009-12-18 05:02:21 +00005829 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005830 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005831 case InitializedEntity::EK_ArrayElement:
5832 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005833 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005834 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005835 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005836 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005837 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005838 return Sema::AA_Initializing;
5839 }
5840
David Blaikie8a40f702012-01-17 06:56:22 +00005841 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005842}
5843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005844/// Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005845/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005846static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005847 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005848 case InitializedEntity::EK_ArrayElement:
5849 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005850 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005851 case InitializedEntity::EK_StmtExprResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005852 case InitializedEntity::EK_New:
5853 case InitializedEntity::EK_Variable:
5854 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005855 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005856 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005857 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005858 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005859 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005860 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005861 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005862 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005863 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005864
Douglas Gregore1314a62009-12-18 05:02:21 +00005865 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005866 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005867 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005868 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005869 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005870 return true;
5871 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005872
Douglas Gregore1314a62009-12-18 05:02:21 +00005873 llvm_unreachable("missed an InitializedEntity kind?");
5874}
5875
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005876/// Whether the given entity, when initialized with an object
Douglas Gregor95562572010-04-24 23:45:46 +00005877/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005878static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005879 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005880 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005881 case InitializedEntity::EK_StmtExprResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005882 case InitializedEntity::EK_New:
5883 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005884 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005885 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005886 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005887 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005888 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005889 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005890 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005891
Richard Smith27874d62013-01-08 00:08:23 +00005892 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005893 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005894 case InitializedEntity::EK_Variable:
5895 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005896 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005897 case InitializedEntity::EK_Temporary:
5898 case InitializedEntity::EK_ArrayElement:
5899 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005900 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005901 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005902 return true;
5903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005904
5905 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005906}
5907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005908/// Get the location at which initialization diagnostics should appear.
Richard Smithc620f552011-10-19 16:55:56 +00005909static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5910 Expr *Initializer) {
5911 switch (Entity.getKind()) {
5912 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005913 case InitializedEntity::EK_StmtExprResult:
Richard Smithc620f552011-10-19 16:55:56 +00005914 return Entity.getReturnLoc();
5915
5916 case InitializedEntity::EK_Exception:
5917 return Entity.getThrowLoc();
5918
5919 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005920 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005921 return Entity.getDecl()->getLocation();
5922
Douglas Gregor19666fb2012-02-15 16:57:26 +00005923 case InitializedEntity::EK_LambdaCapture:
5924 return Entity.getCaptureLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00005925
Richard Smithc620f552011-10-19 16:55:56 +00005926 case InitializedEntity::EK_ArrayElement:
5927 case InitializedEntity::EK_Member:
5928 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005929 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005930 case InitializedEntity::EK_Temporary:
5931 case InitializedEntity::EK_New:
5932 case InitializedEntity::EK_Base:
5933 case InitializedEntity::EK_Delegating:
5934 case InitializedEntity::EK_VectorElement:
5935 case InitializedEntity::EK_ComplexElement:
5936 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005937 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005938 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005939 case InitializedEntity::EK_RelatedResult:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005940 return Initializer->getBeginLoc();
Richard Smithc620f552011-10-19 16:55:56 +00005941 }
5942 llvm_unreachable("missed an InitializedEntity kind?");
5943}
5944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005945/// Make a (potentially elidable) temporary copy of the object
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005946/// provided by the given initializer by calling the appropriate copy
5947/// constructor.
5948///
5949/// \param S The Sema object used for type-checking.
5950///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005951/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005952/// the type of the initializer expression or a superclass thereof.
5953///
James Dennett634962f2012-06-14 21:40:34 +00005954/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005955///
5956/// \param CurInit The initializer expression.
5957///
5958/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5959/// is permitted in C++03 (but not C++0x) when binding a reference to
5960/// an rvalue.
5961///
5962/// \returns An expression that copies the initializer expression into
5963/// a temporary object, or an error expression if a copy could not be
5964/// created.
John McCalldadc5752010-08-24 06:29:42 +00005965static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005966 QualType T,
5967 const InitializedEntity &Entity,
5968 ExprResult CurInit,
5969 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005970 if (CurInit.isInvalid())
5971 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005972 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005973 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005974 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005975 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005976 Class = cast<CXXRecordDecl>(Record->getDecl());
5977 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005978 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005979
Richard Smithc620f552011-10-19 16:55:56 +00005980 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005981
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005982 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005983 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005984 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005985
Richard Smith7c2bcc92016-09-07 02:14:33 +00005986 // Perform overload resolution using the class's constructors. Per
5987 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005988 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005989 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005990 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005991
Douglas Gregore1314a62009-12-18 05:02:21 +00005992 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005993 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005994 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005995 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5996 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5997 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005998 case OR_Success:
5999 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006000
Douglas Gregore1314a62009-12-18 05:02:21 +00006001 case OR_No_Viable_Function:
David Blaikie5e328052019-05-03 00:44:50 +00006002 CandidateSet.NoteCandidates(
6003 PartialDiagnosticAt(
6004 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6005 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6006 : diag::err_temp_copy_no_viable)
6007 << (int)Entity.getKind() << CurInitExpr->getType()
6008 << CurInitExpr->getSourceRange()),
6009 S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00006010 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00006011 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006012 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006013
Douglas Gregore1314a62009-12-18 05:02:21 +00006014 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00006015 CandidateSet.NoteCandidates(
6016 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6017 << (int)Entity.getKind()
6018 << CurInitExpr->getType()
6019 << CurInitExpr->getSourceRange()),
6020 S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00006021 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006022
Douglas Gregore1314a62009-12-18 05:02:21 +00006023 case OR_Deleted:
6024 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00006025 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00006026 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00006027 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00006028 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006029 }
6030
Richard Smith7c2bcc92016-09-07 02:14:33 +00006031 bool HadMultipleCandidates = CandidateSet.size() > 1;
6032
Douglas Gregor5ab11652010-04-17 22:01:05 +00006033 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00006034 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006035 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006036
Richard Smith5179eb72016-06-28 19:03:57 +00006037 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6038 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006039
6040 if (IsExtraneousCopy) {
6041 // If this is a totally extraneous copy for C++03 reference
6042 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00006043 // expression. We don't generate an (elided) copy operation here
6044 // because doing so would require us to pass down a flag to avoid
6045 // infinite recursion, where each step adds another extraneous,
6046 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006047
Douglas Gregor30b52772010-04-18 07:57:34 +00006048 // Instantiate the default arguments of any extra parameters in
6049 // the selected copy constructor, as if we were going to create a
6050 // proper call to the copy constructor.
6051 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6052 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6053 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006054 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00006055 break;
6056
6057 // Build the default argument expression; we don't actually care
6058 // if this succeeds or not, because this routine will complain
6059 // if there was a problem.
6060 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6061 }
6062
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006063 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006065
Douglas Gregor5ab11652010-04-17 22:01:05 +00006066 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006067 // constructor call (we might have derived-to-base conversions, or
6068 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006069 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006070 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006071
Richard Smith7c2bcc92016-09-07 02:14:33 +00006072 // C++0x [class.copy]p32:
6073 // When certain criteria are met, an implementation is allowed to
6074 // omit the copy/move construction of a class object, even if the
6075 // copy/move constructor and/or destructor for the object have
6076 // side effects. [...]
6077 // - when a temporary class object that has not been bound to a
6078 // reference (12.2) would be copied/moved to a class object
6079 // with the same cv-unqualified type, the copy/move operation
6080 // can be omitted by constructing the temporary object
6081 // directly into the target of the omitted copy/move
6082 //
6083 // Note that the other three bullets are handled elsewhere. Copy
6084 // elision for return statements and throw expressions are handled as part
6085 // of constructor initialization, while copy elision for exception handlers
6086 // is handled by the run-time.
6087 //
6088 // FIXME: If the function parameter is not the same type as the temporary, we
6089 // should still be able to elide the copy, but we don't have a way to
6090 // represent in the AST how much should be elided in this case.
6091 bool Elidable =
6092 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6093 S.Context.hasSameUnqualifiedType(
6094 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6095 CurInitExpr->getType());
6096
Douglas Gregord0ace022010-04-25 00:55:24 +00006097 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00006098 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
6099 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006100 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006101 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006102 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006103 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006104 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006105 CXXConstructExpr::CK_Complete,
6106 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006107
Douglas Gregord0ace022010-04-25 00:55:24 +00006108 // If we're supposed to bind temporaries, do so.
6109 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006110 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006111 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006112}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006113
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006114/// Check whether elidable copy construction for binding a reference to
Richard Smithc620f552011-10-19 16:55:56 +00006115/// a temporary would have succeeded if we were building in C++98 mode, for
6116/// -Wc++98-compat.
6117static void CheckCXX98CompatAccessibleCopy(Sema &S,
6118 const InitializedEntity &Entity,
6119 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006120 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00006121
6122 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6123 if (!Record)
6124 return;
6125
6126 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006127 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00006128 return;
6129
6130 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00006131 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00006132 DeclContext::lookup_result Ctors =
6133 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00006134
6135 // Perform overload resolution.
6136 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00006137 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00006138 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00006139 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6140 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6141 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00006142
6143 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6144 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6145 << CurInitExpr->getSourceRange();
6146
6147 switch (OR) {
6148 case OR_Success:
6149 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00006150 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00006151 // FIXME: Check default arguments as far as that's possible.
6152 break;
6153
6154 case OR_No_Viable_Function:
David Blaikie5e328052019-05-03 00:44:50 +00006155 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6156 OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00006157 break;
6158
6159 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00006160 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6161 OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00006162 break;
6163
6164 case OR_Deleted:
6165 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00006166 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00006167 break;
6168 }
6169}
6170
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006171void InitializationSequence::PrintInitLocationNote(Sema &S,
6172 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006173 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006174 if (Entity.getDecl()->getLocation().isInvalid())
6175 return;
6176
6177 if (Entity.getDecl()->getDeclName())
6178 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6179 << Entity.getDecl()->getDeclName();
6180 else
6181 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6182 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006183 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6184 Entity.getMethodDecl())
6185 S.Diag(Entity.getMethodDecl()->getLocation(),
6186 diag::note_method_return_type_change)
6187 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006188}
6189
Jordan Rose6c0505e2013-05-06 16:48:12 +00006190/// Returns true if the parameters describe a constructor initialization of
6191/// an explicit temporary object, e.g. "Point(x, y)".
6192static bool isExplicitTemporary(const InitializedEntity &Entity,
6193 const InitializationKind &Kind,
6194 unsigned NumArgs) {
6195 switch (Entity.getKind()) {
6196 case InitializedEntity::EK_Temporary:
6197 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006198 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006199 break;
6200 default:
6201 return false;
6202 }
6203
6204 switch (Kind.getKind()) {
6205 case InitializationKind::IK_DirectList:
6206 return true;
6207 // FIXME: Hack to work around cast weirdness.
6208 case InitializationKind::IK_Direct:
6209 case InitializationKind::IK_Value:
6210 return NumArgs != 1;
6211 default:
6212 return false;
6213 }
6214}
6215
Sebastian Redled2e5322011-12-22 14:44:04 +00006216static ExprResult
6217PerformConstructorInitialization(Sema &S,
6218 const InitializedEntity &Entity,
6219 const InitializationKind &Kind,
6220 MultiExprArg Args,
6221 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006222 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006223 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006224 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006225 SourceLocation LBraceLoc,
6226 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006227 unsigned NumArgs = Args.size();
6228 CXXConstructorDecl *Constructor
6229 = cast<CXXConstructorDecl>(Step.Function.Function);
6230 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6231
6232 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006233 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006234 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6235 ? Kind.getEqualLoc()
6236 : Kind.getLocation();
6237
6238 if (Kind.getKind() == InitializationKind::IK_Default) {
6239 // Force even a trivial, implicit default constructor to be
6240 // semantically checked. We do this explicitly because we don't build
6241 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006242 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006243 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006244 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006245 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6246 }
6247
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006248 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006249
Douglas Gregor6073dca2012-02-24 23:56:31 +00006250 // C++ [over.match.copy]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00006251 // - When initializing a temporary to be bound to the first parameter
6252 // of a constructor that takes a reference to possibly cv-qualified
6253 // T as its first argument, called with a single argument in the
Douglas Gregor6073dca2012-02-24 23:56:31 +00006254 // context of direct-initialization, explicit conversion functions
6255 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006256 bool AllowExplicitConv =
6257 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6258 hasCopyOrMoveCtorParam(S.Context,
6259 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006260
Sebastian Redled2e5322011-12-22 14:44:04 +00006261 // Determine the arguments required to actually perform the constructor
6262 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006263 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006264 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006265 AllowExplicitConv,
6266 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006267 return ExprError();
6268
6269
Jordan Rose6c0505e2013-05-06 16:48:12 +00006270 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006271 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006272 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6273 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006274
6275 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6276 if (!TSInfo)
6277 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumarc9a95312018-11-19 20:10:21 +00006278 SourceRange ParenOrBraceRange =
6279 (Kind.getKind() == InitializationKind::IK_DirectList)
6280 ? SourceRange(LBraceLoc, RBraceLoc)
6281 : Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006282
Richard Smith5179eb72016-06-28 19:03:57 +00006283 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006284 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006285 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006286 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6287 return ExprError();
6288 }
Richard Smith5179eb72016-06-28 19:03:57 +00006289 S.MarkFunctionReferenced(Loc, Constructor);
6290
Bruno Ricciddb8f6b2018-12-22 14:39:30 +00006291 CurInit = CXXTemporaryObjectExpr::Create(
Richard Smith60437622017-02-09 19:17:44 +00006292 S.Context, Constructor,
6293 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006294 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6295 IsListInitialization, IsStdInitListInitialization,
6296 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006297 } else {
6298 CXXConstructExpr::ConstructionKind ConstructKind =
6299 CXXConstructExpr::CK_Complete;
6300
6301 if (Entity.getKind() == InitializedEntity::EK_Base) {
6302 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6303 CXXConstructExpr::CK_VirtualBase :
6304 CXXConstructExpr::CK_NonVirtualBase;
6305 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6306 ConstructKind = CXXConstructExpr::CK_Delegating;
6307 }
6308
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006309 // Only get the parenthesis or brace range if it is a list initialization or
6310 // direct construction.
6311 SourceRange ParenOrBraceRange;
6312 if (IsListInitialization)
6313 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6314 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006315 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006316
6317 // If the entity allows NRVO, mark the construction as elidable
6318 // unconditionally.
6319 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006320 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006321 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006322 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006323 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006324 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006325 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006326 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006327 ConstructorInitRequiresZeroInit,
6328 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006329 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006330 else
Richard Smith410306b2016-12-12 02:53:20 +00006331 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006332 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006333 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006334 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006335 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006336 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006337 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006338 ConstructorInitRequiresZeroInit,
6339 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006340 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006341 }
6342 if (CurInit.isInvalid())
6343 return ExprError();
6344
6345 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006346 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006347 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6348 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006349
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00006350 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
6351 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
6352 return ExprError();
6353
Sebastian Redled2e5322011-12-22 14:44:04 +00006354 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006355 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006356
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006357 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006358}
6359
Richard Smithd87aab92018-07-17 22:24:09 +00006360namespace {
6361enum LifetimeKind {
6362 /// The lifetime of a temporary bound to this entity ends at the end of the
6363 /// full-expression, and that's (probably) fine.
6364 LK_FullExpression,
6365
6366 /// The lifetime of a temporary bound to this entity is extended to the
6367 /// lifeitme of the entity itself.
6368 LK_Extended,
6369
6370 /// The lifetime of a temporary bound to this entity probably ends too soon,
6371 /// because the entity is allocated in a new-expression.
6372 LK_New,
6373
6374 /// The lifetime of a temporary bound to this entity ends too soon, because
6375 /// the entity is a return object.
6376 LK_Return,
6377
Richard Smith67af95b2018-07-23 19:19:08 +00006378 /// The lifetime of a temporary bound to this entity ends too soon, because
6379 /// the entity is the result of a statement expression.
6380 LK_StmtExprResult,
6381
Richard Smithd87aab92018-07-17 22:24:09 +00006382 /// This is a mem-initializer: if it would extend a temporary (other than via
6383 /// a default member initializer), the program is ill-formed.
6384 LK_MemInitializer,
6385};
6386using LifetimeResult =
6387 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6388}
6389
Richard Smithe6c01442013-06-05 00:46:14 +00006390/// Determine the declaration which an initialized entity ultimately refers to,
6391/// for the purpose of lifetime-extending a temporary bound to a reference in
6392/// the initialization of \p Entity.
Richard Smithca975b22018-07-23 18:50:26 +00006393static LifetimeResult getEntityLifetime(
David Majnemerdaff3702014-05-01 17:50:17 +00006394 const InitializedEntity *Entity,
Richard Smithd87aab92018-07-17 22:24:09 +00006395 const InitializedEntity *InitField = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006396 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006397 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006398 case InitializedEntity::EK_Variable:
6399 // The temporary [...] persists for the lifetime of the reference
Richard Smithd87aab92018-07-17 22:24:09 +00006400 return {Entity, LK_Extended};
Richard Smithe6c01442013-06-05 00:46:14 +00006401
6402 case InitializedEntity::EK_Member:
6403 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006404 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006405 return getEntityLifetime(Entity->getParent(), Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006406
6407 // except:
Richard Smithd87aab92018-07-17 22:24:09 +00006408 // C++17 [class.base.init]p8:
6409 // A temporary expression bound to a reference member in a
6410 // mem-initializer is ill-formed.
6411 // C++17 [class.base.init]p11:
6412 // A temporary expression bound to a reference member from a
6413 // default member initializer is ill-formed.
6414 //
6415 // The context of p11 and its example suggest that it's only the use of a
6416 // default member initializer from a constructor that makes the program
6417 // ill-formed, not its mere existence, and that it can even be used by
6418 // aggregate initialization.
6419 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6420 : LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006421
Richard Smith7873de02016-08-11 22:25:46 +00006422 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006423 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6424 // type.
Richard Smithd87aab92018-07-17 22:24:09 +00006425 return {Entity, LK_Extended};
Richard Smith7873de02016-08-11 22:25:46 +00006426
Richard Smithe6c01442013-06-05 00:46:14 +00006427 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006428 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006429 // -- A temporary bound to a reference parameter in a function call
6430 // persists until the completion of the full-expression containing
6431 // the call.
Richard Smithd87aab92018-07-17 22:24:09 +00006432 return {nullptr, LK_FullExpression};
6433
Richard Smithe6c01442013-06-05 00:46:14 +00006434 case InitializedEntity::EK_Result:
6435 // -- The lifetime of a temporary bound to the returned value in a
6436 // function return statement is not extended; the temporary is
6437 // destroyed at the end of the full-expression in the return statement.
Richard Smithd87aab92018-07-17 22:24:09 +00006438 return {nullptr, LK_Return};
6439
Richard Smith67af95b2018-07-23 19:19:08 +00006440 case InitializedEntity::EK_StmtExprResult:
6441 // FIXME: Should we lifetime-extend through the result of a statement
6442 // expression?
6443 return {nullptr, LK_StmtExprResult};
6444
Richard Smithe6c01442013-06-05 00:46:14 +00006445 case InitializedEntity::EK_New:
6446 // -- A temporary bound to a reference in a new-initializer persists
6447 // until the completion of the full-expression containing the
6448 // new-initializer.
Richard Smithd87aab92018-07-17 22:24:09 +00006449 return {nullptr, LK_New};
Richard Smithe6c01442013-06-05 00:46:14 +00006450
6451 case InitializedEntity::EK_Temporary:
6452 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006453 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006454 // We don't yet know the storage duration of the surrounding temporary.
6455 // Assume it's got full-expression duration for now, it will patch up our
6456 // storage duration if that's not correct.
Richard Smithd87aab92018-07-17 22:24:09 +00006457 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006458
6459 case InitializedEntity::EK_ArrayElement:
6460 // For subobjects, we look at the complete object.
Richard Smithca975b22018-07-23 18:50:26 +00006461 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithe6c01442013-06-05 00:46:14 +00006462
6463 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006464 // For subobjects, we look at the complete object.
6465 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006466 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithd87aab92018-07-17 22:24:09 +00006467 return {InitField, LK_MemInitializer};
6468
Richard Smithe6c01442013-06-05 00:46:14 +00006469 case InitializedEntity::EK_Delegating:
6470 // We can reach this case for aggregate initialization in a constructor:
6471 // struct A { int &&r; };
6472 // struct B : A { B() : A{0} {} };
Richard Smithd87aab92018-07-17 22:24:09 +00006473 // In this case, use the outermost field decl as the context.
6474 return {InitField, LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006475
6476 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006477 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006478 case InitializedEntity::EK_LambdaCapture:
Richard Smithe6c01442013-06-05 00:46:14 +00006479 case InitializedEntity::EK_VectorElement:
6480 case InitializedEntity::EK_ComplexElement:
Richard Smithd87aab92018-07-17 22:24:09 +00006481 return {nullptr, LK_FullExpression};
Richard Smithca975b22018-07-23 18:50:26 +00006482
6483 case InitializedEntity::EK_Exception:
6484 // FIXME: Can we diagnose lifetime problems with exceptions?
6485 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006486 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006487 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006488}
6489
Richard Smithd87aab92018-07-17 22:24:09 +00006490namespace {
Richard Smithca975b22018-07-23 18:50:26 +00006491enum ReferenceKind {
Richard Smithd87aab92018-07-17 22:24:09 +00006492 /// Lifetime would be extended by a reference binding to a temporary.
Richard Smithca975b22018-07-23 18:50:26 +00006493 RK_ReferenceBinding,
Richard Smithd87aab92018-07-17 22:24:09 +00006494 /// Lifetime would be extended by a std::initializer_list object binding to
6495 /// its backing array.
Richard Smithca975b22018-07-23 18:50:26 +00006496 RK_StdInitializerList,
Richard Smithd87aab92018-07-17 22:24:09 +00006497};
Richard Smithca975b22018-07-23 18:50:26 +00006498
Richard Smithafe48f92018-07-23 21:21:22 +00006499/// A temporary or local variable. This will be one of:
6500/// * A MaterializeTemporaryExpr.
6501/// * A DeclRefExpr whose declaration is a local.
6502/// * An AddrLabelExpr.
6503/// * A BlockExpr for a block with captures.
6504using Local = Expr*;
Richard Smithca975b22018-07-23 18:50:26 +00006505
6506/// Expressions we stepped over when looking for the local state. Any steps
6507/// that would inhibit lifetime extension or take us out of subexpressions of
6508/// the initializer are included.
6509struct IndirectLocalPathEntry {
Richard Smithafe48f92018-07-23 21:21:22 +00006510 enum EntryKind {
Richard Smithca975b22018-07-23 18:50:26 +00006511 DefaultInit,
6512 AddressOf,
Richard Smithafe48f92018-07-23 21:21:22 +00006513 VarInit,
6514 LValToRVal,
Richard Smithf4e248c2018-08-01 00:33:25 +00006515 LifetimeBoundCall,
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006516 GslPointerInit
Richard Smithca975b22018-07-23 18:50:26 +00006517 } Kind;
6518 Expr *E;
Richard Smithf4e248c2018-08-01 00:33:25 +00006519 const Decl *D = nullptr;
Richard Smithafe48f92018-07-23 21:21:22 +00006520 IndirectLocalPathEntry() {}
6521 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
Richard Smithf4e248c2018-08-01 00:33:25 +00006522 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
6523 : Kind(K), E(E), D(D) {}
Richard Smithca975b22018-07-23 18:50:26 +00006524};
6525
6526using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
Richard Smithe6c01442013-06-05 00:46:14 +00006527
Richard Smithd87aab92018-07-17 22:24:09 +00006528struct RevertToOldSizeRAII {
Richard Smithca975b22018-07-23 18:50:26 +00006529 IndirectLocalPath &Path;
Richard Smithd87aab92018-07-17 22:24:09 +00006530 unsigned OldSize = Path.size();
Richard Smithca975b22018-07-23 18:50:26 +00006531 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
Richard Smithd87aab92018-07-17 22:24:09 +00006532 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6533};
Richard Smithafe48f92018-07-23 21:21:22 +00006534
6535using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
6536 ReferenceKind RK)>;
Richard Smithd87aab92018-07-17 22:24:09 +00006537}
6538
Richard Smithafe48f92018-07-23 21:21:22 +00006539static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
6540 for (auto E : Path)
6541 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
6542 return true;
6543 return false;
6544}
6545
Richard Smith0e3102d2018-07-24 00:55:08 +00006546static bool pathContainsInit(IndirectLocalPath &Path) {
Fangrui Song3117b172018-10-20 17:53:42 +00006547 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
Richard Smith0e3102d2018-07-24 00:55:08 +00006548 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
6549 E.Kind == IndirectLocalPathEntry::VarInit;
6550 });
6551}
6552
Richard Smithca975b22018-07-23 18:50:26 +00006553static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6554 Expr *Init, LocalVisitor Visit,
6555 bool RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006556
Richard Smithf4e248c2018-08-01 00:33:25 +00006557static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6558 Expr *Init, ReferenceKind RK,
6559 LocalVisitor Visit);
6560
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006561template <typename T> static bool isRecordWithAttr(QualType Type) {
6562 if (auto *RD = Type->getAsCXXRecordDecl())
6563 return RD->getCanonicalDecl()->hasAttr<T>();
6564 return false;
6565}
6566
6567static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
6568 LocalVisitor Visit) {
6569 auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
6570 Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
6571 if (Arg->isGLValue())
6572 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6573 Visit);
6574 else
6575 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6576 Path.pop_back();
6577 };
6578
6579 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6580 const FunctionDecl *Callee = MCE->getDirectCallee();
6581 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
6582 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
6583 VisitPointerArg(Callee, MCE->getImplicitObjectArgument());
6584 return;
6585 }
6586
6587 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
6588 const auto *Ctor = CCE->getConstructor();
6589 const CXXRecordDecl *RD = Ctor->getParent()->getCanonicalDecl();
6590 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
6591 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0]);
6592 }
6593}
6594
Richard Smithf4e248c2018-08-01 00:33:25 +00006595static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
6596 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
6597 if (!TSI)
6598 return false;
Martin Storsjod03fa992018-08-02 18:12:08 +00006599 // Don't declare this variable in the second operand of the for-statement;
6600 // GCC miscompiles that by ending its lifetime before evaluating the
6601 // third operand. See gcc.gnu.org/PR86769.
6602 AttributedTypeLoc ATL;
Richard Smithf4e248c2018-08-01 00:33:25 +00006603 for (TypeLoc TL = TSI->getTypeLoc();
Martin Storsjod03fa992018-08-02 18:12:08 +00006604 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
Richard Smithf4e248c2018-08-01 00:33:25 +00006605 TL = ATL.getModifiedLoc()) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006606 if (ATL.getAttrAs<LifetimeBoundAttr>())
Richard Smithf4e248c2018-08-01 00:33:25 +00006607 return true;
6608 }
6609 return false;
6610}
6611
6612static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
6613 LocalVisitor Visit) {
6614 const FunctionDecl *Callee;
6615 ArrayRef<Expr*> Args;
6616
6617 if (auto *CE = dyn_cast<CallExpr>(Call)) {
6618 Callee = CE->getDirectCallee();
6619 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
6620 } else {
6621 auto *CCE = cast<CXXConstructExpr>(Call);
6622 Callee = CCE->getConstructor();
6623 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
6624 }
6625 if (!Callee)
6626 return;
6627
6628 Expr *ObjectArg = nullptr;
6629 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
6630 ObjectArg = Args[0];
6631 Args = Args.slice(1);
6632 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6633 ObjectArg = MCE->getImplicitObjectArgument();
6634 }
6635
6636 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
6637 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
6638 if (Arg->isGLValue())
6639 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6640 Visit);
6641 else
6642 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6643 Path.pop_back();
6644 };
6645
6646 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
6647 VisitLifetimeBoundArg(Callee, ObjectArg);
6648
6649 for (unsigned I = 0,
6650 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
6651 I != N; ++I) {
6652 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
6653 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
6654 }
6655}
6656
Richard Smithca975b22018-07-23 18:50:26 +00006657/// Visit the locals that would be reachable through a reference bound to the
6658/// glvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006659static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6660 Expr *Init, ReferenceKind RK,
6661 LocalVisitor Visit) {
Richard Smithd87aab92018-07-17 22:24:09 +00006662 RevertToOldSizeRAII RAII(Path);
6663
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006664 // Walk past any constructs which we can lifetime-extend across.
6665 Expr *Old;
6666 do {
6667 Old = Init;
6668
Bill Wendling7c44da22018-10-31 03:48:47 +00006669 if (auto *FE = dyn_cast<FullExpr>(Init))
6670 Init = FE->getSubExpr();
Richard Smithafe48f92018-07-23 21:21:22 +00006671
Richard Smithdbc82492015-01-10 01:28:13 +00006672 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithd87aab92018-07-17 22:24:09 +00006673 // If this is just redundant braces around an initializer, step over it.
6674 if (ILE->isTransparent())
Richard Smithdbc82492015-01-10 01:28:13 +00006675 Init = ILE->getInit(0);
Richard Smithdbc82492015-01-10 01:28:13 +00006676 }
6677
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006678 // Step over any subobject adjustments; we may have a materialized
6679 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006680 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006681
6682 // Per current approach for DR1376, look through casts to reference type
6683 // when performing lifetime extension.
6684 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6685 if (CE->getSubExpr()->isGLValue())
6686 Init = CE->getSubExpr();
6687
Richard Smithb3189a12016-12-05 07:49:14 +00006688 // Per the current approach for DR1299, look through array element access
Richard Smithca975b22018-07-23 18:50:26 +00006689 // on array glvalues when performing lifetime extension.
6690 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006691 Init = ASE->getBase();
6692 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
6693 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
6694 Init = ICE->getSubExpr();
6695 else
6696 // We can't lifetime extend through this but we might still find some
6697 // retained temporaries.
6698 return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
Richard Smithca975b22018-07-23 18:50:26 +00006699 }
Richard Smithd87aab92018-07-17 22:24:09 +00006700
6701 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6702 // constructor inherits one as an implicit mem-initializer.
6703 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006704 Path.push_back(
6705 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
Richard Smithd87aab92018-07-17 22:24:09 +00006706 Init = DIE->getExpr();
Richard Smithd87aab92018-07-17 22:24:09 +00006707 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006708 } while (Init != Old);
6709
Richard Smithd87aab92018-07-17 22:24:09 +00006710 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006711 if (Visit(Path, Local(MTE), RK))
6712 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
6713 true);
6714 }
6715
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006716 if (isa<CallExpr>(Init)) {
6717 handleGslAnnotatedTypes(Path, Init, Visit);
Richard Smithf4e248c2018-08-01 00:33:25 +00006718 return visitLifetimeBoundArguments(Path, Init, Visit);
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006719 }
Richard Smithf4e248c2018-08-01 00:33:25 +00006720
Richard Smithafe48f92018-07-23 21:21:22 +00006721 switch (Init->getStmtClass()) {
6722 case Stmt::DeclRefExprClass: {
6723 // If we find the name of a local non-reference parameter, we could have a
6724 // lifetime problem.
6725 auto *DRE = cast<DeclRefExpr>(Init);
Richard Smithca975b22018-07-23 18:50:26 +00006726 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6727 if (VD && VD->hasLocalStorage() &&
6728 !DRE->refersToEnclosingVariableOrCapture()) {
Richard Smithafe48f92018-07-23 21:21:22 +00006729 if (!VD->getType()->isReferenceType()) {
6730 Visit(Path, Local(DRE), RK);
6731 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
6732 // The lifetime of a reference parameter is unknown; assume it's OK
6733 // for now.
6734 break;
6735 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
6736 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6737 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
6738 RK_ReferenceBinding, Visit);
6739 }
Richard Smithca975b22018-07-23 18:50:26 +00006740 }
Richard Smithafe48f92018-07-23 21:21:22 +00006741 break;
6742 }
6743
6744 case Stmt::UnaryOperatorClass: {
6745 // The only unary operator that make sense to handle here
6746 // is Deref. All others don't resolve to a "name." This includes
6747 // handling all sorts of rvalues passed to a unary operator.
6748 const UnaryOperator *U = cast<UnaryOperator>(Init);
6749 if (U->getOpcode() == UO_Deref)
6750 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
6751 break;
6752 }
6753
6754 case Stmt::OMPArraySectionExprClass: {
6755 visitLocalsRetainedByInitializer(
6756 Path, cast<OMPArraySectionExpr>(Init)->getBase(), Visit, true);
6757 break;
6758 }
6759
6760 case Stmt::ConditionalOperatorClass:
6761 case Stmt::BinaryConditionalOperatorClass: {
6762 auto *C = cast<AbstractConditionalOperator>(Init);
6763 if (!C->getTrueExpr()->getType()->isVoidType())
6764 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
6765 if (!C->getFalseExpr()->getType()->isVoidType())
6766 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
6767 break;
6768 }
6769
6770 // FIXME: Visit the left-hand side of an -> or ->*.
6771
6772 default:
6773 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006774 }
6775}
6776
Richard Smithca975b22018-07-23 18:50:26 +00006777/// Visit the locals that would be reachable through an object initialized by
6778/// the prvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006779static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6780 Expr *Init, LocalVisitor Visit,
6781 bool RevisitSubinits) {
Richard Smithd87aab92018-07-17 22:24:09 +00006782 RevertToOldSizeRAII RAII(Path);
6783
Richard Smithf4e248c2018-08-01 00:33:25 +00006784 Expr *Old;
6785 do {
6786 Old = Init;
Richard Smithd87aab92018-07-17 22:24:09 +00006787
Richard Smithf4e248c2018-08-01 00:33:25 +00006788 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6789 // constructor inherits one as an implicit mem-initializer.
6790 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6791 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
6792 Init = DIE->getExpr();
6793 }
Richard Smithafe48f92018-07-23 21:21:22 +00006794
Bill Wendling7c44da22018-10-31 03:48:47 +00006795 if (auto *FE = dyn_cast<FullExpr>(Init))
6796 Init = FE->getSubExpr();
Richard Smithe6c01442013-06-05 00:46:14 +00006797
Richard Smithf4e248c2018-08-01 00:33:25 +00006798 // Dig out the expression which constructs the extended temporary.
6799 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6800
6801 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6802 Init = BTE->getSubExpr();
6803
6804 Init = Init->IgnoreParens();
6805
6806 // Step over value-preserving rvalue casts.
6807 if (auto *CE = dyn_cast<CastExpr>(Init)) {
6808 switch (CE->getCastKind()) {
6809 case CK_LValueToRValue:
6810 // If we can match the lvalue to a const object, we can look at its
6811 // initializer.
6812 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
6813 return visitLocalsRetainedByReferenceBinding(
6814 Path, Init, RK_ReferenceBinding,
6815 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
6816 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
6817 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6818 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
6819 !isVarOnPath(Path, VD)) {
6820 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6821 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true);
6822 }
6823 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
6824 if (MTE->getType().isConstQualified())
6825 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
6826 Visit, true);
6827 }
6828 return false;
6829 });
6830
6831 // We assume that objects can be retained by pointers cast to integers,
6832 // but not if the integer is cast to floating-point type or to _Complex.
6833 // We assume that casts to 'bool' do not preserve enough information to
6834 // retain a local object.
6835 case CK_NoOp:
6836 case CK_BitCast:
6837 case CK_BaseToDerived:
6838 case CK_DerivedToBase:
6839 case CK_UncheckedDerivedToBase:
6840 case CK_Dynamic:
6841 case CK_ToUnion:
6842 case CK_UserDefinedConversion:
6843 case CK_ConstructorConversion:
6844 case CK_IntegralToPointer:
6845 case CK_PointerToIntegral:
6846 case CK_VectorSplat:
6847 case CK_IntegralCast:
6848 case CK_CPointerToObjCPointerCast:
6849 case CK_BlockPointerToObjCPointerCast:
6850 case CK_AnyPointerToBlockPointerCast:
6851 case CK_AddressSpaceConversion:
6852 break;
6853
6854 case CK_ArrayToPointerDecay:
6855 // Model array-to-pointer decay as taking the address of the array
6856 // lvalue.
6857 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
6858 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
6859 RK_ReferenceBinding, Visit);
6860
6861 default:
6862 return;
6863 }
6864
6865 Init = CE->getSubExpr();
6866 }
6867 } while (Old != Init);
Richard Smith736a9472013-06-12 20:42:33 +00006868
Richard Smithd87aab92018-07-17 22:24:09 +00006869 // C++17 [dcl.init.list]p6:
6870 // initializing an initializer_list object from the array extends the
6871 // lifetime of the array exactly like binding a reference to a temporary.
6872 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
Richard Smithca975b22018-07-23 18:50:26 +00006873 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
6874 RK_StdInitializerList, Visit);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006875
Richard Smithe6c01442013-06-05 00:46:14 +00006876 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006877 // We already visited the elements of this initializer list while
6878 // performing the initialization. Don't visit them again unless we've
6879 // changed the lifetime of the initialized entity.
6880 if (!RevisitSubinits)
6881 return;
6882
Richard Smithd87aab92018-07-17 22:24:09 +00006883 if (ILE->isTransparent())
Richard Smithca975b22018-07-23 18:50:26 +00006884 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
6885 RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006886
Richard Smithcc1b96d2013-06-12 22:31:48 +00006887 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006888 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Richard Smithca975b22018-07-23 18:50:26 +00006889 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
6890 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006891 return;
6892 }
6893
Richard Smithcc1b96d2013-06-12 22:31:48 +00006894 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006895 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6896
6897 // If we lifetime-extend a braced initializer which is initializing an
6898 // aggregate, and that aggregate contains reference members which are
6899 // bound to temporaries, those temporaries are also lifetime-extended.
6900 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6901 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006902 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
6903 RK_ReferenceBinding, Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006904 else {
6905 unsigned Index = 0;
Richard Smithc69cc842019-06-12 18:32:22 +00006906 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
6907 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
6908 RevisitSubinits);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006909 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006910 if (Index >= ILE->getNumInits())
6911 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006912 if (I->isUnnamedBitfield())
6913 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006914 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006915 if (I->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006916 visitLocalsRetainedByReferenceBinding(Path, SubInit,
6917 RK_ReferenceBinding, Visit);
Richard Smithd87aab92018-07-17 22:24:09 +00006918 else
6919 // This might be either aggregate-initialization of a member or
6920 // initialization of a std::initializer_list object. Regardless,
Richard Smithe6c01442013-06-05 00:46:14 +00006921 // we should recursively lifetime-extend that initializer.
Richard Smithca975b22018-07-23 18:50:26 +00006922 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
6923 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006924 ++Index;
6925 }
6926 }
6927 }
Richard Smithca975b22018-07-23 18:50:26 +00006928 return;
6929 }
6930
Richard Smithb3d203f2018-10-19 19:01:34 +00006931 // The lifetime of an init-capture is that of the closure object constructed
6932 // by a lambda-expression.
6933 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
6934 for (Expr *E : LE->capture_inits()) {
6935 if (!E)
6936 continue;
6937 if (E->isGLValue())
6938 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
6939 Visit);
6940 else
6941 visitLocalsRetainedByInitializer(Path, E, Visit, true);
6942 }
6943 }
6944
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006945 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
6946 handleGslAnnotatedTypes(Path, Init, Visit);
Richard Smithf4e248c2018-08-01 00:33:25 +00006947 return visitLifetimeBoundArguments(Path, Init, Visit);
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006948 }
Richard Smithafe48f92018-07-23 21:21:22 +00006949
Richard Smithafe48f92018-07-23 21:21:22 +00006950 switch (Init->getStmtClass()) {
6951 case Stmt::UnaryOperatorClass: {
6952 auto *UO = cast<UnaryOperator>(Init);
6953 // If the initializer is the address of a local, we could have a lifetime
6954 // problem.
6955 if (UO->getOpcode() == UO_AddrOf) {
Richard Smith0e3102d2018-07-24 00:55:08 +00006956 // If this is &rvalue, then it's ill-formed and we have already diagnosed
6957 // it. Don't produce a redundant warning about the lifetime of the
6958 // temporary.
6959 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
6960 return;
6961
Richard Smithafe48f92018-07-23 21:21:22 +00006962 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
6963 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
6964 RK_ReferenceBinding, Visit);
6965 }
6966 break;
6967 }
6968
6969 case Stmt::BinaryOperatorClass: {
6970 // Handle pointer arithmetic.
6971 auto *BO = cast<BinaryOperator>(Init);
6972 BinaryOperatorKind BOK = BO->getOpcode();
6973 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
6974 break;
6975
6976 if (BO->getLHS()->getType()->isPointerType())
6977 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
6978 else if (BO->getRHS()->getType()->isPointerType())
6979 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
6980 break;
6981 }
6982
6983 case Stmt::ConditionalOperatorClass:
6984 case Stmt::BinaryConditionalOperatorClass: {
6985 auto *C = cast<AbstractConditionalOperator>(Init);
6986 // In C++, we can have a throw-expression operand, which has 'void' type
6987 // and isn't interesting from a lifetime perspective.
6988 if (!C->getTrueExpr()->getType()->isVoidType())
6989 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
6990 if (!C->getFalseExpr()->getType()->isVoidType())
6991 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
6992 break;
6993 }
6994
6995 case Stmt::BlockExprClass:
6996 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
6997 // This is a local block, whose lifetime is that of the function.
6998 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
6999 }
7000 break;
7001
7002 case Stmt::AddrLabelExprClass:
7003 // We want to warn if the address of a label would escape the function.
7004 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
7005 break;
7006
7007 default:
7008 break;
Richard Smithe6c01442013-06-05 00:46:14 +00007009 }
7010}
7011
Richard Smithd87aab92018-07-17 22:24:09 +00007012/// Determine whether this is an indirect path to a temporary that we are
7013/// supposed to lifetime-extend along (but don't).
Richard Smithca975b22018-07-23 18:50:26 +00007014static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
Richard Smithd87aab92018-07-17 22:24:09 +00007015 for (auto Elem : Path) {
Richard Smithf66e4f72018-07-23 22:56:45 +00007016 if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
Richard Smithd87aab92018-07-17 22:24:09 +00007017 return false;
7018 }
7019 return true;
7020}
7021
Richard Smith6a32c052018-07-23 21:21:24 +00007022/// Find the range for the first interesting entry in the path at or after I.
7023static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
7024 Expr *E) {
7025 for (unsigned N = Path.size(); I != N; ++I) {
7026 switch (Path[I].Kind) {
7027 case IndirectLocalPathEntry::AddressOf:
7028 case IndirectLocalPathEntry::LValToRVal:
Richard Smithf4e248c2018-08-01 00:33:25 +00007029 case IndirectLocalPathEntry::LifetimeBoundCall:
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007030 case IndirectLocalPathEntry::GslPointerInit:
Richard Smith6a32c052018-07-23 21:21:24 +00007031 // These exist primarily to mark the path as not permitting or
7032 // supporting lifetime extension.
7033 break;
7034
7035 case IndirectLocalPathEntry::DefaultInit:
7036 case IndirectLocalPathEntry::VarInit:
7037 return Path[I].E->getSourceRange();
7038 }
7039 }
7040 return E->getSourceRange();
7041}
7042
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007043static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
7044 return !Path.empty() &&
7045 Path.back().Kind == IndirectLocalPathEntry::GslPointerInit;
7046}
7047
Richard Smithd87aab92018-07-17 22:24:09 +00007048void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7049 Expr *Init) {
Richard Smithca975b22018-07-23 18:50:26 +00007050 LifetimeResult LR = getEntityLifetime(&Entity);
Richard Smithd87aab92018-07-17 22:24:09 +00007051 LifetimeKind LK = LR.getInt();
7052 const InitializedEntity *ExtendingEntity = LR.getPointer();
7053
7054 // If this entity doesn't have an interesting lifetime, don't bother looking
7055 // for temporaries within its initializer.
7056 if (LK == LK_FullExpression)
7057 return;
7058
Richard Smithca975b22018-07-23 18:50:26 +00007059 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
7060 ReferenceKind RK) -> bool {
Richard Smith6a32c052018-07-23 21:21:24 +00007061 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
7062 SourceLocation DiagLoc = DiagRange.getBegin();
Richard Smithca975b22018-07-23 18:50:26 +00007063
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007064 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
7065 bool IsTempGslOwner = MTE && isRecordWithAttr<OwnerAttr>(MTE->getType());
7066 bool IsLocalGslOwner =
7067 isa<DeclRefExpr>(L) && isRecordWithAttr<OwnerAttr>(L->getType());
7068
7069 // Skipping a chain of initializing gsl::Pointer annotated objects.
7070 // We are looking only for the final source to find out if it was
7071 // a local or temporary owner or the address of a local variable/param. We
7072 // do not want to follow the references when returning a pointer originating
7073 // from a local owner to avoid the following false positive:
7074 // int &p = *localOwner;
7075 // someContainer.add(std::move(localOwner));
7076 // return p;
7077 if (!IsTempGslOwner && pathOnlyInitializesGslPointer(Path) &&
7078 !(IsLocalGslOwner && !pathContainsInit(Path)))
7079 return true;
7080
7081 bool IsGslPtrInitWithGslTempOwner =
7082 IsTempGslOwner && pathOnlyInitializesGslPointer(Path);
7083
Richard Smithd87aab92018-07-17 22:24:09 +00007084 switch (LK) {
7085 case LK_FullExpression:
7086 llvm_unreachable("already handled this");
7087
Richard Smithafe48f92018-07-23 21:21:22 +00007088 case LK_Extended: {
Richard Smith0e3102d2018-07-24 00:55:08 +00007089 if (!MTE) {
7090 // The initialized entity has lifetime beyond the full-expression,
7091 // and the local entity does too, so don't warn.
7092 //
7093 // FIXME: We should consider warning if a static / thread storage
7094 // duration variable retains an automatic storage duration local.
Richard Smithafe48f92018-07-23 21:21:22 +00007095 return false;
Richard Smith0e3102d2018-07-24 00:55:08 +00007096 }
Richard Smithafe48f92018-07-23 21:21:22 +00007097
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007098 if (IsGslPtrInitWithGslTempOwner) {
7099 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
7100 return false;
7101 }
7102
Richard Smithd87aab92018-07-17 22:24:09 +00007103 // Lifetime-extend the temporary.
7104 if (Path.empty()) {
7105 // Update the storage duration of the materialized temporary.
7106 // FIXME: Rebuild the expression instead of mutating it.
7107 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
7108 ExtendingEntity->allocateManglingNumber());
7109 // Also visit the temporaries lifetime-extended by this initializer.
7110 return true;
7111 }
7112
7113 if (shouldLifetimeExtendThroughPath(Path)) {
7114 // We're supposed to lifetime-extend the temporary along this path (per
7115 // the resolution of DR1815), but we don't support that yet.
7116 //
Richard Smith0e3102d2018-07-24 00:55:08 +00007117 // FIXME: Properly handle this situation. Perhaps the easiest approach
Richard Smithd87aab92018-07-17 22:24:09 +00007118 // would be to clone the initializer expression on each use that would
7119 // lifetime extend its temporaries.
Richard Smith0e3102d2018-07-24 00:55:08 +00007120 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
7121 << RK << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00007122 } else {
Richard Smith0e3102d2018-07-24 00:55:08 +00007123 // If the path goes through the initialization of a variable or field,
7124 // it can't possibly reach a temporary created in this full-expression.
7125 // We will have already diagnosed any problems with the initializer.
7126 if (pathContainsInit(Path))
7127 return false;
7128
7129 Diag(DiagLoc, diag::warn_dangling_variable)
Richard Smithad5bbcc2018-08-01 01:03:33 +00007130 << RK << !Entity.getParent()
7131 << ExtendingEntity->getDecl()->isImplicit()
7132 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00007133 }
7134 break;
Richard Smithafe48f92018-07-23 21:21:22 +00007135 }
Richard Smithd87aab92018-07-17 22:24:09 +00007136
Richard Smithafe48f92018-07-23 21:21:22 +00007137 case LK_MemInitializer: {
George Burgess IV06df2292018-07-24 02:10:53 +00007138 if (isa<MaterializeTemporaryExpr>(L)) {
Richard Smithafe48f92018-07-23 21:21:22 +00007139 // Under C++ DR1696, if a mem-initializer (or a default member
7140 // initializer used by the absence of one) would lifetime-extend a
7141 // temporary, the program is ill-formed.
7142 if (auto *ExtendingDecl =
7143 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007144 if (IsGslPtrInitWithGslTempOwner) {
7145 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
7146 << ExtendingDecl << DiagRange;
7147 Diag(ExtendingDecl->getLocation(),
7148 diag::note_ref_or_ptr_member_declared_here)
7149 << true;
7150 return false;
7151 }
Richard Smithafe48f92018-07-23 21:21:22 +00007152 bool IsSubobjectMember = ExtendingEntity != &Entity;
Richard Smith0e3102d2018-07-24 00:55:08 +00007153 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
7154 ? diag::err_dangling_member
7155 : diag::warn_dangling_member)
Richard Smithafe48f92018-07-23 21:21:22 +00007156 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
7157 // Don't bother adding a note pointing to the field if we're inside
7158 // its default member initializer; our primary diagnostic points to
7159 // the same place in that case.
7160 if (Path.empty() ||
7161 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
7162 Diag(ExtendingDecl->getLocation(),
7163 diag::note_lifetime_extending_member_declared_here)
7164 << RK << IsSubobjectMember;
7165 }
7166 } else {
7167 // We have a mem-initializer but no particular field within it; this
7168 // is either a base class or a delegating initializer directly
7169 // initializing the base-class from something that doesn't live long
7170 // enough.
7171 //
7172 // FIXME: Warn on this.
7173 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00007174 }
7175 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00007176 // Paths via a default initializer can only occur during error recovery
7177 // (there's no other way that a default initializer can refer to a
7178 // local). Don't produce a bogus warning on those cases.
Richard Smith0e3102d2018-07-24 00:55:08 +00007179 if (pathContainsInit(Path))
Richard Smithafe48f92018-07-23 21:21:22 +00007180 return false;
7181
7182 auto *DRE = dyn_cast<DeclRefExpr>(L);
7183 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7184 if (!VD) {
7185 // A member was initialized to a local block.
7186 // FIXME: Warn on this.
7187 return false;
7188 }
7189
7190 if (auto *Member =
7191 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007192 bool IsPointer = !Member->getType()->isReferenceType();
Richard Smithafe48f92018-07-23 21:21:22 +00007193 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
7194 : diag::warn_bind_ref_member_to_parameter)
7195 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
7196 Diag(Member->getLocation(),
7197 diag::note_ref_or_ptr_member_declared_here)
7198 << (unsigned)IsPointer;
7199 }
Richard Smithd87aab92018-07-17 22:24:09 +00007200 }
7201 break;
Richard Smithafe48f92018-07-23 21:21:22 +00007202 }
Richard Smithd87aab92018-07-17 22:24:09 +00007203
7204 case LK_New:
George Burgess IV06df2292018-07-24 02:10:53 +00007205 if (isa<MaterializeTemporaryExpr>(L)) {
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007206 if (IsGslPtrInitWithGslTempOwner)
7207 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
7208 else
7209 Diag(DiagLoc, RK == RK_ReferenceBinding
7210 ? diag::warn_new_dangling_reference
7211 : diag::warn_new_dangling_initializer_list)
7212 << !Entity.getParent() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00007213 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00007214 // We can't determine if the allocation outlives the local declaration.
7215 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00007216 }
7217 break;
7218
7219 case LK_Return:
Richard Smith67af95b2018-07-23 19:19:08 +00007220 case LK_StmtExprResult:
Richard Smithafe48f92018-07-23 21:21:22 +00007221 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7222 // We can't determine if the local variable outlives the statement
7223 // expression.
7224 if (LK == LK_StmtExprResult)
7225 return false;
7226 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
7227 << Entity.getType()->isReferenceType() << DRE->getDecl()
7228 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
7229 } else if (isa<BlockExpr>(L)) {
7230 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
7231 } else if (isa<AddrLabelExpr>(L)) {
Reid Kleckner4c33d192018-08-17 22:11:31 +00007232 // Don't warn when returning a label from a statement expression.
7233 // Leaving the scope doesn't end its lifetime.
7234 if (LK == LK_StmtExprResult)
7235 return false;
Richard Smithafe48f92018-07-23 21:21:22 +00007236 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
7237 } else {
7238 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
7239 << Entity.getType()->isReferenceType() << DiagRange;
7240 }
7241 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00007242 }
7243
Richard Smithafe48f92018-07-23 21:21:22 +00007244 for (unsigned I = 0; I != Path.size(); ++I) {
7245 auto Elem = Path[I];
7246
Richard Smithca975b22018-07-23 18:50:26 +00007247 switch (Elem.Kind) {
Richard Smithafe48f92018-07-23 21:21:22 +00007248 case IndirectLocalPathEntry::AddressOf:
7249 case IndirectLocalPathEntry::LValToRVal:
Richard Smith6a32c052018-07-23 21:21:24 +00007250 // These exist primarily to mark the path as not permitting or
7251 // supporting lifetime extension.
Richard Smithca975b22018-07-23 18:50:26 +00007252 break;
7253
Richard Smithf4e248c2018-08-01 00:33:25 +00007254 case IndirectLocalPathEntry::LifetimeBoundCall:
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007255 case IndirectLocalPathEntry::GslPointerInit:
7256 // FIXME: Consider adding a note for these.
Richard Smithf4e248c2018-08-01 00:33:25 +00007257 break;
7258
Richard Smithafe48f92018-07-23 21:21:22 +00007259 case IndirectLocalPathEntry::DefaultInit: {
7260 auto *FD = cast<FieldDecl>(Elem.D);
7261 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
Richard Smith6a32c052018-07-23 21:21:24 +00007262 << FD << nextPathEntryRange(Path, I + 1, L);
Richard Smithafe48f92018-07-23 21:21:22 +00007263 break;
7264 }
7265
7266 case IndirectLocalPathEntry::VarInit:
7267 const VarDecl *VD = cast<VarDecl>(Elem.D);
7268 Diag(VD->getLocation(), diag::note_local_var_initializer)
Richard Smithad5bbcc2018-08-01 01:03:33 +00007269 << VD->getType()->isReferenceType()
7270 << VD->isImplicit() << VD->getDeclName()
Richard Smith6a32c052018-07-23 21:21:24 +00007271 << nextPathEntryRange(Path, I + 1, L);
Richard Smithca975b22018-07-23 18:50:26 +00007272 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00007273 }
7274 }
Richard Smithd87aab92018-07-17 22:24:09 +00007275
7276 // We didn't lifetime-extend, so don't go any further; we don't need more
7277 // warnings or errors on inner temporaries within this one's initializer.
7278 return false;
7279 };
7280
Richard Smithca975b22018-07-23 18:50:26 +00007281 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
Richard Smithd87aab92018-07-17 22:24:09 +00007282 if (Init->isGLValue())
Richard Smithca975b22018-07-23 18:50:26 +00007283 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
7284 TemporaryVisitor);
Richard Smithd87aab92018-07-17 22:24:09 +00007285 else
Richard Smithca975b22018-07-23 18:50:26 +00007286 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007287}
7288
Richard Smithaaa0ec42013-09-21 21:19:19 +00007289static void DiagnoseNarrowingInInitList(Sema &S,
7290 const ImplicitConversionSequence &ICS,
7291 QualType PreNarrowingType,
7292 QualType EntityType,
7293 const Expr *PostInit);
7294
Richard Trieuac3eca52015-04-29 01:52:17 +00007295/// Provide warnings when std::move is used on construction.
7296static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7297 bool IsReturnStmt) {
7298 if (!InitExpr)
7299 return;
7300
Richard Smith51ec0cf2017-02-21 01:17:38 +00007301 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00007302 return;
7303
Richard Trieuac3eca52015-04-29 01:52:17 +00007304 QualType DestType = InitExpr->getType();
7305 if (!DestType->isRecordType())
7306 return;
7307
Richard Trieu155b8d02019-08-08 00:12:51 +00007308 const CXXConstructExpr *CCE =
7309 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7310 if (!CCE || CCE->getNumArgs() != 1)
7311 return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007312
Richard Trieu155b8d02019-08-08 00:12:51 +00007313 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7314 return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007315
Richard Trieu155b8d02019-08-08 00:12:51 +00007316 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00007317
7318 // Find the std::move call and get the argument.
7319 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
Nico Weber192184c2018-06-20 15:57:38 +00007320 if (!CE || !CE->isCallToStdMove())
Richard Trieuac3eca52015-04-29 01:52:17 +00007321 return;
7322
Richard Trieu155b8d02019-08-08 00:12:51 +00007323 const Expr *Arg = CE->getArg(0);
Richard Trieuac3eca52015-04-29 01:52:17 +00007324
Richard Trieu155b8d02019-08-08 00:12:51 +00007325 unsigned DiagID = 0;
7326
7327 if (!IsReturnStmt && !isa<MaterializeTemporaryExpr>(Arg))
7328 return;
7329
7330 if (isa<MaterializeTemporaryExpr>(Arg)) {
7331 DiagID = diag::warn_pessimizing_move_on_initialization;
7332 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7333 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
7334 return;
7335 } else { // IsReturnStmt
Richard Trieuac3eca52015-04-29 01:52:17 +00007336 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7337 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7338 return;
7339
7340 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7341 if (!VD || !VD->hasLocalStorage())
7342 return;
7343
Alex Lorenzbbe51d82017-11-07 21:40:11 +00007344 // __block variables are not moved implicitly.
7345 if (VD->hasAttr<BlocksAttr>())
7346 return;
7347
Richard Trieu8d4006a2015-07-28 19:06:16 +00007348 QualType SourceType = VD->getType();
7349 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00007350 return;
7351
Richard Trieu8d4006a2015-07-28 19:06:16 +00007352 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00007353 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00007354 }
7355
Davide Italiano7842c3f2015-07-18 01:15:19 +00007356 // If we're returning a function parameter, copy elision
7357 // is not possible.
7358 if (isa<ParmVarDecl>(VD))
7359 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00007360 else
7361 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007362 }
7363
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007364 S.Diag(CE->getBeginLoc(), DiagID);
Richard Trieuac3eca52015-04-29 01:52:17 +00007365
7366 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7367 // is within a macro.
Richard Trieu155b8d02019-08-08 00:12:51 +00007368 SourceLocation BeginLoc = CCE->getBeginLoc();
7369 if (BeginLoc.isMacroID())
Richard Trieuac3eca52015-04-29 01:52:17 +00007370 return;
7371 SourceLocation RParen = CE->getRParenLoc();
7372 if (RParen.isMacroID())
7373 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007374 SourceLocation ArgLoc = Arg->getBeginLoc();
Richard Trieuac3eca52015-04-29 01:52:17 +00007375
7376 // Special testing for the argument location. Since the fix-it needs the
7377 // location right before the argument, the argument location can be in a
7378 // macro only if it is at the beginning of the macro.
7379 while (ArgLoc.isMacroID() &&
7380 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
Richard Smithb5f81712018-04-30 05:25:48 +00007381 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
Richard Trieuac3eca52015-04-29 01:52:17 +00007382 }
7383
Richard Trieu155b8d02019-08-08 00:12:51 +00007384 SourceLocation LParen = ArgLoc.getLocWithOffset(-1);
Richard Trieuac3eca52015-04-29 01:52:17 +00007385 if (LParen.isMacroID())
7386 return;
Richard Trieu155b8d02019-08-08 00:12:51 +00007387 SourceLocation EndLoc = CCE->getEndLoc();
7388 if (EndLoc.isMacroID())
7389 return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007390
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007391 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
Richard Trieu155b8d02019-08-08 00:12:51 +00007392 << FixItHint::CreateRemoval(SourceRange(BeginLoc, LParen))
7393 << FixItHint::CreateRemoval(SourceRange(RParen, EndLoc));
Richard Trieuac3eca52015-04-29 01:52:17 +00007394}
7395
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007396static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7397 // Check to see if we are dereferencing a null pointer. If so, this is
7398 // undefined behavior, so warn about it. This only handles the pattern
7399 // "*null", which is a very syntactic check.
7400 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7401 if (UO->getOpcode() == UO_Deref &&
7402 UO->getSubExpr()->IgnoreParenCasts()->
7403 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7404 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7405 S.PDiag(diag::warn_binding_null_to_reference)
7406 << UO->getSubExpr()->getSourceRange());
7407 }
7408}
7409
Tim Shen4a05bb82016-06-21 20:29:17 +00007410MaterializeTemporaryExpr *
7411Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7412 bool BoundToLvalueReference) {
7413 auto MTE = new (Context)
7414 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7415
7416 // Order an ExprWithCleanups for lifetime marks.
7417 //
7418 // TODO: It'll be good to have a single place to check the access of the
7419 // destructor and generate ExprWithCleanups for various uses. Currently these
7420 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7421 // but there may be a chance to merge them.
7422 Cleanup.setExprNeedsCleanups(false);
7423 return MTE;
7424}
7425
Richard Smith4baaa5a2016-12-03 01:14:32 +00007426ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7427 // In C++98, we don't want to implicitly create an xvalue.
7428 // FIXME: This means that AST consumers need to deal with "prvalues" that
7429 // denote materialized temporaries. Maybe we should add another ValueKind
7430 // for "xvalue pretending to be a prvalue" for C++98 support.
7431 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
7432 return E;
7433
7434 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00007435 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7436 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00007437 QualType T = E->getType();
7438 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7439 return ExprError();
7440
7441 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7442}
7443
Anastasia Stulova04307942018-11-16 16:22:56 +00007444ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7445 ExprValueKind VK,
7446 CheckedConversionKind CCK) {
Anastasia Stulova094c7262019-04-04 10:48:36 +00007447
7448 CastKind CK = CK_NoOp;
7449
7450 if (VK == VK_RValue) {
7451 auto PointeeTy = Ty->getPointeeType();
7452 auto ExprPointeeTy = E->getType()->getPointeeType();
7453 if (!PointeeTy.isNull() &&
7454 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7455 CK = CK_AddressSpaceConversion;
7456 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7457 CK = CK_AddressSpaceConversion;
7458 }
7459
Anastasia Stulova04307942018-11-16 16:22:56 +00007460 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7461}
7462
7463ExprResult InitializationSequence::Perform(Sema &S,
7464 const InitializedEntity &Entity,
7465 const InitializationKind &Kind,
7466 MultiExprArg Args,
7467 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007468 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007469 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00007470 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007471 }
Nico Weber337d5aa2015-04-17 08:32:38 +00007472 if (!ZeroInitializationFixit.empty()) {
7473 unsigned DiagID = diag::err_default_init_const;
7474 if (Decl *D = Entity.getDecl())
7475 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
7476 DiagID = diag::ext_default_init_const;
7477
7478 // The initialization would have succeeded with this fixit. Since the fixit
7479 // is on the error, we need to build a valid AST in this case, so this isn't
7480 // handled in the Failed() branch above.
7481 QualType DestType = Entity.getType();
7482 S.Diag(Kind.getLocation(), DiagID)
7483 << DestType << (bool)DestType->getAs<RecordType>()
7484 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7485 ZeroInitializationFixit);
7486 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007487
Sebastian Redld201edf2011-06-05 13:59:11 +00007488 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007489 // If the declaration is a non-dependent, incomplete array type
7490 // that has an initializer, then its type will be completed once
7491 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00007492 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00007493 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007494 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007495 if (const IncompleteArrayType *ArrayT
7496 = S.Context.getAsIncompleteArrayType(DeclType)) {
7497 // FIXME: We don't currently have the ability to accurately
7498 // compute the length of an initializer list without
7499 // performing full type-checking of the initializer list
7500 // (since we have to determine where braces are implicitly
7501 // introduced and such). So, we fall back to making the array
7502 // type a dependently-sized array type with no specified
7503 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007504 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007505 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00007506
Douglas Gregor51e77d52009-12-10 17:56:55 +00007507 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00007508 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007509 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7510 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007511 if (IncompleteArrayTypeLoc ArrayLoc =
7512 TL.getAs<IncompleteArrayTypeLoc>())
7513 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00007514 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007515 }
7516
7517 *ResultType
7518 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007519 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00007520 ArrayT->getSizeModifier(),
7521 ArrayT->getIndexTypeCVRQualifiers(),
7522 Brackets);
7523 }
7524
7525 }
7526 }
Sebastian Redla9351792012-02-11 23:51:47 +00007527 if (Kind.getKind() == InitializationKind::IK_Direct &&
7528 !Kind.isExplicitCast()) {
7529 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00007530 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00007531 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007532 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00007533 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00007534 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Fangrui Song6907ce22018-07-30 19:24:48 +00007535 Kind.isExplicitCast() ||
Douglas Gregorbf138952012-04-04 04:06:51 +00007536 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007537 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007538 }
7539
Sebastian Redld201edf2011-06-05 13:59:11 +00007540 // No steps means no initialization.
7541 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007542 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007543
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007544 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007545 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007546 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00007547 // Produce a C++98 compatibility warning if we are initializing a reference
7548 // from an initializer list. For parameters, we produce a better warning
7549 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007550 Expr *Init = Args[0];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007551 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7552 << Init->getSourceRange();
Richard Smith2b349ae2012-04-19 06:58:00 +00007553 }
7554
Egor Churaev3bccec52017-04-05 12:47:10 +00007555 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7556 QualType ETy = Entity.getType();
7557 Qualifiers TyQualifiers = ETy.getQualifiers();
7558 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
7559 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
7560
7561 if (S.getLangOpts().OpenCLVersion >= 200 &&
7562 ETy->isAtomicType() && !HasGlobalAS &&
7563 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007564 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7565 << 1
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007566 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
Egor Churaev3bccec52017-04-05 12:47:10 +00007567 return ExprError();
7568 }
7569
Douglas Gregor1b303932009-12-22 15:35:07 +00007570 QualType DestType = Entity.getType().getNonReferenceType();
7571 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00007572 // the same as Entity.getDecl()->getType() in cases involving type merging,
7573 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00007574 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00007575 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00007576 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007577
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007578 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00007579 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007580
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00007582 // grab the only argument out the Args and place it into the "current"
7583 // initializer.
7584 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007585 case SK_ResolveAddressOfOverloadedFunction:
7586 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007587 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007588 case SK_CastDerivedToBaseLValue:
7589 case SK_BindReference:
7590 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00007591 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007592 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00007593 case SK_UserConversion:
7594 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007595 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007596 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00007597 case SK_AtomicConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00007598 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00007599 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00007600 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00007601 case SK_UnwrapInitList:
7602 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00007603 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00007604 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007605 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00007606 case SK_ArrayLoopIndex:
7607 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00007608 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00007609 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00007610 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00007611 case SK_PassByIndirectCopyRestore:
7612 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00007613 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007614 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00007615 case SK_OCLSamplerInit:
Andrew Savonichevb555b762018-10-23 15:19:20 +00007616 case SK_OCLZeroOpaqueType: {
Douglas Gregore1314a62009-12-18 05:02:21 +00007617 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007618 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00007619 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00007620 break;
John McCall34376a62010-12-04 03:47:34 +00007621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007622
Douglas Gregore1314a62009-12-18 05:02:21 +00007623 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00007624 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007625 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00007626 case SK_ZeroInitialization:
7627 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007629
Richard Smithd6a15082017-01-07 00:48:55 +00007630 // Promote from an unevaluated context to an unevaluated list context in
7631 // C++11 list-initialization; we need to instantiate entities usable in
7632 // constant expressions here in order to perform narrowing checks =(
7633 EnterExpressionEvaluationContext Evaluated(
7634 S, EnterExpressionEvaluationContext::InitList,
7635 CurInit.get() && isa<InitListExpr>(CurInit.get()));
7636
Richard Smith81f5ade2016-12-15 02:28:18 +00007637 // C++ [class.abstract]p2:
7638 // no objects of an abstract class can be created except as subobjects
7639 // of a class derived from it
7640 auto checkAbstractType = [&](QualType T) -> bool {
7641 if (Entity.getKind() == InitializedEntity::EK_Base ||
7642 Entity.getKind() == InitializedEntity::EK_Delegating)
7643 return false;
7644 return S.RequireNonAbstractType(Kind.getLocation(), T,
7645 diag::err_allocation_of_abstract_type);
7646 };
7647
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007648 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007649 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007650 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007651 for (step_iterator Step = step_begin(), StepEnd = step_end();
7652 Step != StepEnd; ++Step) {
7653 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007654 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007655
John Wiegley01296292011-04-08 18:41:53 +00007656 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007657
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007658 switch (Step->Kind) {
7659 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007660 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007661 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00007662 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00007663 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7664 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007665 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00007666 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00007667 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007670 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007671 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007672 case SK_CastDerivedToBaseLValue: {
7673 // We have a derived-to-base cast that produces either an rvalue or an
7674 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007675
John McCallcf142162010-08-07 06:22:56 +00007676 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00007677
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007678 // Casts to inaccessible base classes are allowed with C-style casts.
7679 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007680 if (S.CheckDerivedToBaseConversion(
7681 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
7682 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00007683 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007684
John McCall2536c6d2010-08-25 10:28:54 +00007685 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007686 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007687 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007688 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007689 VK_XValue :
7690 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007691 CurInit =
7692 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
7693 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007694 break;
7695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007696
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007697 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007698 // Reference binding does not have any corresponding ASTs.
7699
7700 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007701 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007702 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007703
George Burgess IVcfd48d92017-04-13 23:47:08 +00007704 // We don't check for e.g. function pointers here, since address
7705 // availability checks should only occur when the function first decays
7706 // into a pointer or reference.
7707 if (CurInit.get()->getType()->isFunctionProtoType()) {
7708 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7709 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7710 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007711 DRE->getBeginLoc()))
George Burgess IVcfd48d92017-04-13 23:47:08 +00007712 return ExprError();
7713 }
7714 }
7715 }
7716
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007717 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007718 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007719
Richard Smithe6c01442013-06-05 00:46:14 +00007720 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00007721 // Make sure the "temporary" is actually an rvalue.
7722 assert(CurInit.get()->isRValue() && "not a temporary");
7723
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007724 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007725 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007726 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007727
Douglas Gregorfe314812011-06-21 17:03:29 +00007728 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007729 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00007730 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
Richard Smithd87aab92018-07-17 22:24:09 +00007731 CurInit = MTE;
David Majnemerdaff3702014-05-01 17:50:17 +00007732
Brian Kelley762f9282017-03-29 18:16:38 +00007733 // If we're extending this temporary to automatic storage duration -- we
7734 // need to register its cleanup during the full-expression's cleanups.
7735 if (MTE->getStorageDuration() == SD_Automatic &&
7736 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00007737 S.Cleanup.setExprNeedsCleanups(true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007738 break;
Richard Smithe6c01442013-06-05 00:46:14 +00007739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007740
Richard Smithb8c0f552016-12-09 18:49:13 +00007741 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00007742 if (checkAbstractType(Step->Type))
7743 return ExprError();
7744
Richard Smithb8c0f552016-12-09 18:49:13 +00007745 // If the overall initialization is initializing a temporary, we already
7746 // bound our argument if it was necessary to do so. If not (if we're
7747 // ultimately initializing a non-temporary), our argument needs to be
7748 // bound since it's initializing a function parameter.
7749 // FIXME: This is a mess. Rationalize temporary destruction.
7750 if (!shouldBindAsTemporary(Entity))
7751 CurInit = S.MaybeBindToTemporary(CurInit.get());
7752 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7753 /*IsExtraneousCopy=*/false);
7754 break;
7755
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007756 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007757 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007758 /*IsExtraneousCopy=*/true);
7759 break;
7760
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007761 case SK_UserConversion: {
7762 // We have a user-defined conversion that invokes either a constructor
7763 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00007764 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00007765 FunctionDecl *Fn = Step->Function.Function;
7766 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007767 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00007768 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00007769 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007770 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00007771 SmallVector<Expr*, 8> ConstructorArgs;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007772 SourceLocation Loc = CurInit.get()->getBeginLoc();
John McCall760af172010-02-01 03:16:54 +00007773
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007774 // Determine the arguments required to actually perform the constructor
7775 // call.
John Wiegley01296292011-04-08 18:41:53 +00007776 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007777 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00007778 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007779 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00007780 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007781
Richard Smithb24f0672012-02-11 19:22:50 +00007782 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00007783 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
7784 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007785 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007786 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00007787 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007788 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00007789 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00007790 CXXConstructExpr::CK_Complete,
7791 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007792 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007793 return ExprError();
John McCall760af172010-02-01 03:16:54 +00007794
Richard Smith5179eb72016-06-28 19:03:57 +00007795 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7796 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00007797 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7798 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007799
John McCalle3027922010-08-25 11:45:40 +00007800 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00007801 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007802 } else {
7803 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00007804 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00007805 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00007806 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00007807 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7808 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007809
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007810 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7811 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00007812 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007813 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007814
John McCalle3027922010-08-25 11:45:40 +00007815 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00007816 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007818
Richard Smith81f5ade2016-12-15 02:28:18 +00007819 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7820 return ExprError();
7821
Richard Smithb8c0f552016-12-09 18:49:13 +00007822 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
7823 CastKind, CurInit.get(), nullptr,
7824 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00007825
Richard Smithb8c0f552016-12-09 18:49:13 +00007826 if (shouldBindAsTemporary(Entity))
7827 // The overall entity is temporary, so this expression should be
7828 // destroyed at the end of its full-expression.
7829 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7830 else if (CreatedObject && shouldDestroyEntity(Entity)) {
7831 // The object outlasts the full-expression, but we need to prepare for
7832 // a destructor being run on it.
7833 // FIXME: It makes no sense to do this here. This should happen
7834 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00007835 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00007836 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007837 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00007838 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007839 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00007840 S.PDiag(diag::err_access_dtor_temp) << T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007841 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
7842 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
Richard Smith22262ab2013-05-04 06:44:46 +00007843 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00007844 }
7845 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007846 break;
7847 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007848
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007849 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007850 case SK_QualificationConversionXValue:
7851 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007852 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00007853 ExprValueKind VK =
Anastasia Stulova04307942018-11-16 16:22:56 +00007854 Step->Kind == SK_QualificationConversionLValue
7855 ? VK_LValue
7856 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
7857 : VK_RValue);
7858 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007859 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007860 }
7861
Richard Smith77be48a2014-07-31 06:31:19 +00007862 case SK_AtomicConversion: {
7863 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7864 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7865 CK_NonAtomicToAtomic, VK_RValue);
7866 break;
7867 }
7868
Richard Smithaaa0ec42013-09-21 21:19:19 +00007869 case SK_ConversionSequence:
7870 case SK_ConversionSequenceNoNarrowing: {
Leonard Chanad7ac962018-12-06 01:05:54 +00007871 if (const auto *FromPtrType =
7872 CurInit.get()->getType()->getAs<PointerType>()) {
7873 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
7874 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
7875 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
7876 S.Diag(CurInit.get()->getExprLoc(),
7877 diag::warn_noderef_to_dereferenceable_pointer)
7878 << CurInit.get()->getSourceRange();
7879 }
7880 }
7881 }
7882
Richard Smithaaa0ec42013-09-21 21:19:19 +00007883 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007884 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7885 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007886 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007887 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007888 ExprResult CurInitExprRes =
7889 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007890 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007891 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007892 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007893
7894 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7895
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007896 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007897
7898 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007899 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007900 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7901 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007902
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007903 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007905
Douglas Gregor51e77d52009-12-10 17:56:55 +00007906 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007907 if (checkAbstractType(Step->Type))
7908 return ExprError();
7909
John Wiegley01296292011-04-08 18:41:53 +00007910 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007911 // If we're not initializing the top-level entity, we need to create an
7912 // InitializeTemporary entity for our target type.
7913 QualType Ty = Step->Type;
7914 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007915 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007916 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7917 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007918 InitList, Ty, /*VerifyOnly=*/false,
7919 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007920 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007921 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007922
Richard Smithcc1b96d2013-06-12 22:31:48 +00007923 // Hack: We must update *ResultType if available in order to set the
7924 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7925 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7926 if (ResultType &&
7927 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007928 if ((*ResultType)->isRValueReferenceType())
7929 Ty = S.Context.getRValueReferenceType(Ty);
7930 else if ((*ResultType)->isLValueReferenceType())
7931 Ty = S.Context.getLValueReferenceType(Ty,
7932 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7933 *ResultType = Ty;
7934 }
7935
7936 InitListExpr *StructuredInitList =
7937 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007938 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007939 CurInit = shouldBindAsTemporary(InitEntity)
7940 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007941 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007942 break;
7943 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007944
Richard Smith53324112014-07-16 21:33:43 +00007945 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007946 if (checkAbstractType(Step->Type))
7947 return ExprError();
7948
Sebastian Redl5a41f682012-02-12 16:37:24 +00007949 // When an initializer list is passed for a parameter of type "reference
7950 // to object", we don't get an EK_Temporary entity, but instead an
7951 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007952 // FIXME: This is a hack. What we really should do is create a user
7953 // conversion step for this case, but this makes it considerably more
7954 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007955 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7956 Entity.getType().getNonReferenceType());
7957 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007958 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007959 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007960 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7961 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007962 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007963 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7964 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007965 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007966 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007967 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007968 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007969 InitList->getLBraceLoc(),
7970 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007971 break;
7972 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007973
Sebastian Redl29526f02011-11-27 16:50:07 +00007974 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007975 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007976 break;
7977
7978 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007979 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007980 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7981 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007982 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007983 ILE->setSyntacticForm(Syntactic);
7984 ILE->setType(E->getType());
7985 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007986 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007987 break;
7988 }
7989
Richard Smith53324112014-07-16 21:33:43 +00007990 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007991 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007992 if (checkAbstractType(Step->Type))
7993 return ExprError();
7994
Sebastian Redl99f66162012-02-19 12:27:56 +00007995 // When an initializer list is passed for a parameter of type "reference
7996 // to object", we don't get an EK_Temporary entity, but instead an
7997 // EK_Parameter entity with reference type.
7998 // FIXME: This is a hack. What we really should do is create a user
7999 // conversion step for this case, but this makes it considerably more
8000 // complicated. For now, this will do.
8001 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8002 Entity.getType().getNonReferenceType());
8003 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00008004 bool IsStdInitListInit =
8005 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00008006 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00008007 SourceRange Range = Kind.hasParenOrBraceRange()
8008 ? Kind.getParenOrBraceRange()
8009 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00008010 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00008011 S, UseTemporary ? TempEntity : Entity, Kind,
8012 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00008013 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00008014 /*IsListInitialization*/ IsStdInitListInit,
8015 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00008016 /*LBraceLoc*/ Range.getBegin(),
8017 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008018 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00008019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020
Douglas Gregor7dc42e52009-12-15 00:01:57 +00008021 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008022 step_iterator NextStep = Step;
8023 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008024 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00008025 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00008026 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008027 // The need for zero-initialization is recorded directly into
8028 // the call to the object's constructor within the next step.
8029 ConstructorInitRequiresZeroInit = true;
8030 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008031 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008032 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00008033 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8034 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008035 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00008036 Kind.getRange().getBegin());
8037
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008038 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00008039 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008040 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008041 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008042 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008043 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00008044 break;
8045 }
Douglas Gregore1314a62009-12-18 05:02:21 +00008046
8047 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00008048 QualType SourceType = CurInit.get()->getType();
Leonard Chanad7ac962018-12-06 01:05:54 +00008049
George Burgess IV5f21c712015-10-12 19:57:04 +00008050 // Save off the initial CurInit in case we need to emit a diagnostic
8051 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008052 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00008053 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00008054 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
8055 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00008056 if (Result.isInvalid())
8057 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008058 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00008059
8060 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008061 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00008062 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00008063 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00008064 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00008065 == Sema::Compatible)
8066 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00008067 if (CurInitExprRes.isInvalid())
8068 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008069 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00008070
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008071 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00008072 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8073 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00008074 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00008075 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008076 &Complained)) {
8077 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00008078 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008079 } else if (Complained)
8080 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00008081 break;
8082 }
Eli Friedman78275202009-12-19 08:11:05 +00008083
8084 case SK_StringInit: {
8085 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00008086 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00008087 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00008088 break;
8089 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008090
8091 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008092 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00008093 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00008094 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008095 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008096
Richard Smith410306b2016-12-12 02:53:20 +00008097 case SK_ArrayLoopIndex: {
8098 Expr *Cur = CurInit.get();
8099 Expr *BaseExpr = new (S.Context)
8100 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8101 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8102 Expr *IndexExpr =
8103 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
8104 CurInit = S.CreateBuiltinArraySubscriptExpr(
8105 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8106 ArrayLoopCommonExprs.push_back(BaseExpr);
8107 break;
8108 }
8109
8110 case SK_ArrayLoopInit: {
8111 assert(!ArrayLoopCommonExprs.empty() &&
8112 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8113 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8114 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8115 CurInit.get());
8116 break;
8117 }
8118
Richard Smith378b8c82016-12-14 03:22:16 +00008119 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00008120 // Okay: we checked everything before creating this step. Note that
8121 // this is a GNU extension.
8122 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00008123 << Step->Type << CurInit.get()->getType()
8124 << CurInit.get()->getSourceRange();
Eli Friedman88fccbd2019-02-11 22:54:27 +00008125 updateGNUCompoundLiteralRValue(CurInit.get());
Richard Smith378b8c82016-12-14 03:22:16 +00008126 LLVM_FALLTHROUGH;
8127 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00008128 // If the destination type is an incomplete array type, update the
8129 // type accordingly.
8130 if (ResultType) {
8131 if (const IncompleteArrayType *IncompleteDest
8132 = S.Context.getAsIncompleteArrayType(Step->Type)) {
8133 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00008134 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00008135 *ResultType = S.Context.getConstantArrayType(
8136 IncompleteDest->getElementType(),
8137 ConstantSource->getSize(),
8138 ArrayType::Normal, 0);
8139 }
8140 }
8141 }
John McCall31168b02011-06-15 23:02:42 +00008142 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008143
Richard Smithebeed412012-02-15 22:38:09 +00008144 case SK_ParenthesizedArrayInit:
8145 // Okay: we checked everything before creating this step. Note that
8146 // this is a GNU extension.
8147 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8148 << CurInit.get()->getSourceRange();
8149 break;
8150
John McCall31168b02011-06-15 23:02:42 +00008151 case SK_PassByIndirectCopyRestore:
8152 case SK_PassByIndirectRestore:
8153 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008154 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8155 CurInit.get(), Step->Type,
8156 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00008157 break;
8158
8159 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008160 CurInit =
8161 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
8162 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00008163 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008164
8165 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00008166 S.Diag(CurInit.get()->getExprLoc(),
8167 diag::warn_cxx98_compat_initializer_list_init)
8168 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00008169
Richard Smithcc1b96d2013-06-12 22:31:48 +00008170 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00008171 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8172 CurInit.get()->getType(), CurInit.get(),
8173 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00008174
Florian Hahn0aa117d2018-07-17 09:23:31 +00008175 // Wrap it in a construction of a std::initializer_list<T>.
8176 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smith0a9969b2018-07-17 00:11:41 +00008177
Richard Smithcc1b96d2013-06-12 22:31:48 +00008178 // Bind the result, in case the library has given initializer_list a
8179 // non-trivial destructor.
8180 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008181 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00008182 break;
8183 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00008184
Guy Benyei61054192013-02-07 10:55:47 +00008185 case SK_OCLSamplerInit: {
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008186 // Sampler initialization have 5 cases:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008187 // 1. function argument passing
8188 // 1a. argument is a file-scope variable
8189 // 1b. argument is a function-scope variable
8190 // 1c. argument is one of caller function's parameters
8191 // 2. variable initialization
8192 // 2a. initializing a file-scope variable
8193 // 2b. initializing a function-scope variable
8194 //
8195 // For file-scope variables, since they cannot be initialized by function
8196 // call of __translate_sampler_initializer in LLVM IR, their references
8197 // need to be replaced by a cast from their literal initializers to
8198 // sampler type. Since sampler variables can only be used in function
8199 // calls as arguments, we only need to replace them when handling the
8200 // argument passing.
8201 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00008202 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008203 Expr *Init = CurInit.get();
8204 QualType SourceType = Init->getType();
8205 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00008206 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00008207 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00008208 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8209 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008210 break;
8211 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8212 auto Var = cast<VarDecl>(DRE->getDecl());
8213 // Case 1b and 1c
8214 // No cast from integer to sampler is needed.
8215 if (!Var->hasGlobalStorage()) {
8216 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8217 CK_LValueToRValue, Init,
8218 /*BasePath=*/nullptr, VK_RValue);
8219 break;
8220 }
8221 // Case 1a
8222 // For function call with a file-scope sampler variable as argument,
8223 // get the integer literal.
8224 // Do not diagnose if the file-scope variable does not have initializer
8225 // since this has already been diagnosed when parsing the variable
8226 // declaration.
8227 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8228 break;
8229 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8230 Var->getInit()))->getSubExpr();
8231 SourceType = Init->getType();
8232 }
8233 } else {
8234 // Case 2
8235 // Check initializer is 32 bit integer constant.
8236 // If the initializer is taken from global variable, do not diagnose since
8237 // this has already been done when parsing the variable declaration.
8238 if (!Init->isConstantInitializer(S.Context, false))
8239 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00008240
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008241 if (!SourceType->isIntegerType() ||
8242 32 != S.Context.getIntWidth(SourceType)) {
8243 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8244 << SourceType;
8245 break;
8246 }
8247
Fangrui Song407659a2018-11-30 23:41:18 +00008248 Expr::EvalResult EVResult;
8249 Init->EvaluateAsInt(EVResult, S.Context);
8250 llvm::APSInt Result = EVResult.Val.getInt();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008251 const uint64_t SamplerValue = Result.getLimitedValue();
8252 // 32-bit value of sampler's initializer is interpreted as
8253 // bit-field with the following structure:
8254 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8255 // |31 6|5 4|3 1| 0|
8256 // This structure corresponds to enum values of sampler properties
8257 // defined in SPIR spec v1.2 and also opencl-c.h
8258 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8259 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008260 if (FilterMode != 1 && FilterMode != 2 &&
8261 !S.getOpenCLOptions().isEnabled(
8262 "cl_intel_device_side_avc_motion_estimation"))
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008263 S.Diag(Kind.getLocation(),
8264 diag::warn_sampler_initializer_invalid_bits)
8265 << "Filter Mode";
8266 if (AddressingMode > 4)
8267 S.Diag(Kind.getLocation(),
8268 diag::warn_sampler_initializer_invalid_bits)
8269 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00008270 }
8271
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008272 // Cases 1a, 2a and 2b
8273 // Insert cast from integer to sampler.
8274 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
8275 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00008276 break;
8277 }
Andrew Savonichevb555b762018-10-23 15:19:20 +00008278 case SK_OCLZeroOpaqueType: {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008279 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8280 Step->Type->isOCLIntelSubgroupAVCType()) &&
Andrew Savonichevb555b762018-10-23 15:19:20 +00008281 "Wrong type for initialization of OpenCL opaque type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008282
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008283 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Andrew Savonichevb555b762018-10-23 15:19:20 +00008284 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00008285 CurInit.get()->getValueKind());
8286 break;
8287 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008288 }
8289 }
John McCall1f425642010-11-11 03:21:53 +00008290
Richard Smithca975b22018-07-23 18:50:26 +00008291 // Check whether the initializer has a shorter lifetime than the initialized
8292 // entity, and if not, either lifetime-extend or warn as appropriate.
8293 if (auto *Init = CurInit.get())
8294 S.checkInitializerLifetime(Entity, Init);
8295
John McCall1f425642010-11-11 03:21:53 +00008296 // Diagnose non-fatal problems with the completed initialization.
8297 if (Entity.getKind() == InitializedEntity::EK_Member &&
8298 cast<FieldDecl>(Entity.getDecl())->isBitField())
8299 S.CheckBitFieldInitialization(Kind.getLocation(),
8300 cast<FieldDecl>(Entity.getDecl()),
8301 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008302
Richard Trieuac3eca52015-04-29 01:52:17 +00008303 // Check for std::move on construction.
8304 if (const Expr *E = CurInit.get()) {
8305 CheckMoveOnConstruction(S, E,
8306 Entity.getKind() == InitializedEntity::EK_Result);
8307 }
8308
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008309 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008310}
8311
Richard Smith593f9932012-12-08 02:01:17 +00008312/// Somewhere within T there is an uninitialized reference subobject.
8313/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00008314static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8315 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00008316 if (T->isReferenceType()) {
8317 S.Diag(Loc, diag::err_reference_without_init)
8318 << T.getNonReferenceType();
8319 return true;
8320 }
8321
8322 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8323 if (!RD || !RD->hasUninitializedReferenceMember())
8324 return false;
8325
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008326 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00008327 if (FI->isUnnamedBitfield())
8328 continue;
8329
8330 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8331 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8332 return true;
8333 }
8334 }
8335
Aaron Ballman574705e2014-03-13 15:41:46 +00008336 for (const auto &BI : RD->bases()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008337 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00008338 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8339 return true;
8340 }
8341 }
8342
8343 return false;
8344}
8345
8346
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008347//===----------------------------------------------------------------------===//
8348// Diagnose initialization failures
8349//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00008350
8351/// Emit notes associated with an initialization that failed due to a
8352/// "simple" conversion failure.
8353static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8354 Expr *op) {
8355 QualType destType = entity.getType();
8356 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8357 op->getType()->isObjCObjectPointerType()) {
8358
8359 // Emit a possible note about the conversion failing because the
8360 // operand is a message send with a related result type.
8361 S.EmitRelatedResultTypeNote(op);
8362
8363 // Emit a possible note about a return failing because we're
8364 // expecting a related result type.
8365 if (entity.getKind() == InitializedEntity::EK_Result)
8366 S.EmitRelatedResultTypeNoteForReturn(destType);
8367 }
8368}
8369
Richard Smith0449aaf2013-11-21 23:30:57 +00008370static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8371 InitListExpr *InitList) {
8372 QualType DestType = Entity.getType();
8373
8374 QualType E;
8375 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8376 QualType ArrayType = S.Context.getConstantArrayType(
8377 E.withConst(),
8378 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8379 InitList->getNumInits()),
8380 clang::ArrayType::Normal, 0);
8381 InitializedEntity HiddenArray =
8382 InitializedEntity::InitializeTemporary(ArrayType);
8383 return diagnoseListInit(S, HiddenArray, InitList);
8384 }
8385
Richard Smith8d082d12014-09-04 22:13:39 +00008386 if (DestType->isReferenceType()) {
8387 // A list-initialization failure for a reference means that we tried to
8388 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8389 // inner initialization failed.
8390 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
8391 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008392 SourceLocation Loc = InitList->getBeginLoc();
Richard Smith8d082d12014-09-04 22:13:39 +00008393 if (auto *D = Entity.getDecl())
8394 Loc = D->getLocation();
8395 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8396 return;
8397 }
8398
Richard Smith0449aaf2013-11-21 23:30:57 +00008399 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00008400 /*VerifyOnly=*/false,
8401 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00008402 assert(DiagnoseInitList.HadError() &&
8403 "Inconsistent init list check result.");
8404}
8405
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008406bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008407 const InitializedEntity &Entity,
8408 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008409 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00008410 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008411 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008412
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008413 // When we want to diagnose only one element of a braced-init-list,
8414 // we need to factor it out.
8415 Expr *OnlyArg;
8416 if (Args.size() == 1) {
8417 auto *List = dyn_cast<InitListExpr>(Args[0]);
8418 if (List && List->getNumInits() == 1)
8419 OnlyArg = List->getInit(0);
8420 else
8421 OnlyArg = Args[0];
8422 }
8423 else
8424 OnlyArg = nullptr;
8425
Douglas Gregor1b303932009-12-22 15:35:07 +00008426 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008427 switch (Failure) {
8428 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008429 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008430 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00008431 // Dig out the reference subobject which is uninitialized and diagnose it.
8432 // If this is value-initialization, this could be nested some way within
8433 // the target type.
8434 assert(Kind.getKind() == InitializationKind::IK_Value ||
8435 DestType->isReferenceType());
8436 bool Diagnosed =
8437 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8438 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8439 (void)Diagnosed;
8440 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008441 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008442 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008443 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00008444 case FK_ParenthesizedListInitForReference:
8445 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8446 << 1 << Entity.getType() << Args[0]->getSourceRange();
8447 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008448
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008449 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008450 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008451 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008452 case FK_ArrayNeedsInitListOrStringLiteral:
8453 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8454 break;
8455 case FK_ArrayNeedsInitListOrWideStringLiteral:
8456 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8457 break;
8458 case FK_NarrowStringIntoWideCharArray:
8459 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8460 break;
8461 case FK_WideStringIntoCharArray:
8462 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8463 break;
8464 case FK_IncompatWideStringIntoWideChar:
8465 S.Diag(Kind.getLocation(),
8466 diag::err_array_init_incompat_wide_string_into_wchar);
8467 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00008468 case FK_PlainStringIntoUTF8Char:
8469 S.Diag(Kind.getLocation(),
8470 diag::err_array_init_plain_string_into_char8_t);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008471 S.Diag(Args.front()->getBeginLoc(),
Richard Smith3a8244d2018-05-01 05:02:45 +00008472 diag::note_array_init_plain_string_into_char8_t)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008473 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
Richard Smith3a8244d2018-05-01 05:02:45 +00008474 break;
8475 case FK_UTF8StringIntoPlainChar:
8476 S.Diag(Kind.getLocation(),
Richard Smith28ddb912018-11-14 21:04:34 +00008477 diag::err_array_init_utf8_string_into_char)
8478 << S.getLangOpts().CPlusPlus2a;
Richard Smith3a8244d2018-05-01 05:02:45 +00008479 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008480 case FK_ArrayTypeMismatch:
8481 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00008482 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00008483 (Failure == FK_ArrayTypeMismatch
8484 ? diag::err_array_init_different_type
8485 : diag::err_array_init_non_constant_array))
8486 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008487 << OnlyArg->getType()
Douglas Gregore2f943b2011-02-22 18:29:51 +00008488 << Args[0]->getSourceRange();
8489 break;
8490
John McCalla59dc2f2012-01-05 00:13:19 +00008491 case FK_VariableLengthArrayHasInitializer:
8492 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8493 << Args[0]->getSourceRange();
8494 break;
8495
John McCall16df1e52010-03-30 21:47:33 +00008496 case FK_AddressOfOverloadFailed: {
8497 DeclAccessPair Found;
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008498 S.ResolveAddressOfOverloadedFunction(OnlyArg,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008499 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00008500 true,
8501 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008502 break;
John McCall16df1e52010-03-30 21:47:33 +00008503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008504
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008505 case FK_AddressOfUnaddressableFunction: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008506 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008507 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008508 OnlyArg->getBeginLoc());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008509 break;
8510 }
8511
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008512 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00008513 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008514 switch (FailedOverloadResult) {
8515 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00008516
David Blaikie5e328052019-05-03 00:44:50 +00008517 FailedCandidateSet.NoteCandidates(
8518 PartialDiagnosticAt(
8519 Kind.getLocation(),
8520 Failure == FK_UserConversionOverloadFailed
8521 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
8522 << OnlyArg->getType() << DestType
8523 << Args[0]->getSourceRange())
8524 : (S.PDiag(diag::err_ref_init_ambiguous)
8525 << DestType << OnlyArg->getType()
8526 << Args[0]->getSourceRange())),
8527 S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008528 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008529
David Blaikie5e328052019-05-03 00:44:50 +00008530 case OR_No_Viable_Function: {
8531 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
Larisse Voufo70bb43a2013-06-27 03:36:30 +00008532 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008533 DestType.getNonReferenceType(),
8534 diag::err_typecheck_nonviable_condition_incomplete,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008535 OnlyArg->getType(), Args[0]->getSourceRange()))
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008536 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00008537 << (Entity.getKind() == InitializedEntity::EK_Result)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008538 << OnlyArg->getType() << Args[0]->getSourceRange()
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008539 << DestType.getNonReferenceType();
8540
David Blaikie5e328052019-05-03 00:44:50 +00008541 FailedCandidateSet.NoteCandidates(S, Args, Cands);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008542 break;
David Blaikie5e328052019-05-03 00:44:50 +00008543 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008544 case OR_Deleted: {
8545 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008546 << OnlyArg->getType() << DestType.getNonReferenceType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008547 << Args[0]->getSourceRange();
8548 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008549 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00008550 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008551 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00008552 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008553 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008554 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008555 }
8556 break;
8557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008558
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008559 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008560 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008561 }
8562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008563
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008564 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00008565 if (isa<InitListExpr>(Args[0])) {
8566 S.Diag(Kind.getLocation(),
8567 diag::err_lvalue_reference_bind_to_initlist)
8568 << DestType.getNonReferenceType().isVolatileQualified()
8569 << DestType.getNonReferenceType()
8570 << Args[0]->getSourceRange();
8571 break;
8572 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008573 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00008574
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008575 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008576 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008577 Failure == FK_NonConstLValueReferenceBindingToTemporary
8578 ? diag::err_lvalue_reference_bind_to_temporary
8579 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00008580 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008581 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008582 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008583 << Args[0]->getSourceRange();
8584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008585
Richard Smithb8c0f552016-12-09 18:49:13 +00008586 case FK_NonConstLValueReferenceBindingToBitfield: {
8587 // We don't necessarily have an unambiguous source bit-field.
8588 FieldDecl *BitField = Args[0]->getSourceBitField();
8589 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
8590 << DestType.isVolatileQualified()
8591 << (BitField ? BitField->getDeclName() : DeclarationName())
8592 << (BitField != nullptr)
8593 << Args[0]->getSourceRange();
8594 if (BitField)
8595 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8596 break;
8597 }
8598
8599 case FK_NonConstLValueReferenceBindingToVectorElement:
8600 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
8601 << DestType.isVolatileQualified()
8602 << Args[0]->getSourceRange();
8603 break;
8604
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008605 case FK_RValueReferenceBindingToLValue:
8606 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008607 << DestType.getNonReferenceType() << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008608 << Args[0]->getSourceRange();
8609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008610
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00008611 case FK_ReferenceAddrspaceMismatchTemporary:
8612 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
8613 << DestType << Args[0]->getSourceRange();
8614 break;
8615
Richard Trieuf956a492015-05-16 01:27:03 +00008616 case FK_ReferenceInitDropsQualifiers: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008617 QualType SourceType = OnlyArg->getType();
Richard Trieuf956a492015-05-16 01:27:03 +00008618 QualType NonRefType = DestType.getNonReferenceType();
8619 Qualifiers DroppedQualifiers =
8620 SourceType.getQualifiers() - NonRefType.getQualifiers();
8621
Anastasia Stulova3562edb2019-06-21 11:36:15 +00008622 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
8623 SourceType.getQualifiers()))
8624 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8625 << NonRefType << SourceType << 1 /*addr space*/
8626 << Args[0]->getSourceRange();
8627 else
8628 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8629 << NonRefType << SourceType << 0 /*cv quals*/
8630 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
8631 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008632 break;
Richard Trieuf956a492015-05-16 01:27:03 +00008633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008634
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008635 case FK_ReferenceInitFailed:
8636 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
8637 << DestType.getNonReferenceType()
Eric Fiselier1147f712019-02-01 22:06:02 +00008638 << DestType.getNonReferenceType()->isIncompleteType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008639 << OnlyArg->isLValue()
8640 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008641 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00008642 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008643 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008644
Douglas Gregorb491ed32011-02-19 21:32:49 +00008645 case FK_ConversionFailed: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008646 QualType FromType = OnlyArg->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00008647 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00008648 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008649 << DestType
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008650 << OnlyArg->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00008651 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008652 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008653 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
8654 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00008655 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00008656 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008657 }
John Wiegley01296292011-04-08 18:41:53 +00008658
8659 case FK_ConversionFromPropertyFailed:
8660 // No-op. This error has already been reported.
8661 break;
8662
Douglas Gregor51e77d52009-12-10 17:56:55 +00008663 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00008664 SourceRange R;
8665
David Majnemerbd385442015-04-10 04:52:06 +00008666 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008667 if (InitList && InitList->getNumInits() >= 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008668 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008669 } else {
8670 assert(Args.size() > 1 && "Expected multiple initializers!");
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008671 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008672 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00008673
Alp Tokerb6cc5922014-05-03 03:45:55 +00008674 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00008675 if (Kind.isCStyleOrFunctionalCast())
8676 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
8677 << R;
8678 else
8679 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
8680 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00008681 break;
8682 }
8683
Richard Smith49a6b6e2017-03-24 01:14:25 +00008684 case FK_ParenthesizedListInitForScalar:
8685 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8686 << 0 << Entity.getType() << Args[0]->getSourceRange();
8687 break;
8688
Douglas Gregor51e77d52009-12-10 17:56:55 +00008689 case FK_ReferenceBindingToInitList:
8690 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
8691 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8692 break;
8693
8694 case FK_InitListBadDestinationType:
8695 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8696 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8697 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008698
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008699 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008700 case FK_ConstructorOverloadFailed: {
8701 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008702 if (Args.size())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008703 ArgsRange =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008704 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008705
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008706 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00008707 assert(Args.size() == 1 &&
8708 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008709 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008710 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008711 }
8712
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008713 // FIXME: Using "DestType" for the entity we're printing is probably
8714 // bad.
8715 switch (FailedOverloadResult) {
8716 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00008717 FailedCandidateSet.NoteCandidates(
8718 PartialDiagnosticAt(Kind.getLocation(),
8719 S.PDiag(diag::err_ovl_ambiguous_init)
8720 << DestType << ArgsRange),
8721 S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008722 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008723
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008724 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008725 if (Kind.getKind() == InitializationKind::IK_Default &&
8726 (Entity.getKind() == InitializedEntity::EK_Base ||
8727 Entity.getKind() == InitializedEntity::EK_Member) &&
8728 isa<CXXConstructorDecl>(S.CurContext)) {
8729 // This is implicit default initialization of a member or
8730 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00008731 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008732 // initialize this base/member.
8733 CXXConstructorDecl *Constructor
8734 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00008735 const CXXRecordDecl *InheritedFrom = nullptr;
8736 if (auto Inherited = Constructor->getInheritedConstructor())
8737 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008738 if (Entity.getKind() == InitializedEntity::EK_Base) {
8739 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008740 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008741 << S.Context.getTypeDeclType(Constructor->getParent())
8742 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00008743 << Entity.getType()
8744 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008745
8746 RecordDecl *BaseDecl
8747 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
8748 ->getDecl();
8749 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8750 << S.Context.getTagDeclType(BaseDecl);
8751 } else {
8752 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008753 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008754 << S.Context.getTypeDeclType(Constructor->getParent())
8755 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00008756 << Entity.getName()
8757 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00008758 S.Diag(Entity.getDecl()->getLocation(),
8759 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008760
8761 if (const RecordType *Record
8762 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008763 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008764 diag::note_previous_decl)
8765 << S.Context.getTagDeclType(Record->getDecl());
8766 }
8767 break;
8768 }
8769
David Blaikie5e328052019-05-03 00:44:50 +00008770 FailedCandidateSet.NoteCandidates(
8771 PartialDiagnosticAt(
8772 Kind.getLocation(),
8773 S.PDiag(diag::err_ovl_no_viable_function_in_init)
8774 << DestType << ArgsRange),
8775 S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008776 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008777
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008778 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008779 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008780 OverloadingResult Ovl
8781 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00008782 if (Ovl != OR_Deleted) {
8783 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
Erik Pilkington13ee62f2019-03-20 19:26:33 +00008784 << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008785 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00008786 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008787 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008788
Douglas Gregor74f7d502012-02-15 19:33:52 +00008789 // If this is a defaulted or implicitly-declared function, then
8790 // it was implicitly deleted. Make it clear that the deletion was
8791 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00008792 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008793 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00008794 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008795 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00008796 else
8797 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
Erik Pilkington13ee62f2019-03-20 19:26:33 +00008798 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00008799
8800 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008801 break;
8802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008803
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008804 case OR_Success:
8805 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008806 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008807 }
David Blaikie60deeee2012-01-17 08:24:58 +00008808 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008809
Douglas Gregor85dabae2009-12-16 01:38:02 +00008810 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008811 if (Entity.getKind() == InitializedEntity::EK_Member &&
8812 isa<CXXConstructorDecl>(S.CurContext)) {
8813 // This is implicit default-initialization of a const member in
8814 // a constructor. Complain that it needs to be explicitly
8815 // initialized.
8816 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
8817 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00008818 << (Constructor->getInheritedConstructor() ? 2 :
8819 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008820 << S.Context.getTypeDeclType(Constructor->getParent())
8821 << /*const=*/1
8822 << Entity.getName();
8823 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
8824 << Entity.getName();
8825 } else {
8826 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00008827 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008828 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00008829 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008830
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008831 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00008832 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008833 diag::err_init_incomplete_type);
8834 break;
8835
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008836 case FK_ListInitializationFailed: {
8837 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00008838 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8839 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008840 break;
8841 }
John McCall4124c492011-10-17 18:40:02 +00008842
8843 case FK_PlaceholderType: {
8844 // FIXME: Already diagnosed!
8845 break;
8846 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00008847
Sebastian Redl048a6d72012-04-01 19:54:59 +00008848 case FK_ExplicitConstructor: {
8849 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
8850 << Args[0]->getSourceRange();
8851 OverloadCandidateSet::iterator Best;
8852 OverloadingResult Ovl
8853 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00008854 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008855 assert(Ovl == OR_Success && "Inconsistent overload resolution");
8856 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00008857 S.Diag(CtorDecl->getLocation(),
8858 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008859 break;
8860 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008862
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008863 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008864 return true;
8865}
Douglas Gregore1314a62009-12-18 05:02:21 +00008866
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008867void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008868 switch (SequenceKind) {
8869 case FailedSequence: {
8870 OS << "Failed sequence: ";
8871 switch (Failure) {
8872 case FK_TooManyInitsForReference:
8873 OS << "too many initializers for reference";
8874 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008875
Richard Smith49a6b6e2017-03-24 01:14:25 +00008876 case FK_ParenthesizedListInitForReference:
8877 OS << "parenthesized list init for reference";
8878 break;
8879
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008880 case FK_ArrayNeedsInitList:
8881 OS << "array requires initializer list";
8882 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008883
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008884 case FK_AddressOfUnaddressableFunction:
8885 OS << "address of unaddressable function was taken";
8886 break;
8887
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008888 case FK_ArrayNeedsInitListOrStringLiteral:
8889 OS << "array requires initializer list or string literal";
8890 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008891
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008892 case FK_ArrayNeedsInitListOrWideStringLiteral:
8893 OS << "array requires initializer list or wide string literal";
8894 break;
8895
8896 case FK_NarrowStringIntoWideCharArray:
8897 OS << "narrow string into wide char array";
8898 break;
8899
8900 case FK_WideStringIntoCharArray:
8901 OS << "wide string into char array";
8902 break;
8903
8904 case FK_IncompatWideStringIntoWideChar:
8905 OS << "incompatible wide string into wide char array";
8906 break;
8907
Richard Smith3a8244d2018-05-01 05:02:45 +00008908 case FK_PlainStringIntoUTF8Char:
8909 OS << "plain string literal into char8_t array";
8910 break;
8911
8912 case FK_UTF8StringIntoPlainChar:
8913 OS << "u8 string literal into char array";
8914 break;
8915
Douglas Gregore2f943b2011-02-22 18:29:51 +00008916 case FK_ArrayTypeMismatch:
8917 OS << "array type mismatch";
8918 break;
8919
8920 case FK_NonConstantArrayInit:
8921 OS << "non-constant array initializer";
8922 break;
8923
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008924 case FK_AddressOfOverloadFailed:
8925 OS << "address of overloaded function failed";
8926 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008927
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008928 case FK_ReferenceInitOverloadFailed:
8929 OS << "overload resolution for reference initialization failed";
8930 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008931
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008932 case FK_NonConstLValueReferenceBindingToTemporary:
8933 OS << "non-const lvalue reference bound to temporary";
8934 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008935
Richard Smithb8c0f552016-12-09 18:49:13 +00008936 case FK_NonConstLValueReferenceBindingToBitfield:
8937 OS << "non-const lvalue reference bound to bit-field";
8938 break;
8939
8940 case FK_NonConstLValueReferenceBindingToVectorElement:
8941 OS << "non-const lvalue reference bound to vector element";
8942 break;
8943
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008944 case FK_NonConstLValueReferenceBindingToUnrelated:
8945 OS << "non-const lvalue reference bound to unrelated type";
8946 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008947
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008948 case FK_RValueReferenceBindingToLValue:
8949 OS << "rvalue reference bound to an lvalue";
8950 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008951
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008952 case FK_ReferenceInitDropsQualifiers:
8953 OS << "reference initialization drops qualifiers";
8954 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008955
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00008956 case FK_ReferenceAddrspaceMismatchTemporary:
8957 OS << "reference with mismatching address space bound to temporary";
8958 break;
8959
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008960 case FK_ReferenceInitFailed:
8961 OS << "reference initialization failed";
8962 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008963
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008964 case FK_ConversionFailed:
8965 OS << "conversion failed";
8966 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008967
John Wiegley01296292011-04-08 18:41:53 +00008968 case FK_ConversionFromPropertyFailed:
8969 OS << "conversion from property failed";
8970 break;
8971
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008972 case FK_TooManyInitsForScalar:
8973 OS << "too many initializers for scalar";
8974 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008975
Richard Smith49a6b6e2017-03-24 01:14:25 +00008976 case FK_ParenthesizedListInitForScalar:
8977 OS << "parenthesized list init for reference";
8978 break;
8979
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008980 case FK_ReferenceBindingToInitList:
8981 OS << "referencing binding to initializer list";
8982 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008983
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008984 case FK_InitListBadDestinationType:
8985 OS << "initializer list for non-aggregate, non-scalar type";
8986 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008987
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008988 case FK_UserConversionOverloadFailed:
8989 OS << "overloading failed for user-defined conversion";
8990 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008991
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008992 case FK_ConstructorOverloadFailed:
8993 OS << "constructor overloading failed";
8994 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008995
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008996 case FK_DefaultInitOfConst:
8997 OS << "default initialization of a const variable";
8998 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008999
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00009000 case FK_Incomplete:
9001 OS << "initialization of incomplete type";
9002 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00009003
9004 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009005 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00009006 break;
9007
John McCalla59dc2f2012-01-05 00:13:19 +00009008 case FK_VariableLengthArrayHasInitializer:
9009 OS << "variable length array has an initializer";
9010 break;
9011
John McCall4124c492011-10-17 18:40:02 +00009012 case FK_PlaceholderType:
9013 OS << "initializer expression isn't contextually valid";
9014 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00009015
9016 case FK_ListConstructorOverloadFailed:
9017 OS << "list constructor overloading failed";
9018 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00009019
Sebastian Redl048a6d72012-04-01 19:54:59 +00009020 case FK_ExplicitConstructor:
9021 OS << "list copy initialization chose explicit constructor";
9022 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009023 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009024 OS << '\n';
9025 return;
9026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009027
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009028 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00009029 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009030 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009031
Sebastian Redld201edf2011-06-05 13:59:11 +00009032 case NormalSequence:
9033 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009034 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009036
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009037 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9038 if (S != step_begin()) {
9039 OS << " -> ";
9040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009041
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009042 switch (S->Kind) {
9043 case SK_ResolveAddressOfOverloadedFunction:
9044 OS << "resolve address of overloaded function";
9045 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009046
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009047 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00009048 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009049 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009050
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009051 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00009052 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009053 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009054
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009055 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00009056 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009057 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009058
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009059 case SK_BindReference:
9060 OS << "bind reference to lvalue";
9061 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009062
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009063 case SK_BindReferenceToTemporary:
9064 OS << "bind reference to a temporary";
9065 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009066
Richard Smithb8c0f552016-12-09 18:49:13 +00009067 case SK_FinalCopy:
9068 OS << "final copy in class direct-initialization";
9069 break;
9070
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00009071 case SK_ExtraneousCopyToTemporary:
9072 OS << "extraneous C++03 copy to temporary";
9073 break;
9074
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009075 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00009076 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009077 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009078
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009079 case SK_QualificationConversionRValue:
9080 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00009081 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009082
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009083 case SK_QualificationConversionXValue:
9084 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00009085 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009086
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009087 case SK_QualificationConversionLValue:
9088 OS << "qualification conversion (lvalue)";
9089 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009090
Richard Smith77be48a2014-07-31 06:31:19 +00009091 case SK_AtomicConversion:
9092 OS << "non-atomic-to-atomic conversion";
9093 break;
9094
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009095 case SK_ConversionSequence:
9096 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00009097 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009098 OS << ")";
9099 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009100
Richard Smithaaa0ec42013-09-21 21:19:19 +00009101 case SK_ConversionSequenceNoNarrowing:
9102 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00009103 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00009104 OS << ")";
9105 break;
9106
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009107 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00009108 OS << "list aggregate initialization";
9109 break;
9110
Sebastian Redl29526f02011-11-27 16:50:07 +00009111 case SK_UnwrapInitList:
9112 OS << "unwrap reference initializer list";
9113 break;
9114
9115 case SK_RewrapInitList:
9116 OS << "rewrap reference initializer list";
9117 break;
9118
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009119 case SK_ConstructorInitialization:
9120 OS << "constructor initialization";
9121 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009122
Richard Smith53324112014-07-16 21:33:43 +00009123 case SK_ConstructorInitializationFromList:
9124 OS << "list initialization via constructor";
9125 break;
9126
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009127 case SK_ZeroInitialization:
9128 OS << "zero initialization";
9129 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009130
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009131 case SK_CAssignment:
9132 OS << "C assignment";
9133 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009134
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009135 case SK_StringInit:
9136 OS << "string initialization";
9137 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00009138
9139 case SK_ObjCObjectConversion:
9140 OS << "Objective-C object conversion";
9141 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00009142
Richard Smith410306b2016-12-12 02:53:20 +00009143 case SK_ArrayLoopIndex:
9144 OS << "indexing for array initialization loop";
9145 break;
9146
9147 case SK_ArrayLoopInit:
9148 OS << "array initialization loop";
9149 break;
9150
Douglas Gregore2f943b2011-02-22 18:29:51 +00009151 case SK_ArrayInit:
9152 OS << "array initialization";
9153 break;
John McCall31168b02011-06-15 23:02:42 +00009154
Richard Smith378b8c82016-12-14 03:22:16 +00009155 case SK_GNUArrayInit:
9156 OS << "array initialization (GNU extension)";
9157 break;
9158
Richard Smithebeed412012-02-15 22:38:09 +00009159 case SK_ParenthesizedArrayInit:
9160 OS << "parenthesized array initialization";
9161 break;
9162
John McCall31168b02011-06-15 23:02:42 +00009163 case SK_PassByIndirectCopyRestore:
9164 OS << "pass by indirect copy and restore";
9165 break;
9166
9167 case SK_PassByIndirectRestore:
9168 OS << "pass by indirect restore";
9169 break;
9170
9171 case SK_ProduceObjCObject:
9172 OS << "Objective-C object retension";
9173 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00009174
9175 case SK_StdInitializerList:
9176 OS << "std::initializer_list from initializer list";
9177 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009178
Richard Smithf8adcdc2014-07-17 05:12:35 +00009179 case SK_StdInitializerListConstructorCall:
9180 OS << "list initialization from std::initializer_list";
9181 break;
9182
Guy Benyei61054192013-02-07 10:55:47 +00009183 case SK_OCLSamplerInit:
9184 OS << "OpenCL sampler_t from integer constant";
9185 break;
9186
Andrew Savonichevb555b762018-10-23 15:19:20 +00009187 case SK_OCLZeroOpaqueType:
9188 OS << "OpenCL opaque type from zero";
Egor Churaev89831422016-12-23 14:55:49 +00009189 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009190 }
Richard Smith6b216962013-02-05 05:52:24 +00009191
9192 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009193 }
Richard Smith6b216962013-02-05 05:52:24 +00009194
9195 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009196}
9197
9198void InitializationSequence::dump() const {
9199 dump(llvm::errs());
9200}
9201
Nico Weber3d7f00d2018-06-19 23:19:34 +00009202static bool NarrowingErrs(const LangOptions &L) {
9203 return L.CPlusPlus11 &&
9204 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
9205}
9206
Richard Smithaaa0ec42013-09-21 21:19:19 +00009207static void DiagnoseNarrowingInInitList(Sema &S,
9208 const ImplicitConversionSequence &ICS,
9209 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00009210 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00009211 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009212 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00009213 switch (ICS.getKind()) {
9214 case ImplicitConversionSequence::StandardConversion:
9215 SCS = &ICS.Standard;
9216 break;
9217 case ImplicitConversionSequence::UserDefinedConversion:
9218 SCS = &ICS.UserDefined.After;
9219 break;
9220 case ImplicitConversionSequence::AmbiguousConversion:
9221 case ImplicitConversionSequence::EllipsisConversion:
9222 case ImplicitConversionSequence::BadConversion:
9223 return;
9224 }
9225
Richard Smith66e05fe2012-01-18 05:21:49 +00009226 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9227 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00009228 QualType ConstantType;
9229 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9230 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00009231 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00009232 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00009233 // No narrowing occurred.
9234 return;
9235
9236 case NK_Type_Narrowing:
9237 // This was a floating-to-integer conversion, which is always considered a
9238 // narrowing conversion even if the value is a constant and can be
9239 // represented exactly as an integer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009240 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
Nico Weber3d7f00d2018-06-19 23:19:34 +00009241 ? diag::ext_init_list_type_narrowing
9242 : diag::warn_init_list_type_narrowing)
9243 << PostInit->getSourceRange()
9244 << PreNarrowingType.getLocalUnqualifiedType()
9245 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009246 break;
9247
9248 case NK_Constant_Narrowing:
9249 // A constant value was narrowed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009250 S.Diag(PostInit->getBeginLoc(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00009251 NarrowingErrs(S.getLangOpts())
9252 ? diag::ext_init_list_constant_narrowing
9253 : diag::warn_init_list_constant_narrowing)
9254 << PostInit->getSourceRange()
9255 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9256 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009257 break;
9258
9259 case NK_Variable_Narrowing:
9260 // A variable's value may have been narrowed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009261 S.Diag(PostInit->getBeginLoc(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00009262 NarrowingErrs(S.getLangOpts())
9263 ? diag::ext_init_list_variable_narrowing
9264 : diag::warn_init_list_variable_narrowing)
9265 << PostInit->getSourceRange()
9266 << PreNarrowingType.getLocalUnqualifiedType()
9267 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009268 break;
9269 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009270
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009271 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009272 llvm::raw_svector_ostream OS(StaticCast);
9273 OS << "static_cast<";
9274 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9275 // It's important to use the typedef's name if there is one so that the
9276 // fixit doesn't break code using types like int64_t.
9277 //
9278 // FIXME: This will break if the typedef requires qualification. But
9279 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00009280 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009281 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00009282 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009283 else {
9284 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9285 // with a broken cast.
9286 return;
9287 }
9288 OS << ">(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009289 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009290 << PostInit->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009291 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
Alp Tokerb6cc5922014-05-03 03:45:55 +00009292 << FixItHint::CreateInsertion(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009293 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009294}
9295
Douglas Gregore1314a62009-12-18 05:02:21 +00009296//===----------------------------------------------------------------------===//
9297// Initialization helper functions
9298//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00009299bool
9300Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
9301 ExprResult Init) {
9302 if (Init.isInvalid())
9303 return false;
9304
9305 Expr *InitE = Init.get();
9306 assert(InitE && "No initialization expression");
9307
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009308 InitializationKind Kind =
9309 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00009310 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00009311 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00009312}
9313
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009314ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00009315Sema::PerformCopyInitialization(const InitializedEntity &Entity,
9316 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009317 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00009318 bool TopLevelOfInitList,
9319 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00009320 if (Init.isInvalid())
9321 return ExprError();
9322
John McCall1f425642010-11-11 03:21:53 +00009323 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00009324 assert(InitE && "No initialization expression?");
9325
9326 if (EqualLoc.isInvalid())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009327 EqualLoc = InitE->getBeginLoc();
Douglas Gregore1314a62009-12-18 05:02:21 +00009328
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009329 InitializationKind Kind = InitializationKind::CreateCopy(
9330 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00009331 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009332
Alex Lorenzde69ff92017-05-16 10:23:58 +00009333 // Prevent infinite recursion when performing parameter copy-initialization.
9334 const bool ShouldTrackCopy =
9335 Entity.isParameterKind() && Seq.isConstructorInitialization();
9336 if (ShouldTrackCopy) {
9337 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
9338 CurrentParameterCopyTypes.end()) {
9339 Seq.SetOverloadFailure(
9340 InitializationSequence::FK_ConstructorOverloadFailed,
9341 OR_No_Viable_Function);
9342
9343 // Try to give a meaningful diagnostic note for the problematic
9344 // constructor.
9345 const auto LastStep = Seq.step_end() - 1;
9346 assert(LastStep->Kind ==
9347 InitializationSequence::SK_ConstructorInitialization);
9348 const FunctionDecl *Function = LastStep->Function.Function;
9349 auto Candidate =
9350 llvm::find_if(Seq.getFailedCandidateSet(),
9351 [Function](const OverloadCandidate &Candidate) -> bool {
9352 return Candidate.Viable &&
9353 Candidate.Function == Function &&
9354 Candidate.Conversions.size() > 0;
9355 });
9356 if (Candidate != Seq.getFailedCandidateSet().end() &&
9357 Function->getNumParams() > 0) {
9358 Candidate->Viable = false;
9359 Candidate->FailureKind = ovl_fail_bad_conversion;
9360 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9361 InitE,
9362 Function->getParamDecl(0)->getType());
9363 }
9364 }
9365 CurrentParameterCopyTypes.push_back(Entity.getType());
9366 }
9367
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00009368 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00009369
Alex Lorenzde69ff92017-05-16 10:23:58 +00009370 if (ShouldTrackCopy)
9371 CurrentParameterCopyTypes.pop_back();
9372
Richard Smith66e05fe2012-01-18 05:21:49 +00009373 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00009374}
Richard Smith60437622017-02-09 19:17:44 +00009375
Richard Smith1363e8f2017-09-07 07:22:36 +00009376/// Determine whether RD is, or is derived from, a specialization of CTD.
9377static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
9378 ClassTemplateDecl *CTD) {
9379 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9380 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9381 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9382 };
9383 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9384}
9385
Richard Smith60437622017-02-09 19:17:44 +00009386QualType Sema::DeduceTemplateSpecializationFromInitializer(
9387 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9388 const InitializationKind &Kind, MultiExprArg Inits) {
9389 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9390 TSInfo->getType()->getContainedDeducedType());
9391 assert(DeducedTST && "not a deduced template specialization type");
9392
Richard Smith60437622017-02-09 19:17:44 +00009393 auto TemplateName = DeducedTST->getTemplateName();
Richard Smithcff42012018-09-28 03:18:53 +00009394 if (TemplateName.isDependent())
9395 return Context.DependentTy;
9396
9397 // We can only perform deduction for class templates.
Richard Smith60437622017-02-09 19:17:44 +00009398 auto *Template =
9399 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
9400 if (!Template) {
9401 Diag(Kind.getLocation(),
9402 diag::err_deduced_non_class_template_specialization_type)
9403 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
9404 if (auto *TD = TemplateName.getAsTemplateDecl())
9405 Diag(TD->getLocation(), diag::note_template_decl_here);
9406 return QualType();
9407 }
9408
Richard Smith32918772017-02-14 00:25:28 +00009409 // Can't deduce from dependent arguments.
Richard Smith8eeb16f2018-09-10 20:31:03 +00009410 if (Expr::hasAnyTypeDependentArguments(Inits)) {
9411 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9412 diag::warn_cxx14_compat_class_template_argument_deduction)
9413 << TSInfo->getTypeLoc().getSourceRange() << 0;
Richard Smith32918772017-02-14 00:25:28 +00009414 return Context.DependentTy;
Richard Smith8eeb16f2018-09-10 20:31:03 +00009415 }
Richard Smith32918772017-02-14 00:25:28 +00009416
Richard Smith60437622017-02-09 19:17:44 +00009417 // FIXME: Perform "exact type" matching first, per CWG discussion?
9418 // Or implement this via an implied 'T(T) -> T' deduction guide?
9419
9420 // FIXME: Do we need/want a std::initializer_list<T> special case?
9421
Richard Smith32918772017-02-14 00:25:28 +00009422 // Look up deduction guides, including those synthesized from constructors.
9423 //
Richard Smith60437622017-02-09 19:17:44 +00009424 // C++1z [over.match.class.deduct]p1:
9425 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00009426 // - For each constructor of the class template designated by the
9427 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00009428 // - For each deduction-guide, a function or function template [...]
9429 DeclarationNameInfo NameInfo(
9430 Context.DeclarationNames.getCXXDeductionGuideName(Template),
9431 TSInfo->getTypeLoc().getEndLoc());
9432 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
9433 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00009434
9435 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9436 // clear on this, but they're not found by name so access does not apply.
9437 Guides.suppressDiagnostics();
9438
9439 // Figure out if this is list-initialization.
9440 InitListExpr *ListInit =
9441 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
9442 ? dyn_cast<InitListExpr>(Inits[0])
9443 : nullptr;
9444
9445 // C++1z [over.match.class.deduct]p1:
9446 // Initialization and overload resolution are performed as described in
9447 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9448 // (as appropriate for the type of initialization performed) for an object
9449 // of a hypothetical class type, where the selected functions and function
9450 // templates are considered to be the constructors of that class type
9451 //
9452 // Since we know we're initializing a class type of a type unrelated to that
9453 // of the initializer, this reduces to something fairly reasonable.
9454 OverloadCandidateSet Candidates(Kind.getLocation(),
9455 OverloadCandidateSet::CSK_Normal);
9456 OverloadCandidateSet::iterator Best;
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009457
9458 bool HasAnyDeductionGuide = false;
Richard Smith76b90272019-05-09 03:59:21 +00009459 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009460
Richard Smith60437622017-02-09 19:17:44 +00009461 auto tryToResolveOverload =
9462 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00009463 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009464 HasAnyDeductionGuide = false;
9465
Richard Smith32918772017-02-14 00:25:28 +00009466 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
9467 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00009468 if (D->isInvalidDecl())
9469 continue;
9470
Richard Smithbc491202017-02-17 20:05:37 +00009471 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
9472 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
9473 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9474 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00009475 continue;
9476
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009477 if (!GD->isImplicit())
9478 HasAnyDeductionGuide = true;
9479
Richard Smith60437622017-02-09 19:17:44 +00009480 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9481 // For copy-initialization, the candidate functions are all the
9482 // converting constructors (12.3.1) of that class.
9483 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9484 // The converting constructors of T are candidate functions.
Richard Smith76b90272019-05-09 03:59:21 +00009485 if (!AllowExplicit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00009486 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00009487 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00009488 continue;
Richard Smith60437622017-02-09 19:17:44 +00009489
9490 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00009491 // could never be called with one argument are not interesting to
9492 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00009493 if (GD->getMinRequiredArguments() > 1 ||
9494 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00009495 continue;
9496 }
9497
9498 // C++ [over.match.list]p1.1: (first phase list initialization)
9499 // Initially, the candidate functions are the initializer-list
9500 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00009501 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00009502 continue;
9503
9504 // C++ [over.match.list]p1.2: (second phase list initialization)
9505 // the candidate functions are all the constructors of the class T
9506 // C++ [over.match.ctor]p1: (all other cases)
9507 // the candidate functions are all the constructors of the class of
9508 // the object being initialized
9509
9510 // C++ [over.best.ics]p4:
9511 // When [...] the constructor [...] is a candidate by
9512 // - [over.match.copy] (in all cases)
9513 // FIXME: The "second phase of [over.match.list] case can also
9514 // theoretically happen here, but it's not clear whether we can
9515 // ever have a parameter of the right type.
9516 bool SuppressUserConversions = Kind.isCopyInit();
9517
Richard Smith60437622017-02-09 19:17:44 +00009518 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00009519 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
Richard Smith76b90272019-05-09 03:59:21 +00009520 Inits, Candidates, SuppressUserConversions,
9521 /*PartialOverloading*/ false,
9522 AllowExplicit);
Richard Smith60437622017-02-09 19:17:44 +00009523 else
Richard Smithbc491202017-02-17 20:05:37 +00009524 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith76b90272019-05-09 03:59:21 +00009525 SuppressUserConversions,
9526 /*PartialOverloading*/ false, AllowExplicit);
Richard Smith60437622017-02-09 19:17:44 +00009527 }
9528 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
9529 };
9530
9531 OverloadingResult Result = OR_No_Viable_Function;
9532
9533 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9534 // try initializer-list constructors.
9535 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00009536 bool TryListConstructors = true;
9537
9538 // Try list constructors unless the list is empty and the class has one or
9539 // more default constructors, in which case those constructors win.
9540 if (!ListInit->getNumInits()) {
9541 for (NamedDecl *D : Guides) {
9542 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9543 if (FD && FD->getMinRequiredArguments() == 0) {
9544 TryListConstructors = false;
9545 break;
9546 }
9547 }
Richard Smith1363e8f2017-09-07 07:22:36 +00009548 } else if (ListInit->getNumInits() == 1) {
9549 // C++ [over.match.class.deduct]:
9550 // As an exception, the first phase in [over.match.list] (considering
9551 // initializer-list constructors) is omitted if the initializer list
9552 // consists of a single expression of type cv U, where U is a
9553 // specialization of C or a class derived from a specialization of C.
9554 Expr *E = ListInit->getInit(0);
9555 auto *RD = E->getType()->getAsCXXRecordDecl();
9556 if (!isa<InitListExpr>(E) && RD &&
Erik Pilkingtondd0b3442018-07-26 23:40:42 +00009557 isCompleteType(Kind.getLocation(), E->getType()) &&
Richard Smith1363e8f2017-09-07 07:22:36 +00009558 isOrIsDerivedFromSpecializationOf(RD, Template))
9559 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00009560 }
9561
9562 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00009563 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
9564 // Then unwrap the initializer list and try again considering all
9565 // constructors.
9566 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
9567 }
9568
9569 // If list-initialization fails, or if we're doing any other kind of
9570 // initialization, we (eventually) consider constructors.
9571 if (Result == OR_No_Viable_Function)
9572 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
9573
9574 switch (Result) {
9575 case OR_Ambiguous:
Richard Smith60437622017-02-09 19:17:44 +00009576 // FIXME: For list-initialization candidates, it'd usually be better to
9577 // list why they were not viable when given the initializer list itself as
9578 // an argument.
David Blaikie5e328052019-05-03 00:44:50 +00009579 Candidates.NoteCandidates(
9580 PartialDiagnosticAt(
9581 Kind.getLocation(),
9582 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
9583 << TemplateName),
9584 *this, OCD_ViableCandidates, Inits);
Richard Smith60437622017-02-09 19:17:44 +00009585 return QualType();
9586
Richard Smith32918772017-02-14 00:25:28 +00009587 case OR_No_Viable_Function: {
9588 CXXRecordDecl *Primary =
9589 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
9590 bool Complete =
9591 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
David Blaikie5e328052019-05-03 00:44:50 +00009592 Candidates.NoteCandidates(
9593 PartialDiagnosticAt(
9594 Kind.getLocation(),
9595 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
9596 : diag::err_deduced_class_template_incomplete)
9597 << TemplateName << !Guides.empty()),
9598 *this, OCD_AllCandidates, Inits);
Richard Smith60437622017-02-09 19:17:44 +00009599 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00009600 }
Richard Smith60437622017-02-09 19:17:44 +00009601
9602 case OR_Deleted: {
9603 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
9604 << TemplateName;
9605 NoteDeletedFunction(Best->Function);
9606 return QualType();
9607 }
9608
9609 case OR_Success:
9610 // C++ [over.match.list]p1:
9611 // In copy-list-initialization, if an explicit constructor is chosen, the
9612 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00009613 if (Kind.isCopyInit() && ListInit &&
9614 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00009615 bool IsDeductionGuide = !Best->Function->isImplicit();
9616 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
9617 << TemplateName << IsDeductionGuide;
9618 Diag(Best->Function->getLocation(),
9619 diag::note_explicit_ctor_deduction_guide_here)
9620 << IsDeductionGuide;
9621 return QualType();
9622 }
9623
9624 // Make sure we didn't select an unusable deduction guide, and mark it
9625 // as referenced.
9626 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
9627 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
9628 break;
9629 }
9630
9631 // C++ [dcl.type.class.deduct]p1:
9632 // The placeholder is replaced by the return type of the function selected
9633 // by overload resolution for class template deduction.
Richard Smith8eeb16f2018-09-10 20:31:03 +00009634 QualType DeducedType =
9635 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
9636 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9637 diag::warn_cxx14_compat_class_template_argument_deduction)
9638 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009639
9640 // Warn if CTAD was used on a type that does not have any user-defined
9641 // deduction guides.
9642 if (!HasAnyDeductionGuide) {
9643 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9644 diag::warn_ctad_maybe_unsupported)
9645 << TemplateName;
9646 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
9647 }
9648
Richard Smith8eeb16f2018-09-10 20:31:03 +00009649 return DeducedType;
Richard Smith60437622017-02-09 19:17:44 +00009650}