blob: f94eabd67192632dad682783b217ecbde7f4fe4b [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Steve Narofff8ecff22008-05-01 22:18:59 +000014#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000016#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000017#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000018#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000019#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Designator.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000028
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
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);
Richard Smithd74b16062013-05-06 00:35:47 +0000147 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
148 break;
149 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
150 E = PE->getSubExpr();
151 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
152 E = UO->getSubExpr();
153 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
154 E = GSE->getResultExpr();
155 else
156 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000157 }
Richard Smith430c23b2013-05-05 16:40:13 +0000158}
159
John McCall5decec92011-02-21 07:57:55 +0000160static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
161 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000162 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000163 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000164 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000165 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chris Lattner0cb78032009-02-24 22:27:37 +0000167 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000168 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000169 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000170 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000171 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000172 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
173 ConstVal,
174 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000175 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000176 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000177 }
Mike Stump11289f42009-09-09 15:08:12 +0000178
Eli Friedman893abe42009-05-29 18:22:49 +0000179 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000180
Eli Friedman554eba92011-04-11 00:23:45 +0000181 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000182 // the size may be smaller or larger than the string we are initializing.
183 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000184 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000185 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000186 // For Pascal strings it's OK to strip off the terminating null character,
187 // so the example below is valid:
188 //
189 // unsigned char a[2] = "\pa";
190 if (SL->isPascal())
191 StrLength--;
192 }
193
Eli Friedman554eba92011-04-11 00:23:45 +0000194 // [dcl.init.string]p2
195 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000196 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000197 diag::err_initializer_string_for_char_array_too_long)
198 << Str->getSourceRange();
199 } else {
200 // C99 6.7.8p14.
201 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000202 S.Diag(Str->getLocStart(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000203 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000204 << Str->getSourceRange();
205 }
Mike Stump11289f42009-09-09 15:08:12 +0000206
Eli Friedman893abe42009-05-29 18:22:49 +0000207 // Set the type to the actual size that we are initializing. If we have
208 // something like:
209 // char x[1] = "foo";
210 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000211 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000212}
213
Chris Lattner0cb78032009-02-24 22:27:37 +0000214//===----------------------------------------------------------------------===//
215// Semantic checking for initializer lists.
216//===----------------------------------------------------------------------===//
217
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000218namespace {
219
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000220/// Semantic checking for initializer lists.
Douglas Gregorcde232f2009-01-29 01:05:33 +0000221///
222/// The InitListChecker class contains a set of routines that each
223/// handle the initialization of a certain kind of entity, e.g.,
224/// arrays, vectors, struct/union types, scalars, etc. The
225/// InitListChecker itself performs a recursive walk of the subobject
226/// structure of the type to be initialized, while stepping through
227/// the initializer list one element at a time. The IList and Index
228/// parameters to each of the Check* routines contain the active
229/// (syntactic) initializer list and the index into that initializer
230/// list that represents the current initializer. Each routine is
231/// responsible for moving that Index forward as it consumes elements.
232///
233/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000234/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000235/// initializer list and the index into that initializer list where we
236/// are copying initializers as we map them over to the semantic
237/// list. Once we have completed our recursive walk of the subobject
238/// structure, we will have constructed a full semantic initializer
239/// list.
240///
241/// C99 designators cause changes in the initializer list traversal,
242/// because they make the initialization "jump" into a specific
243/// subobject and then continue the initialization from that
244/// point. CheckDesignatedInitializer() recursively steps into the
245/// designated subobject and manages backing out the recursion to
246/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000247class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000248 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000249 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000250 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000251 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000252 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000254
Anders Carlsson6cabf312010-01-23 23:23:01 +0000255 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000256 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000257 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000258 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000259 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000260 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000261 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000262 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000263 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000264 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000265 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000266 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000267 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000268 unsigned &StructuredIndex,
269 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000270 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000271 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000272 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000273 InitListExpr *StructuredList,
274 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000275 void CheckComplexType(const InitializedEntity &Entity,
276 InitListExpr *IList, QualType DeclType,
277 unsigned &Index,
278 InitListExpr *StructuredList,
279 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000280 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000281 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000282 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000283 InitListExpr *StructuredList,
284 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000285 void CheckReferenceType(const InitializedEntity &Entity,
286 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000287 unsigned &Index,
288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000290 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000291 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000294 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000295 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000296 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000297 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000298 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000299 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000300 unsigned &StructuredIndex,
301 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000302 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000303 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000304 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000305 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000306 InitListExpr *StructuredList,
307 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000308 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000309 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000310 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000311 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000312 RecordDecl::field_iterator *NextField,
313 llvm::APSInt *NextElementIndex,
314 unsigned &Index,
315 InitListExpr *StructuredList,
316 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000317 bool FinishSubobjectInit,
318 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000319 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
320 QualType CurrentObjectType,
321 InitListExpr *StructuredList,
322 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000323 SourceRange InitRange,
324 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000325 void UpdateStructuredListElement(InitListExpr *StructuredList,
326 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000327 Expr *expr);
328 int numArrayElements(QualType DeclType);
329 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000330
Richard Smith454a7cd2014-06-03 08:26:00 +0000331 static ExprResult PerformEmptyInit(Sema &SemaRef,
332 SourceLocation Loc,
333 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000334 bool VerifyOnly,
335 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000336
337 // Explanation on the "FillWithNoInit" mode:
338 //
339 // Assume we have the following definitions (Case#1):
340 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
341 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
342 //
343 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
344 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
345 //
346 // But if we have (Case#2):
347 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
348 //
349 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
350 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
351 //
352 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
353 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
354 // initializers but with special "NoInitExpr" place holders, which tells the
355 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000356 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
357 const InitializedEntity &ParentEntity,
358 InitListExpr *ILE, bool &RequiresSecondPass,
359 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000360 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000361 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000362 InitListExpr *ILE, bool &RequiresSecondPass,
363 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000364 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000365 InitListExpr *ILE, bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000366 InitListExpr *OuterILE, unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000367 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000368 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
369 Expr *InitExpr, FieldDecl *Field,
370 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000371 void CheckEmptyInitializable(const InitializedEntity &Entity,
372 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000373
Douglas Gregor85df8d82009-01-29 00:45:39 +0000374public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000375 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000376 InitListExpr *IL, QualType &T, bool VerifyOnly,
377 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000378 bool HadError() { return hadError; }
379
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000380 // Retrieves the fully-structured initializer list used for
Douglas Gregor85df8d82009-01-29 00:45:39 +0000381 // semantic analysis and code generation.
382 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
383};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000384
Chris Lattner9ececce2009-02-24 22:48:58 +0000385} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000386
Richard Smith454a7cd2014-06-03 08:26:00 +0000387ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
388 SourceLocation Loc,
389 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000390 bool VerifyOnly,
391 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000392 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
393 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000394 MultiExprArg SubInit;
395 Expr *InitExpr;
396 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
397
398 // C++ [dcl.init.aggr]p7:
399 // If there are fewer initializer-clauses in the list than there are
400 // members in the aggregate, then each member not explicitly initialized
401 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000402 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
403 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
404 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000405 // C++1y / DR1070:
406 // shall be initialized [...] from an empty initializer list.
407 //
408 // We apply the resolution of this DR to C++11 but not C++98, since C++98
409 // does not have useful semantics for initialization from an init list.
410 // We treat this as copy-initialization, because aggregate initialization
411 // always performs copy-initialization on its elements.
412 //
413 // Only do this if we're initializing a class type, to avoid filling in
414 // the initializer list where possible.
415 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
416 InitListExpr(SemaRef.Context, Loc, None, Loc);
417 InitExpr->setType(SemaRef.Context.VoidTy);
418 SubInit = InitExpr;
419 Kind = InitializationKind::CreateCopy(Loc, Loc);
420 } else {
421 // C++03:
422 // shall be value-initialized.
423 }
424
425 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000426 // libstdc++4.6 marks the vector default constructor as explicit in
427 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
428 // stlport does so too. Look for std::__debug for libstdc++, and for
429 // std:: for stlport. This is effectively a compiler-side implementation of
430 // LWG2193.
431 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
432 InitializationSequence::FK_ExplicitConstructor) {
433 OverloadCandidateSet::iterator Best;
434 OverloadingResult O =
435 InitSeq.getFailedCandidateSet()
436 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
437 (void)O;
438 assert(O == OR_Success && "Inconsistent overload resolution");
439 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
440 CXXRecordDecl *R = CtorDecl->getParent();
441
442 if (CtorDecl->getMinRequiredArguments() == 0 &&
443 CtorDecl->isExplicit() && R->getDeclName() &&
444 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000445 bool IsInStd = false;
446 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000447 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000448 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
449 IsInStd = true;
450 }
451
452 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
453 .Cases("basic_string", "deque", "forward_list", true)
454 .Cases("list", "map", "multimap", "multiset", true)
455 .Cases("priority_queue", "queue", "set", "stack", true)
456 .Cases("unordered_map", "unordered_set", "vector", true)
457 .Default(false)) {
458 InitSeq.InitializeFrom(
459 SemaRef, Entity,
460 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000461 MultiExprArg(), /*TopLevelOfInitList=*/false,
462 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000463 // Emit a warning for this. System header warnings aren't shown
464 // by default, but people working on system headers should see it.
465 if (!VerifyOnly) {
466 SemaRef.Diag(CtorDecl->getLocation(),
467 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000468 if (Entity.getKind() == InitializedEntity::EK_Member)
469 SemaRef.Diag(Entity.getDecl()->getLocation(),
470 diag::note_used_in_initialization_here);
471 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
472 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000473 }
474 }
475 }
476 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000477 if (!InitSeq) {
478 if (!VerifyOnly) {
479 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
480 if (Entity.getKind() == InitializedEntity::EK_Member)
481 SemaRef.Diag(Entity.getDecl()->getLocation(),
482 diag::note_in_omitted_aggregate_initializer)
483 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000484 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
485 bool IsTrailingArrayNewMember =
486 Entity.getParent() &&
487 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000488 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000489 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
490 << Entity.getElementIndex();
491 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000492 }
493 return ExprError();
494 }
495
496 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
497 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
498}
499
500void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
501 SourceLocation Loc) {
502 assert(VerifyOnly &&
503 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000504 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
505 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000506 hadError = true;
507}
508
Richard Smith872307e2016-03-08 22:17:41 +0000509void InitListChecker::FillInEmptyInitForBase(
510 unsigned Init, const CXXBaseSpecifier &Base,
511 const InitializedEntity &ParentEntity, InitListExpr *ILE,
512 bool &RequiresSecondPass, bool FillWithNoInit) {
513 assert(Init < ILE->getNumInits() && "should have been expanded");
514
515 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
516 SemaRef.Context, &Base, false, &ParentEntity);
517
518 if (!ILE->getInit(Init)) {
519 ExprResult BaseInit =
520 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
521 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
Manman Ren073db022016-03-10 18:53:19 +0000522 /*VerifyOnly*/ false,
523 TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000524 if (BaseInit.isInvalid()) {
525 hadError = true;
526 return;
527 }
528
529 ILE->setInit(Init, BaseInit.getAs<Expr>());
530 } else if (InitListExpr *InnerILE =
531 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
Richard Smithf3b4ca82018-02-07 22:25:16 +0000532 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
533 ILE, Init, FillWithNoInit);
Richard Smith872307e2016-03-08 22:17:41 +0000534 } else if (DesignatedInitUpdateExpr *InnerDIUE =
535 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
536 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000537 RequiresSecondPass, ILE, Init,
538 /*FillWithNoInit =*/true);
Richard Smith872307e2016-03-08 22:17:41 +0000539 }
540}
541
Richard Smith454a7cd2014-06-03 08:26:00 +0000542void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000543 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000544 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000545 bool &RequiresSecondPass,
546 bool FillWithNoInit) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000547 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000548 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000549 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000550 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000551
552 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
553 if (!RType->getDecl()->isUnion())
554 assert(Init < NumInits && "This ILE should have been expanded");
555
Douglas Gregor2bb07652009-12-22 00:05:34 +0000556 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000557 if (FillWithNoInit) {
558 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
559 if (Init < NumInits)
560 ILE->setInit(Init, Filler);
561 else
562 ILE->updateInit(SemaRef.Context, Init, Filler);
563 return;
564 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000565 // C++1y [dcl.init.aggr]p7:
566 // If there are fewer initializer-clauses in the list than there are
567 // members in the aggregate, then each member not explicitly initialized
568 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000569 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000570 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
571 if (DIE.isInvalid()) {
572 hadError = true;
573 return;
574 }
Richard Smith0a9969b2018-07-17 00:11:41 +0000575 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000576 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000577 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000578 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000579 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000580 RequiresSecondPass = true;
581 }
582 return;
583 }
584
Douglas Gregor2bb07652009-12-22 00:05:34 +0000585 if (Field->getType()->isReferenceType()) {
586 // C++ [dcl.init.aggr]p9:
587 // If an incomplete or empty initializer-list leaves a
588 // member of reference type uninitialized, the program is
589 // ill-formed.
590 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
591 << Field->getType()
592 << ILE->getSyntacticForm()->getSourceRange();
593 SemaRef.Diag(Field->getLocation(),
594 diag::note_uninit_reference_member);
595 hadError = true;
596 return;
597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Richard Smith454a7cd2014-06-03 08:26:00 +0000599 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000600 /*VerifyOnly*/false,
601 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000602 if (MemberInit.isInvalid()) {
603 hadError = true;
604 return;
605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Douglas Gregor2bb07652009-12-22 00:05:34 +0000607 if (hadError) {
608 // Do nothing
609 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000610 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000611 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
612 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000613 // extend the initializer list to include the constructor
614 // call and make a note that we'll need to take another pass
615 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000616 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000617 RequiresSecondPass = true;
618 }
619 } else if (InitListExpr *InnerILE
620 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000621 FillInEmptyInitializations(MemberEntity, InnerILE,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000622 RequiresSecondPass, ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000623 else if (DesignatedInitUpdateExpr *InnerDIUE
624 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
625 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000626 RequiresSecondPass, ILE, Init,
627 /*FillWithNoInit =*/true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000628}
629
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000630/// Recursively replaces NULL values within the given initializer list
631/// with expressions that perform value-initialization of the
Richard Smithf3b4ca82018-02-07 22:25:16 +0000632/// appropriate type, and finish off the InitListExpr formation.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633void
Richard Smith454a7cd2014-06-03 08:26:00 +0000634InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000635 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000636 bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000637 InitListExpr *OuterILE,
638 unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000639 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000640 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000641 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000642
Richard Smithf3b4ca82018-02-07 22:25:16 +0000643 // If this is a nested initializer list, we might have changed its contents
644 // (and therefore some of its properties, such as instantiation-dependence)
645 // while filling it in. Inform the outer initializer list so that its state
646 // can be updated to match.
647 // FIXME: We should fully build the inner initializers before constructing
648 // the outer InitListExpr instead of mutating AST nodes after they have
649 // been used as subexpressions of other nodes.
650 struct UpdateOuterILEWithUpdatedInit {
651 InitListExpr *Outer;
652 unsigned OuterIndex;
653 ~UpdateOuterILEWithUpdatedInit() {
654 if (Outer)
655 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
656 }
657 } UpdateOuterRAII = {OuterILE, OuterIndex};
658
Richard Smith382bc512017-02-23 22:41:47 +0000659 // A transparent ILE is not performing aggregate initialization and should
660 // not be filled in.
661 if (ILE->isTransparent())
662 return;
663
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000664 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000665 const RecordDecl *RDecl = RType->getDecl();
666 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000667 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000668 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000669 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
670 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000671 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000672 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000673 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
674 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000675 break;
676 }
677 }
678 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000679 // The fields beyond ILE->getNumInits() are default initialized, so in
680 // order to leave them uninitialized, the ILE is expanded and the extra
681 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000682 unsigned NumElems = numStructUnionElements(ILE->getType());
683 if (RDecl->hasFlexibleArrayMember())
684 ++NumElems;
685 if (ILE->getNumInits() < NumElems)
686 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000687
Douglas Gregor2bb07652009-12-22 00:05:34 +0000688 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000689
690 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
691 for (auto &Base : CXXRD->bases()) {
692 if (hadError)
693 return;
694
695 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
696 FillWithNoInit);
697 ++Init;
698 }
699 }
700
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000701 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000702 if (Field->isUnnamedBitfield())
703 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000704
Douglas Gregor2bb07652009-12-22 00:05:34 +0000705 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000706 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000707
Yunzhong Gaocb779302015-06-10 00:27:52 +0000708 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
709 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000710 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000711 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000712
Douglas Gregor2bb07652009-12-22 00:05:34 +0000713 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000714
Douglas Gregor2bb07652009-12-22 00:05:34 +0000715 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000716 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000717 break;
718 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000719 }
720
721 return;
Mike Stump11289f42009-09-09 15:08:12 +0000722 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000723
724 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000725
Douglas Gregor723796a2009-12-16 06:35:08 +0000726 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000727 unsigned NumInits = ILE->getNumInits();
728 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000729 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000730 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000731 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000732 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000733 // For an array new with an unknown bound, ask for one additional element
734 // in order to populate the array filler.
735 if (Entity.isVariableLengthArrayNew())
736 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000738 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000739 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000740 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000741 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000743 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000744 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000745 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000746
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000747 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000748 if (hadError)
749 return;
750
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000751 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
752 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000753 ElementEntity.setElementIndex(Init);
754
Richard Smith3e268632018-05-23 23:41:38 +0000755 if (Init >= NumInits && ILE->hasArrayFiller())
756 return;
757
Craig Topperc3ec1492014-05-26 06:22:03 +0000758 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000759 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
760 ILE->setInit(Init, ILE->getArrayFiller());
761 else if (!InitExpr && !ILE->hasArrayFiller()) {
762 Expr *Filler = nullptr;
763
764 if (FillWithNoInit)
765 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
766 else {
767 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
768 ElementEntity,
Manman Ren073db022016-03-10 18:53:19 +0000769 /*VerifyOnly*/false,
770 TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000771 if (ElementInit.isInvalid()) {
772 hadError = true;
773 return;
774 }
775
776 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000777 }
778
779 if (hadError) {
780 // Do nothing
781 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000782 // For arrays, just set the expression used for value-initialization
783 // of the "holes" in the array.
784 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000785 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000786 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000787 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000788 } else {
789 // For arrays, just set the expression used for value-initialization
790 // of the rest of elements and exit.
791 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000792 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000793 return;
794 }
795
Yunzhong Gaocb779302015-06-10 00:27:52 +0000796 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000797 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000798 // extend the initializer list to include the constructor
799 // call and make a note that we'll need to take another pass
800 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000801 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000802 RequiresSecondPass = true;
803 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000804 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000805 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000806 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000807 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000808 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000809 else if (DesignatedInitUpdateExpr *InnerDIUE
810 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
811 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000812 RequiresSecondPass, ILE, Init,
813 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000814 }
815}
816
Douglas Gregor723796a2009-12-16 06:35:08 +0000817InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000818 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000819 bool VerifyOnly,
820 bool TreatUnavailableAsInvalid)
821 : SemaRef(S), VerifyOnly(VerifyOnly),
822 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000823 // FIXME: Check that IL isn't already the semantic form of some other
824 // InitListExpr. If it is, we'd create a broken AST.
825
Steve Narofff8ecff22008-05-01 22:18:59 +0000826 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000827
Richard Smith4e0d2e42013-09-20 20:10:22 +0000828 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000829 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000830 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000831 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000832
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000833 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000834 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000835 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
836 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000837 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000838 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000839 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000840 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000841}
842
843int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000844 // FIXME: use a proper constant
845 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000846 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000847 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000848 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
849 }
850 return maxElements;
851}
852
853int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000854 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000855 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000856 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
857 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000858 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000859 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000860 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000861
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000862 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000863 return std::min(InitializableMembers, 1);
864 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000865}
866
Richard Smith283e2072017-10-03 20:36:00 +0000867/// Determine whether Entity is an entity for which it is idiomatic to elide
868/// the braces in aggregate initialization.
869static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
870 // Recursive initialization of the one and only field within an aggregate
871 // class is considered idiomatic. This case arises in particular for
872 // initialization of std::array, where the C++ standard suggests the idiom of
873 //
874 // std::array<T, N> arr = {1, 2, 3};
875 //
876 // (where std::array is an aggregate struct containing a single array field.
877
878 // FIXME: Should aggregate initialization of a struct with a single
879 // base class and no members also suppress the warning?
880 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
881 return false;
882
883 auto *ParentRD =
884 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
885 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
886 if (CXXRD->getNumBases())
887 return false;
888
889 auto FieldIt = ParentRD->field_begin();
890 assert(FieldIt != ParentRD->field_end() &&
891 "no fields but have initializer for member?");
892 return ++FieldIt == ParentRD->field_end();
893}
894
Richard Smith4e0d2e42013-09-20 20:10:22 +0000895/// Check whether the range of the initializer \p ParentIList from element
896/// \p Index onwards can be used to initialize an object of type \p T. Update
897/// \p Index to indicate how many elements of the list were consumed.
898///
899/// This also fills in \p StructuredList, from element \p StructuredIndex
900/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000901void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000902 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 QualType T, unsigned &Index,
904 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000905 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000906 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Steve Narofff8ecff22008-05-01 22:18:59 +0000908 if (T->isArrayType())
909 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000910 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000911 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000912 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000913 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000914 else
David Blaikie83d382b2011-09-23 05:06:16 +0000915 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000916
Eli Friedmane0f832b2008-05-25 13:49:22 +0000917 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000918 if (!VerifyOnly)
919 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
920 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000921 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000922 hadError = true;
923 return;
924 }
925
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000926 // Build a structured initializer list corresponding to this subobject.
927 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000928 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
929 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000930 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000931 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000932 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000933
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000934 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000935 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000937 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000938 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000939 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000940
Richard Smithde229232013-06-06 11:41:05 +0000941 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000942 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000943
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000944 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000945 // Update the structured sub-object initializer so that it's ending
946 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000947 if (EndIndex < ParentIList->getNumInits() &&
948 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000949 SourceLocation EndLoc
950 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
951 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000953
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000954 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000955 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000956 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
957 !isIdiomaticBraceElisionEntity(Entity)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000958 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000959 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000960 << StructuredSubobjectInitList->getSourceRange()
961 << FixItHint::CreateInsertion(
962 StructuredSubobjectInitList->getLocStart(), "{")
963 << FixItHint::CreateInsertion(
964 SemaRef.getLocForEndOfToken(
965 StructuredSubobjectInitList->getLocEnd()),
966 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000967 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000968 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000969}
970
Richard Smith420fa122015-02-12 01:50:05 +0000971/// Warn that \p Entity was of scalar type and was initialized by a
972/// single-element braced initializer list.
973static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
974 SourceRange Braces) {
975 // Don't warn during template instantiation. If the initialization was
976 // non-dependent, we warned during the initial parse; otherwise, the
977 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000978 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000979 return;
980
981 unsigned DiagID = 0;
982
983 switch (Entity.getKind()) {
984 case InitializedEntity::EK_VectorElement:
985 case InitializedEntity::EK_ComplexElement:
986 case InitializedEntity::EK_ArrayElement:
987 case InitializedEntity::EK_Parameter:
988 case InitializedEntity::EK_Parameter_CF_Audited:
989 case InitializedEntity::EK_Result:
990 // Extra braces here are suspicious.
991 DiagID = diag::warn_braces_around_scalar_init;
992 break;
993
994 case InitializedEntity::EK_Member:
995 // Warn on aggregate initialization but not on ctor init list or
996 // default member initializer.
997 if (Entity.getParent())
998 DiagID = diag::warn_braces_around_scalar_init;
999 break;
1000
1001 case InitializedEntity::EK_Variable:
1002 case InitializedEntity::EK_LambdaCapture:
1003 // No warning, might be direct-list-initialization.
1004 // FIXME: Should we warn for copy-list-initialization in these cases?
1005 break;
1006
1007 case InitializedEntity::EK_New:
1008 case InitializedEntity::EK_Temporary:
1009 case InitializedEntity::EK_CompoundLiteralInit:
1010 // No warning, braces are part of the syntax of the underlying construct.
1011 break;
1012
1013 case InitializedEntity::EK_RelatedResult:
1014 // No warning, we already warned when initializing the result.
1015 break;
1016
1017 case InitializedEntity::EK_Exception:
1018 case InitializedEntity::EK_Base:
1019 case InitializedEntity::EK_Delegating:
1020 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001021 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001022 case InitializedEntity::EK_Binding:
Richard Smith420fa122015-02-12 01:50:05 +00001023 llvm_unreachable("unexpected braced scalar init");
1024 }
1025
1026 if (DiagID) {
1027 S.Diag(Braces.getBegin(), DiagID)
1028 << Braces
1029 << FixItHint::CreateRemoval(Braces.getBegin())
1030 << FixItHint::CreateRemoval(Braces.getEnd());
1031 }
1032}
1033
Richard Smith4e0d2e42013-09-20 20:10:22 +00001034/// Check whether the initializer \p IList (that was written with explicit
1035/// braces) can be used to initialize an object of type \p T.
1036///
1037/// This also fills in \p StructuredList with the fully-braced, desugared
1038/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001039void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001040 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001041 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001042 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001043 if (!VerifyOnly) {
1044 SyntacticToSemantic[IList] = StructuredList;
1045 StructuredList->setSyntacticForm(IList);
1046 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001047
1048 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001049 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001050 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001051 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001052 QualType ExprTy = T;
1053 if (!ExprTy->isArrayType())
1054 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001055 IList->setType(ExprTy);
1056 StructuredList->setType(ExprTy);
1057 }
Eli Friedman85f54972008-05-25 13:22:35 +00001058 if (hadError)
1059 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001060
Eli Friedman85f54972008-05-25 13:22:35 +00001061 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001062 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001063 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001064 if (SemaRef.getLangOpts().CPlusPlus ||
1065 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001066 IList->getType()->isVectorType())) {
1067 hadError = true;
1068 }
1069 return;
1070 }
1071
Eli Friedmanbd327452009-05-29 20:20:05 +00001072 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001073 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1074 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001075 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001076 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001077 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001078 hadError = true;
1079 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001080 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +00001081 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +00001082 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001083 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001084 // Don't complain for incomplete types, since we'll get an error
1085 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001086 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001087 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001088 CurrentObjectType->isArrayType()? 0 :
1089 CurrentObjectType->isVectorType()? 1 :
1090 CurrentObjectType->isScalarType()? 2 :
1091 CurrentObjectType->isUnionType()? 3 :
1092 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001093
Richard Smith1b98ccc2014-07-19 01:39:17 +00001094 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001095 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001096 DK = diag::err_excess_initializers;
1097 hadError = true;
1098 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001099 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001100 DK = diag::err_excess_initializers;
1101 hadError = true;
1102 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001103
Chris Lattnerb0912a52009-02-24 22:50:46 +00001104 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001105 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001106 }
1107 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001108
Richard Smith420fa122015-02-12 01:50:05 +00001109 if (!VerifyOnly && T->isScalarType() &&
1110 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1111 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +00001112}
1113
Anders Carlsson6cabf312010-01-23 23:23:01 +00001114void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001115 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001116 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001117 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001118 unsigned &Index,
1119 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001120 unsigned &StructuredIndex,
1121 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001122 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1123 // Explicitly braced initializer for complex type can be real+imaginary
1124 // parts.
1125 CheckComplexType(Entity, IList, DeclType, Index,
1126 StructuredList, StructuredIndex);
1127 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001128 CheckScalarType(Entity, IList, DeclType, Index,
1129 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001130 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001131 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001132 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001133 } else if (DeclType->isRecordType()) {
1134 assert(DeclType->isAggregateType() &&
1135 "non-aggregate records should be handed in CheckSubElementType");
1136 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001137 auto Bases =
1138 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1139 CXXRecordDecl::base_class_iterator());
1140 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1141 Bases = CXXRD->bases();
1142 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1143 SubobjectIsDesignatorContext, Index, StructuredList,
1144 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001145 } else if (DeclType->isArrayType()) {
1146 llvm::APSInt Zero(
1147 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1148 false);
1149 CheckArrayType(Entity, IList, DeclType, Zero,
1150 SubobjectIsDesignatorContext, Index,
1151 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001152 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1153 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001154 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001155 if (!VerifyOnly)
1156 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1157 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001158 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001159 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001160 CheckReferenceType(Entity, IList, DeclType, Index,
1161 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001162 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001163 if (!VerifyOnly)
1164 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1165 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001166 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001167 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001168 if (!VerifyOnly)
1169 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1170 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001171 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001172 }
1173}
1174
Anders Carlsson6cabf312010-01-23 23:23:01 +00001175void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001176 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001177 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001178 unsigned &Index,
1179 InitListExpr *StructuredList,
1180 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001181 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001182
1183 if (ElemType->isReferenceType())
1184 return CheckReferenceType(Entity, IList, ElemType, Index,
1185 StructuredList, StructuredIndex);
1186
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001187 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001188 if (SubInitList->getNumInits() == 1 &&
1189 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1190 SIF_None) {
1191 expr = SubInitList->getInit(0);
1192 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001193 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001194 = getStructuredSubobjectInit(IList, Index, ElemType,
1195 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001196 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001197 CheckExplicitInitList(Entity, SubInitList, ElemType,
1198 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001199
1200 if (!hadError && !VerifyOnly) {
1201 bool RequiresSecondPass = false;
1202 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001203 RequiresSecondPass, StructuredList,
1204 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001205 if (RequiresSecondPass && !hadError)
1206 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001207 RequiresSecondPass, StructuredList,
1208 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001209 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001210 ++StructuredIndex;
1211 ++Index;
1212 return;
1213 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001214 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001215 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001216 // This happens during template instantiation when we see an InitListExpr
1217 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001218 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001219 "found implicit initialization for the wrong type");
1220 if (!VerifyOnly)
1221 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1222 ++Index;
1223 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001224 }
1225
Richard Smith3c567fc2015-02-12 01:55:09 +00001226 if (SemaRef.getLangOpts().CPlusPlus) {
1227 // C++ [dcl.init.aggr]p2:
1228 // Each member is copy-initialized from the corresponding
1229 // initializer-clause.
1230
1231 // FIXME: Better EqualLoc?
1232 InitializationKind Kind =
1233 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1234 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1235 /*TopLevelOfInitList*/ true);
1236
1237 // C++14 [dcl.init.aggr]p13:
1238 // If the assignment-expression can initialize a member, the member is
1239 // initialized. Otherwise [...] brace elision is assumed
1240 //
1241 // Brace elision is never performed if the element is not an
1242 // assignment-expression.
1243 if (Seq || isa<InitListExpr>(expr)) {
1244 if (!VerifyOnly) {
1245 ExprResult Result =
1246 Seq.Perform(SemaRef, Entity, Kind, expr);
1247 if (Result.isInvalid())
1248 hadError = true;
1249
1250 UpdateStructuredListElement(StructuredList, StructuredIndex,
1251 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001252 } else if (!Seq)
1253 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001254 ++Index;
1255 return;
1256 }
1257
1258 // Fall through for subaggregate initialization
1259 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1260 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001261 return CheckScalarType(Entity, IList, ElemType, Index,
1262 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001263 } else if (const ArrayType *arrayType =
1264 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001265 // arrayType can be incomplete if we're initializing a flexible
1266 // array member. There's nothing we can do with the completed
1267 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001269 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001270 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001271 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1272 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001273 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001274 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001275 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001276 }
John McCall5decec92011-02-21 07:57:55 +00001277
1278 // Fall through for subaggregate initialization.
1279
John McCall5decec92011-02-21 07:57:55 +00001280 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001281 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001282 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001283
John McCall5decec92011-02-21 07:57:55 +00001284 // C99 6.7.8p13:
1285 //
1286 // The initializer for a structure or union object that has
1287 // automatic storage duration shall be either an initializer
1288 // list as described below, or a single expression that has
1289 // compatible structure or union type. In the latter case, the
1290 // initial value of the object, including unnamed members, is
1291 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001292 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001293 if (SemaRef.CheckSingleAssignmentConstraints(
1294 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001295 if (ExprRes.isInvalid())
1296 hadError = true;
1297 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001298 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001299 if (ExprRes.isInvalid())
1300 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001301 }
1302 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001303 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001304 ++Index;
1305 return;
1306 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001307 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001308 // Fall through for subaggregate initialization
1309 }
1310
1311 // C++ [dcl.init.aggr]p12:
1312 //
1313 // [...] Otherwise, if the member is itself a non-empty
1314 // subaggregate, brace elision is assumed and the initializer is
1315 // considered for the initialization of the first member of
1316 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001317 // OpenCL vector initializer is handled elsewhere.
1318 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1319 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001320 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1321 StructuredIndex);
1322 ++StructuredIndex;
1323 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001324 if (!VerifyOnly) {
1325 // We cannot initialize this element, so let
1326 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001327 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001328 /*TopLevelOfInitList=*/true);
1329 }
John McCall5decec92011-02-21 07:57:55 +00001330 hadError = true;
1331 ++Index;
1332 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001333 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001334}
1335
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001336void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1337 InitListExpr *IList, QualType DeclType,
1338 unsigned &Index,
1339 InitListExpr *StructuredList,
1340 unsigned &StructuredIndex) {
1341 assert(Index == 0 && "Index in explicit init list must be zero");
1342
1343 // As an extension, clang supports complex initializers, which initialize
1344 // a complex number component-wise. When an explicit initializer list for
1345 // a complex number contains two two initializers, this extension kicks in:
1346 // it exepcts the initializer list to contain two elements convertible to
1347 // the element type of the complex type. The first element initializes
1348 // the real part, and the second element intitializes the imaginary part.
1349
1350 if (IList->getNumInits() != 2)
1351 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1352 StructuredIndex);
1353
1354 // This is an extension in C. (The builtin _Complex type does not exist
1355 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001356 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001357 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1358 << IList->getSourceRange();
1359
1360 // Initialize the complex number.
1361 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1362 InitializedEntity ElementEntity =
1363 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1364
1365 for (unsigned i = 0; i < 2; ++i) {
1366 ElementEntity.setElementIndex(Index);
1367 CheckSubElementType(ElementEntity, IList, elementType, Index,
1368 StructuredList, StructuredIndex);
1369 }
1370}
1371
Anders Carlsson6cabf312010-01-23 23:23:01 +00001372void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001373 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001374 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001375 InitListExpr *StructuredList,
1376 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001377 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001378 if (!VerifyOnly)
1379 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001380 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001381 diag::warn_cxx98_compat_empty_scalar_initializer :
1382 diag::err_empty_scalar_initializer)
1383 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001384 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001385 ++Index;
1386 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001387 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001388 }
John McCall643169b2010-11-11 00:46:36 +00001389
1390 Expr *expr = IList->getInit(Index);
1391 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001392 // FIXME: This is invalid, and accepting it causes overload resolution
1393 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001394 if (!VerifyOnly)
1395 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001396 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001397 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001398
1399 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1400 StructuredIndex);
1401 return;
1402 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001403 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001404 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001405 diag::err_designator_for_scalar_init)
1406 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001407 hadError = true;
1408 ++Index;
1409 ++StructuredIndex;
1410 return;
1411 }
1412
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001413 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001414 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001415 hadError = true;
1416 ++Index;
1417 return;
1418 }
1419
John McCall643169b2010-11-11 00:46:36 +00001420 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001421 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001422 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001423
Craig Topperc3ec1492014-05-26 06:22:03 +00001424 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001425
1426 if (Result.isInvalid())
1427 hadError = true; // types weren't compatible.
1428 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001429 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430
John McCall643169b2010-11-11 00:46:36 +00001431 if (ResultExpr != expr) {
1432 // The type was promoted, update initializer list.
1433 IList->setInit(Index, ResultExpr);
1434 }
1435 }
1436 if (hadError)
1437 ++StructuredIndex;
1438 else
1439 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1440 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001441}
1442
Anders Carlsson6cabf312010-01-23 23:23:01 +00001443void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1444 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001445 unsigned &Index,
1446 InitListExpr *StructuredList,
1447 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001448 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001449 // FIXME: It would be wonderful if we could point at the actual member. In
1450 // general, it would be useful to pass location information down the stack,
1451 // so that we know the location (or decl) of the "current object" being
1452 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001453 if (!VerifyOnly)
1454 SemaRef.Diag(IList->getLocStart(),
1455 diag::err_init_reference_member_uninitialized)
1456 << DeclType
1457 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001458 hadError = true;
1459 ++Index;
1460 ++StructuredIndex;
1461 return;
1462 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001463
1464 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001465 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001466 if (!VerifyOnly)
1467 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1468 << DeclType << IList->getSourceRange();
1469 hadError = true;
1470 ++Index;
1471 ++StructuredIndex;
1472 return;
1473 }
1474
1475 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001476 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001477 hadError = true;
1478 ++Index;
1479 return;
1480 }
1481
1482 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001483 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1484 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001485
1486 if (Result.isInvalid())
1487 hadError = true;
1488
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001489 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001490 IList->setInit(Index, expr);
1491
1492 if (hadError)
1493 ++StructuredIndex;
1494 else
1495 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1496 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001497}
1498
Anders Carlsson6cabf312010-01-23 23:23:01 +00001499void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001500 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001501 unsigned &Index,
1502 InitListExpr *StructuredList,
1503 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001504 const VectorType *VT = DeclType->getAs<VectorType>();
1505 unsigned maxElements = VT->getNumElements();
1506 unsigned numEltsInit = 0;
1507 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001508
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001509 if (Index >= IList->getNumInits()) {
1510 // Make sure the element type can be value-initialized.
1511 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001512 CheckEmptyInitializable(
1513 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1514 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001515 return;
1516 }
1517
David Blaikiebbafb8a2012-03-11 07:00:24 +00001518 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001519 // If the initializing element is a vector, try to copy-initialize
1520 // instead of breaking it apart (which is doomed to failure anyway).
1521 Expr *Init = IList->getInit(Index);
1522 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001523 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001524 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001525 hadError = true;
1526 ++Index;
1527 return;
1528 }
1529
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001530 ExprResult Result =
1531 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1532 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001533
Craig Topperc3ec1492014-05-26 06:22:03 +00001534 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001535 if (Result.isInvalid())
1536 hadError = true; // types weren't compatible.
1537 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001538 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001539
John McCall6a16b2f2010-10-30 00:11:39 +00001540 if (ResultExpr != Init) {
1541 // The type was promoted, update initializer list.
1542 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001543 }
1544 }
John McCall6a16b2f2010-10-30 00:11:39 +00001545 if (hadError)
1546 ++StructuredIndex;
1547 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001548 UpdateStructuredListElement(StructuredList, StructuredIndex,
1549 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001550 ++Index;
1551 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553
John McCall6a16b2f2010-10-30 00:11:39 +00001554 InitializedEntity ElementEntity =
1555 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556
John McCall6a16b2f2010-10-30 00:11:39 +00001557 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1558 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001559 if (Index >= IList->getNumInits()) {
1560 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001561 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001562 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
John McCall6a16b2f2010-10-30 00:11:39 +00001565 ElementEntity.setElementIndex(Index);
1566 CheckSubElementType(ElementEntity, IList, elementType, Index,
1567 StructuredList, StructuredIndex);
1568 }
James Molloy9eef2652014-06-20 14:35:13 +00001569
1570 if (VerifyOnly)
1571 return;
1572
1573 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1574 const VectorType *T = Entity.getType()->getAs<VectorType>();
1575 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1576 T->getVectorKind() == VectorType::NeonPolyVector)) {
1577 // The ability to use vector initializer lists is a GNU vector extension
1578 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1579 // endian machines it works fine, however on big endian machines it
1580 // exhibits surprising behaviour:
1581 //
1582 // uint32x2_t x = {42, 64};
1583 // return vget_lane_u32(x, 0); // Will return 64.
1584 //
1585 // Because of this, explicitly call out that it is non-portable.
1586 //
1587 SemaRef.Diag(IList->getLocStart(),
1588 diag::warn_neon_vector_initializer_non_portable);
1589
1590 const char *typeCode;
1591 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1592
1593 if (elementType->isFloatingType())
1594 typeCode = "f";
1595 else if (elementType->isSignedIntegerType())
1596 typeCode = "s";
1597 else if (elementType->isUnsignedIntegerType())
1598 typeCode = "u";
1599 else
1600 llvm_unreachable("Invalid element type!");
1601
1602 SemaRef.Diag(IList->getLocStart(),
1603 SemaRef.Context.getTypeSize(VT) > 64 ?
1604 diag::note_neon_vector_initializer_non_portable_q :
1605 diag::note_neon_vector_initializer_non_portable)
1606 << typeCode << typeSize;
1607 }
1608
John McCall6a16b2f2010-10-30 00:11:39 +00001609 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001610 }
John McCall6a16b2f2010-10-30 00:11:39 +00001611
1612 InitializedEntity ElementEntity =
1613 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001614
John McCall6a16b2f2010-10-30 00:11:39 +00001615 // OpenCL initializers allows vectors to be constructed from vectors.
1616 for (unsigned i = 0; i < maxElements; ++i) {
1617 // Don't attempt to go past the end of the init list
1618 if (Index >= IList->getNumInits())
1619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001620
John McCall6a16b2f2010-10-30 00:11:39 +00001621 ElementEntity.setElementIndex(Index);
1622
1623 QualType IType = IList->getInit(Index)->getType();
1624 if (!IType->isVectorType()) {
1625 CheckSubElementType(ElementEntity, IList, elementType, Index,
1626 StructuredList, StructuredIndex);
1627 ++numEltsInit;
1628 } else {
1629 QualType VecType;
1630 const VectorType *IVT = IType->getAs<VectorType>();
1631 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001632
John McCall6a16b2f2010-10-30 00:11:39 +00001633 if (IType->isExtVectorType())
1634 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1635 else
1636 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001637 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001638 CheckSubElementType(ElementEntity, IList, VecType, Index,
1639 StructuredList, StructuredIndex);
1640 numEltsInit += numIElts;
1641 }
1642 }
1643
1644 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001645 if (numEltsInit != maxElements) {
1646 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001647 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001648 diag::err_vector_incorrect_num_initializers)
1649 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1650 hadError = true;
1651 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001652}
1653
Anders Carlsson6cabf312010-01-23 23:23:01 +00001654void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001655 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001656 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001657 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001658 unsigned &Index,
1659 InitListExpr *StructuredList,
1660 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001661 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1662
Steve Narofff8ecff22008-05-01 22:18:59 +00001663 // Check for the special-case of initializing an array with a string.
1664 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001665 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1666 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001667 // We place the string literal directly into the resulting
1668 // initializer list. This is the only place where the structure
1669 // of the structured initializer list doesn't match exactly,
1670 // because doing so would involve allocating one character
1671 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001672 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001673 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1674 UpdateStructuredListElement(StructuredList, StructuredIndex,
1675 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001676 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1677 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001678 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001679 return;
1680 }
1681 }
John McCall66884dd2011-02-21 07:22:22 +00001682 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001683 // Check for VLAs; in standard C it would be possible to check this
1684 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1685 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001686 if (!VerifyOnly)
1687 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1688 diag::err_variable_object_no_init)
1689 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001690 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 ++Index;
1692 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001693 return;
1694 }
1695
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001696 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001697 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1698 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001699 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001700 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001701 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001702 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001703 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001704 maxElementsKnown = true;
1705 }
1706
John McCall66884dd2011-02-21 07:22:22 +00001707 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001708 while (Index < IList->getNumInits()) {
1709 Expr *Init = IList->getInit(Index);
1710 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001711 // If we're not the subobject that matches up with the '{' for
1712 // the designator, we shouldn't be handling the
1713 // designator. Return immediately.
1714 if (!SubobjectIsDesignatorContext)
1715 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001716
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001717 // Handle this designated initializer. elementIndex will be
1718 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001719 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001720 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001721 StructuredList, StructuredIndex, true,
1722 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001723 hadError = true;
1724 continue;
1725 }
1726
Douglas Gregor033d1252009-01-23 16:54:12 +00001727 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001728 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001729 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001730 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001731 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001732
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001733 // If the array is of incomplete type, keep track of the number of
1734 // elements in the initializer.
1735 if (!maxElementsKnown && elementIndex > maxElements)
1736 maxElements = elementIndex;
1737
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001738 continue;
1739 }
1740
1741 // If we know the maximum number of elements, and we've already
1742 // hit it, stop consuming elements in the initializer list.
1743 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001744 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001745
Anders Carlsson6cabf312010-01-23 23:23:01 +00001746 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001747 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001748 Entity);
1749 // Check this element.
1750 CheckSubElementType(ElementEntity, IList, elementType, Index,
1751 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001752 ++elementIndex;
1753
1754 // If the array is of incomplete type, keep track of the number of
1755 // elements in the initializer.
1756 if (!maxElementsKnown && elementIndex > maxElements)
1757 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001758 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001759 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001760 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001761 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001762 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001763 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001764 // Sizing an array implicitly to zero is not allowed by ISO C,
1765 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001766 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001767 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001768 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001769
Mike Stump11289f42009-09-09 15:08:12 +00001770 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001771 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001772 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001773 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001774 // If there are any members of the array that get value-initialized, check
1775 // that is possible. That happens if we know the bound and don't have
1776 // enough elements, or if we're performing an array new with an unknown
1777 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001778 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001779 if ((maxElementsKnown && elementIndex < maxElements) ||
1780 Entity.isVariableLengthArrayNew())
Richard Smith454a7cd2014-06-03 08:26:00 +00001781 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1782 SemaRef.Context, 0, Entity),
1783 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001784 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001785}
1786
Eli Friedman3fa64df2011-08-23 22:24:57 +00001787bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1788 Expr *InitExpr,
1789 FieldDecl *Field,
1790 bool TopLevelObject) {
1791 // Handle GNU flexible array initializers.
1792 unsigned FlexArrayDiag;
1793 if (isa<InitListExpr>(InitExpr) &&
1794 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1795 // Empty flexible array init always allowed as an extension
1796 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001797 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001798 // Disallow flexible array init in C++; it is not required for gcc
1799 // compatibility, and it needs work to IRGen correctly in general.
1800 FlexArrayDiag = diag::err_flexible_array_init;
1801 } else if (!TopLevelObject) {
1802 // Disallow flexible array init on non-top-level object
1803 FlexArrayDiag = diag::err_flexible_array_init;
1804 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1805 // Disallow flexible array init on anything which is not a variable.
1806 FlexArrayDiag = diag::err_flexible_array_init;
1807 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1808 // Disallow flexible array init on local variables.
1809 FlexArrayDiag = diag::err_flexible_array_init;
1810 } else {
1811 // Allow other cases.
1812 FlexArrayDiag = diag::ext_flexible_array_init;
1813 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001814
1815 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001816 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001817 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001818 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001819 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1820 << Field;
1821 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001822
1823 return FlexArrayDiag != diag::ext_flexible_array_init;
1824}
1825
Richard Smith872307e2016-03-08 22:17:41 +00001826void InitListChecker::CheckStructUnionTypes(
1827 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1828 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1829 bool SubobjectIsDesignatorContext, unsigned &Index,
1830 InitListExpr *StructuredList, unsigned &StructuredIndex,
1831 bool TopLevelObject) {
1832 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001833
Eli Friedman23a9e312008-05-19 19:16:24 +00001834 // If the record is invalid, some of it's members are invalid. To avoid
1835 // confusion, we forgo checking the intializer for the entire record.
1836 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001837 // Assume it was supposed to consume a single initializer.
1838 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001839 hadError = true;
1840 return;
Mike Stump11289f42009-09-09 15:08:12 +00001841 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001842
1843 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001844 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001845
1846 // If there's a default initializer, use it.
1847 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1848 if (VerifyOnly)
1849 return;
1850 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1851 Field != FieldEnd; ++Field) {
1852 if (Field->hasInClassInitializer()) {
1853 StructuredList->setInitializedFieldInUnion(*Field);
1854 // FIXME: Actually build a CXXDefaultInitExpr?
1855 return;
1856 }
1857 }
1858 }
1859
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001860 // Value-initialize the first member of the union that isn't an unnamed
1861 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001862 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1863 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001864 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001865 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001866 CheckEmptyInitializable(
1867 InitializedEntity::InitializeMember(*Field, &Entity),
1868 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001869 else
David Blaikie40ed2972012-06-06 20:45:41 +00001870 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001871 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001872 }
1873 }
1874 return;
1875 }
1876
Richard Smith872307e2016-03-08 22:17:41 +00001877 bool InitializedSomething = false;
1878
1879 // If we have any base classes, they are initialized prior to the fields.
1880 for (auto &Base : Bases) {
1881 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1882 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1883
1884 // Designated inits always initialize fields, so if we see one, all
1885 // remaining base classes have no explicit initializer.
1886 if (Init && isa<DesignatedInitExpr>(Init))
1887 Init = nullptr;
1888
1889 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1890 SemaRef.Context, &Base, false, &Entity);
1891 if (Init) {
1892 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1893 StructuredList, StructuredIndex);
1894 InitializedSomething = true;
1895 } else if (VerifyOnly) {
1896 CheckEmptyInitializable(BaseEntity, InitLoc);
1897 }
1898 }
1899
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001900 // If structDecl is a forward declaration, this loop won't do
1901 // anything except look at designated initializers; That's okay,
1902 // because an error should get printed out elsewhere. It might be
1903 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001904 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001905 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001906 bool CheckForMissingFields =
1907 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1908
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001909 while (Index < IList->getNumInits()) {
1910 Expr *Init = IList->getInit(Index);
1911
1912 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001913 // If we're not the subobject that matches up with the '{' for
1914 // the designator, we shouldn't be handling the
1915 // designator. Return immediately.
1916 if (!SubobjectIsDesignatorContext)
1917 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001918
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001919 // Handle this designated initializer. Field will be updated to
1920 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001921 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001922 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001923 StructuredList, StructuredIndex,
1924 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001925 hadError = true;
1926
Douglas Gregora9add4e2009-02-12 19:00:39 +00001927 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001928
1929 // Disable check for missing fields when designators are used.
1930 // This matches gcc behaviour.
1931 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001932 continue;
1933 }
1934
1935 if (Field == FieldEnd) {
1936 // We've run out of fields. We're done.
1937 break;
1938 }
1939
Douglas Gregora9add4e2009-02-12 19:00:39 +00001940 // We've already initialized a member of a union. We're done.
1941 if (InitializedSomething && DeclType->isUnionType())
1942 break;
1943
Douglas Gregor91f84212008-12-11 16:49:14 +00001944 // If we've hit the flexible array member at the end, we're done.
1945 if (Field->getType()->isIncompleteArrayType())
1946 break;
1947
Douglas Gregor51695702009-01-29 16:53:55 +00001948 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001949 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001950 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001951 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001952 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001953
Douglas Gregora82064c2011-06-29 21:51:31 +00001954 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001955 bool InvalidUse;
1956 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00001957 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001958 else
David Blaikie40ed2972012-06-06 20:45:41 +00001959 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001960 IList->getInit(Index)->getLocStart());
1961 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001962 ++Index;
1963 ++Field;
1964 hadError = true;
1965 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001966 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001967
Anders Carlsson6cabf312010-01-23 23:23:01 +00001968 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001969 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001970 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1971 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001972 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001973
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001974 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001975 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001976 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001977 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001978
1979 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001980 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001981
John McCalle40b58e2010-03-11 19:32:38 +00001982 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001983 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1984 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1985 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001986 // It is possible we have one or more unnamed bitfields remaining.
1987 // Find first (if any) named field and emit warning.
1988 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1989 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001990 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001991 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001992 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001993 break;
1994 }
1995 }
1996 }
1997
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001998 // Check that any remaining fields can be value-initialized.
1999 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2000 !Field->getType()->isIncompleteArrayType()) {
2001 // FIXME: Should check for holes left by designated initializers too.
2002 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00002003 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00002004 CheckEmptyInitializable(
2005 InitializedEntity::InitializeMember(*Field, &Entity),
2006 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002007 }
2008 }
2009
Mike Stump11289f42009-09-09 15:08:12 +00002010 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002011 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002012 return;
2013
David Blaikie40ed2972012-06-06 20:45:41 +00002014 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002015 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002016 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002017 ++Index;
2018 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002019 }
2020
Anders Carlsson6cabf312010-01-23 23:23:01 +00002021 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002022 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002023
Anders Carlsson6cabf312010-01-23 23:23:01 +00002024 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002026 StructuredList, StructuredIndex);
2027 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002029 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002030}
Steve Narofff8ecff22008-05-01 22:18:59 +00002031
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002032/// Expand a field designator that refers to a member of an
Douglas Gregord5846a12009-04-15 06:41:24 +00002033/// anonymous struct or union into a series of field designators that
2034/// refers to the field within the appropriate subobject.
2035///
Douglas Gregord5846a12009-04-15 06:41:24 +00002036static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002037 DesignatedInitExpr *DIE,
2038 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002039 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002040 typedef DesignatedInitExpr::Designator Designator;
2041
Douglas Gregord5846a12009-04-15 06:41:24 +00002042 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002043 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002044 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2045 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2046 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002047 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002048 DIE->getDesignator(DesigIdx)->getDotLoc(),
2049 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2050 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002051 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2052 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002053 assert(isa<FieldDecl>(*PI));
2054 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002055 }
2056
2057 // Expand the current designator into the set of replacement
2058 // designators, so we have a full subobject path down to where the
2059 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002060 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002061 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002062}
Mike Stump11289f42009-09-09 15:08:12 +00002063
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002064static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2065 DesignatedInitExpr *DIE) {
2066 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2067 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2068 for (unsigned I = 0; I < NumIndexExprs; ++I)
2069 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002070 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2071 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002072 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002073 DIE->usesGNUSyntax(), DIE->getInit());
2074}
2075
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002076namespace {
2077
2078// Callback to only accept typo corrections that are for field members of
2079// the given struct or union.
2080class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2081 public:
2082 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2083 : Record(RD) {}
2084
Craig Toppere14c0f82014-03-12 04:55:44 +00002085 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002086 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2087 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2088 }
2089
2090 private:
2091 RecordDecl *Record;
2092};
2093
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002094} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002095
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002096/// Check the well-formedness of a C99 designated initializer.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002097///
2098/// Determines whether the designated initializer @p DIE, which
2099/// resides at the given @p Index within the initializer list @p
2100/// IList, is well-formed for a current object of type @p DeclType
2101/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002102/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002103/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002104///
2105/// @param IList The initializer list in which this designated
2106/// initializer occurs.
2107///
Douglas Gregora5324162009-04-15 04:56:10 +00002108/// @param DIE The designated initializer expression.
2109///
2110/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002111///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002112/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002113/// into which the designation in @p DIE should refer.
2114///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002115/// @param NextField If non-NULL and the first designator in @p DIE is
2116/// a field, this will be set to the field declaration corresponding
2117/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002118///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002119/// @param NextElementIndex If non-NULL and the first designator in @p
2120/// DIE is an array designator or GNU array-range designator, this
2121/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002122///
2123/// @param Index Index into @p IList where the designated initializer
2124/// @p DIE occurs.
2125///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002126/// @param StructuredList The initializer list expression that
2127/// describes all of the subobject initializers in the order they'll
2128/// actually be initialized.
2129///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002130/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002131bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002132InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002133 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002134 DesignatedInitExpr *DIE,
2135 unsigned DesigIdx,
2136 QualType &CurrentObjectType,
2137 RecordDecl::field_iterator *NextField,
2138 llvm::APSInt *NextElementIndex,
2139 unsigned &Index,
2140 InitListExpr *StructuredList,
2141 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002142 bool FinishSubobjectInit,
2143 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002144 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002145 // Check the actual initialization for the designated object type.
2146 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002147
2148 // Temporarily remove the designator expression from the
2149 // initializer list that the child calls see, so that we don't try
2150 // to re-process the designator.
2151 unsigned OldIndex = Index;
2152 IList->setInit(OldIndex, DIE->getInit());
2153
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002154 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002155 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002156
2157 // Restore the designated initializer expression in the syntactic
2158 // form of the initializer list.
2159 if (IList->getInit(OldIndex) != DIE->getInit())
2160 DIE->setInit(IList->getInit(OldIndex));
2161 IList->setInit(OldIndex, DIE);
2162
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002163 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002164 }
2165
Douglas Gregora5324162009-04-15 04:56:10 +00002166 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002167 bool IsFirstDesignator = (DesigIdx == 0);
2168 if (!VerifyOnly) {
2169 assert((IsFirstDesignator || StructuredList) &&
2170 "Need a non-designated initializer list to start from");
2171
2172 // Determine the structural initializer list that corresponds to the
2173 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002174 if (IsFirstDesignator)
2175 StructuredList = SyntacticToSemantic.lookup(IList);
2176 else {
2177 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2178 StructuredList->getInit(StructuredIndex) : nullptr;
2179 if (!ExistingInit && StructuredList->hasArrayFiller())
2180 ExistingInit = StructuredList->getArrayFiller();
2181
2182 if (!ExistingInit)
2183 StructuredList =
2184 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2185 StructuredList, StructuredIndex,
2186 SourceRange(D->getLocStart(),
2187 DIE->getLocEnd()));
2188 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2189 StructuredList = Result;
2190 else {
2191 if (DesignatedInitUpdateExpr *E =
2192 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2193 StructuredList = E->getUpdater();
2194 else {
2195 DesignatedInitUpdateExpr *DIUE =
2196 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2197 D->getLocStart(), ExistingInit,
2198 DIE->getLocEnd());
2199 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2200 StructuredList = DIUE->getUpdater();
2201 }
2202
2203 // We need to check on source range validity because the previous
2204 // initializer does not have to be an explicit initializer. e.g.,
2205 //
2206 // struct P { int a, b; };
2207 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2208 //
2209 // There is an overwrite taking place because the first braced initializer
2210 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2211 if (ExistingInit->getSourceRange().isValid()) {
2212 // We are creating an initializer list that initializes the
2213 // subobjects of the current object, but there was already an
2214 // initialization that completely initialized the current
2215 // subobject, e.g., by a compound literal:
2216 //
2217 // struct X { int a, b; };
2218 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2219 //
2220 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2221 // designated initializer re-initializes the whole
2222 // subobject [0], overwriting previous initializers.
2223 SemaRef.Diag(D->getLocStart(),
2224 diag::warn_subobject_initializer_overrides)
2225 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2226
2227 SemaRef.Diag(ExistingInit->getLocStart(),
2228 diag::note_previous_initializer)
2229 << /*FIXME:has side effects=*/0
2230 << ExistingInit->getSourceRange();
2231 }
2232 }
2233 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002234 assert(StructuredList && "Expected a structured initializer list");
2235 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002236
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002237 if (D->isFieldDesignator()) {
2238 // C99 6.7.8p7:
2239 //
2240 // If a designator has the form
2241 //
2242 // . identifier
2243 //
2244 // then the current object (defined below) shall have
2245 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002246 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002247 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002248 if (!RT) {
2249 SourceLocation Loc = D->getDotLoc();
2250 if (Loc.isInvalid())
2251 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002252 if (!VerifyOnly)
2253 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002254 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002255 ++Index;
2256 return true;
2257 }
2258
Douglas Gregord5846a12009-04-15 06:41:24 +00002259 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002260 if (!KnownField) {
2261 IdentifierInfo *FieldName = D->getFieldName();
2262 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2263 for (NamedDecl *ND : Lookup) {
2264 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2265 KnownField = FD;
2266 break;
2267 }
2268 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002269 // In verify mode, don't modify the original.
2270 if (VerifyOnly)
2271 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002272 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002273 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002274 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002275 break;
2276 }
2277 }
David Majnemer36ef8982014-08-11 18:33:59 +00002278 if (!KnownField) {
2279 if (VerifyOnly) {
2280 ++Index;
2281 return true; // No typo correction when just trying this out.
2282 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002283
David Majnemer36ef8982014-08-11 18:33:59 +00002284 // Name lookup found something, but it wasn't a field.
2285 if (!Lookup.empty()) {
2286 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2287 << FieldName;
2288 SemaRef.Diag(Lookup.front()->getLocation(),
2289 diag::note_field_designator_found);
2290 ++Index;
2291 return true;
2292 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002293
David Majnemer36ef8982014-08-11 18:33:59 +00002294 // Name lookup didn't find anything.
2295 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002296 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2297 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002298 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002299 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2300 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002301 SemaRef.diagnoseTypo(
2302 Corrected,
2303 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002304 << FieldName << CurrentObjectType);
2305 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002306 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002307 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002308 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002309 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2310 << FieldName << CurrentObjectType;
2311 ++Index;
2312 return true;
2313 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002314 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002315 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002316
David Majnemer58e4ea92014-08-23 01:48:50 +00002317 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002318
2319 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2320 FieldIndex = CXXRD->getNumBases();
2321
David Majnemer58e4ea92014-08-23 01:48:50 +00002322 for (auto *FI : RT->getDecl()->fields()) {
2323 if (FI->isUnnamedBitfield())
2324 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002325 if (declaresSameEntity(KnownField, FI)) {
2326 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002327 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002328 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002329 ++FieldIndex;
2330 }
2331
David Majnemer36ef8982014-08-11 18:33:59 +00002332 RecordDecl::field_iterator Field =
2333 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2334
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002335 // All of the fields of a union are located at the same place in
2336 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002337 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002338 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002339 if (!VerifyOnly) {
2340 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002341 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002342 assert(StructuredList->getNumInits() == 1
2343 && "A union should never have more than one initializer!");
2344
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002345 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002346 if (ExistingInit) {
2347 // We're about to throw away an initializer, emit warning.
2348 SemaRef.Diag(D->getFieldLoc(),
2349 diag::warn_initializer_overrides)
2350 << D->getSourceRange();
2351 SemaRef.Diag(ExistingInit->getLocStart(),
2352 diag::note_previous_initializer)
2353 << /*FIXME:has side effects=*/0
2354 << ExistingInit->getSourceRange();
2355 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002356
2357 // remove existing initializer
2358 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002359 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002360 }
2361
David Blaikie40ed2972012-06-06 20:45:41 +00002362 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002363 }
Douglas Gregor51695702009-01-29 16:53:55 +00002364 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002365
Douglas Gregora82064c2011-06-29 21:51:31 +00002366 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002367 bool InvalidUse;
2368 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002369 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002370 else
David Blaikie40ed2972012-06-06 20:45:41 +00002371 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002372 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002373 ++Index;
2374 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002375 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002376
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002377 if (!VerifyOnly) {
2378 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002379 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002380
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002381 // Make sure that our non-designated initializer list has space
2382 // for a subobject corresponding to this field.
2383 if (FieldIndex >= StructuredList->getNumInits())
2384 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2385 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002386
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002387 // This designator names a flexible array member.
2388 if (Field->getType()->isIncompleteArrayType()) {
2389 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002390 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002391 // We can't designate an object within the flexible array
2392 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002393 if (!VerifyOnly) {
2394 DesignatedInitExpr::Designator *NextD
2395 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002396 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002397 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002398 << SourceRange(NextD->getLocStart(),
2399 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002400 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002401 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002402 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002403 Invalid = true;
2404 }
2405
Chris Lattner001b29c2010-10-10 17:49:49 +00002406 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2407 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002408 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002409 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002410 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002411 diag::err_flexible_array_init_needs_braces)
2412 << DIE->getInit()->getSourceRange();
2413 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002414 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002415 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002416 Invalid = true;
2417 }
2418
Eli Friedman3fa64df2011-08-23 22:24:57 +00002419 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002420 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002421 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002422 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002423
2424 if (Invalid) {
2425 ++Index;
2426 return true;
2427 }
2428
2429 // Initialize the array.
2430 bool prevHadError = hadError;
2431 unsigned newStructuredIndex = FieldIndex;
2432 unsigned OldIndex = Index;
2433 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002434
2435 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002436 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002437 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002438 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002439
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002440 IList->setInit(OldIndex, DIE);
2441 if (hadError && !prevHadError) {
2442 ++Field;
2443 ++FieldIndex;
2444 if (NextField)
2445 *NextField = Field;
2446 StructuredIndex = FieldIndex;
2447 return true;
2448 }
2449 } else {
2450 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002451 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002452 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002453
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002454 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002455 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002456 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002457 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002458 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002459 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002460 return true;
2461 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002462
2463 // Find the position of the next field to be initialized in this
2464 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002465 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002466 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002467
2468 // If this the first designator, our caller will continue checking
2469 // the rest of this struct/class/union subobject.
2470 if (IsFirstDesignator) {
2471 if (NextField)
2472 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002473 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002474 return false;
2475 }
2476
Douglas Gregor17bd0942009-01-28 23:36:17 +00002477 if (!FinishSubobjectInit)
2478 return false;
2479
Douglas Gregord5846a12009-04-15 06:41:24 +00002480 // We've already initialized something in the union; we're done.
2481 if (RT->getDecl()->isUnion())
2482 return hadError;
2483
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002484 // Check the remaining fields within this class/struct/union subobject.
2485 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486
Richard Smith872307e2016-03-08 22:17:41 +00002487 auto NoBases =
2488 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2489 CXXRecordDecl::base_class_iterator());
2490 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2491 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002492 return hadError && !prevHadError;
2493 }
2494
2495 // C99 6.7.8p6:
2496 //
2497 // If a designator has the form
2498 //
2499 // [ constant-expression ]
2500 //
2501 // then the current object (defined below) shall have array
2502 // type and the expression shall be an integer constant
2503 // expression. If the array is of unknown size, any
2504 // nonnegative value is valid.
2505 //
2506 // Additionally, cope with the GNU extension that permits
2507 // designators of the form
2508 //
2509 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002510 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002511 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002512 if (!VerifyOnly)
2513 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2514 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002515 ++Index;
2516 return true;
2517 }
2518
Craig Topperc3ec1492014-05-26 06:22:03 +00002519 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002520 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2521 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002522 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002523 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002524 DesignatedEndIndex = DesignatedStartIndex;
2525 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002526 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002527
Mike Stump11289f42009-09-09 15:08:12 +00002528 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002529 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002530 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002531 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002532 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002533
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002534 // Codegen can't handle evaluating array range designators that have side
2535 // effects, because we replicate the AST value for each initialized element.
2536 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2537 // elements with something that has a side effect, so codegen can emit an
2538 // "error unsupported" error instead of miscompiling the app.
2539 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002540 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002541 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002542 }
2543
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002544 if (isa<ConstantArrayType>(AT)) {
2545 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002546 DesignatedStartIndex
2547 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002548 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002549 DesignatedEndIndex
2550 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002551 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2552 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002553 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002554 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002555 diag::err_array_designator_too_large)
2556 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2557 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002558 ++Index;
2559 return true;
2560 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002561 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002562 unsigned DesignatedIndexBitWidth =
2563 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2564 DesignatedStartIndex =
2565 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2566 DesignatedEndIndex =
2567 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002568 DesignatedStartIndex.setIsUnsigned(true);
2569 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002570 }
Mike Stump11289f42009-09-09 15:08:12 +00002571
Eli Friedman1f16b742013-06-11 21:48:11 +00002572 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2573 // We're modifying a string literal init; we have to decompose the string
2574 // so we can modify the individual characters.
2575 ASTContext &Context = SemaRef.Context;
2576 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2577
2578 // Compute the character type
2579 QualType CharTy = AT->getElementType();
2580
2581 // Compute the type of the integer literals.
2582 QualType PromotedCharTy = CharTy;
2583 if (CharTy->isPromotableIntegerType())
2584 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2585 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2586
2587 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2588 // Get the length of the string.
2589 uint64_t StrLen = SL->getLength();
2590 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2591 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2592 StructuredList->resizeInits(Context, StrLen);
2593
2594 // Build a literal for each character in the string, and put them into
2595 // the init list.
2596 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2597 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2598 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002599 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002600 if (CharTy != PromotedCharTy)
2601 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002602 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002603 StructuredList->updateInit(Context, i, Init);
2604 }
2605 } else {
2606 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2607 std::string Str;
2608 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2609
2610 // Get the length of the string.
2611 uint64_t StrLen = Str.size();
2612 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2613 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2614 StructuredList->resizeInits(Context, StrLen);
2615
2616 // Build a literal for each character in the string, and put them into
2617 // the init list.
2618 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2619 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2620 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002621 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002622 if (CharTy != PromotedCharTy)
2623 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002624 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002625 StructuredList->updateInit(Context, i, Init);
2626 }
2627 }
2628 }
2629
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002630 // Make sure that our non-designated initializer list has space
2631 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002632 if (!VerifyOnly &&
2633 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002634 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002635 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002636
Douglas Gregor17bd0942009-01-28 23:36:17 +00002637 // Repeatedly perform subobject initializations in the range
2638 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002639
Douglas Gregor17bd0942009-01-28 23:36:17 +00002640 // Move to the next designator
2641 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2642 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002643
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002644 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002645 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002646
Douglas Gregor17bd0942009-01-28 23:36:17 +00002647 while (DesignatedStartIndex <= DesignatedEndIndex) {
2648 // Recurse to check later designated subobjects.
2649 QualType ElementType = AT->getElementType();
2650 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002651
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002652 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002653 if (CheckDesignatedInitializer(
2654 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2655 nullptr, Index, StructuredList, ElementIndex,
2656 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2657 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002658 return true;
2659
2660 // Move to the next index in the array that we'll be initializing.
2661 ++DesignatedStartIndex;
2662 ElementIndex = DesignatedStartIndex.getZExtValue();
2663 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002664
2665 // If this the first designator, our caller will continue checking
2666 // the rest of this array subobject.
2667 if (IsFirstDesignator) {
2668 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002669 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002670 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002671 return false;
2672 }
Mike Stump11289f42009-09-09 15:08:12 +00002673
Douglas Gregor17bd0942009-01-28 23:36:17 +00002674 if (!FinishSubobjectInit)
2675 return false;
2676
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002677 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002678 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002679 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002680 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002681 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002682 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002683}
2684
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002685// Get the structured initializer list for a subobject of type
2686// @p CurrentObjectType.
2687InitListExpr *
2688InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2689 QualType CurrentObjectType,
2690 InitListExpr *StructuredList,
2691 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002692 SourceRange InitRange,
2693 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002694 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002695 return nullptr; // No structured list in verification-only mode.
2696 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002697 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002698 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002699 else if (StructuredIndex < StructuredList->getNumInits())
2700 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002701
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002702 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002703 // There might have already been initializers for subobjects of the current
2704 // object, but a subsequent initializer list will overwrite the entirety
2705 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2706 //
2707 // struct P { char x[6]; };
2708 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2709 //
2710 // The first designated initializer is ignored, and l.x is just "f".
2711 if (!IsFullyOverwritten)
2712 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002713
2714 if (ExistingInit) {
2715 // We are creating an initializer list that initializes the
2716 // subobjects of the current object, but there was already an
2717 // initialization that completely initialized the current
2718 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002719 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002720 // struct X { int a, b; };
2721 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002722 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002723 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2724 // designated initializer re-initializes the whole
2725 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002726 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002727 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002728 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002729 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002730 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002731 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002732 << ExistingInit->getSourceRange();
2733 }
2734
Mike Stump11289f42009-09-09 15:08:12 +00002735 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002736 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002737 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002738 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002739
Eli Friedman91f5ae52012-02-23 02:25:10 +00002740 QualType ResultType = CurrentObjectType;
2741 if (!ResultType->isArrayType())
2742 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2743 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002744
Douglas Gregor6d00c992009-03-20 23:58:33 +00002745 // Pre-allocate storage for the structured initializer list.
2746 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002747 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002748 bool GotNumInits = false;
2749 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002750 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002751 GotNumInits = true;
2752 } else if (Index < IList->getNumInits()) {
2753 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002754 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002755 GotNumInits = true;
2756 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002757 }
2758
Mike Stump11289f42009-09-09 15:08:12 +00002759 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002760 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2761 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2762 NumElements = CAType->getSize().getZExtValue();
2763 // Simple heuristic so that we don't allocate a very large
2764 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002765 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002766 NumElements = 0;
2767 }
John McCall9dd450b2009-09-21 23:43:11 +00002768 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002769 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002770 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002771 RecordDecl *RDecl = RType->getDecl();
2772 if (RDecl->isUnion())
2773 NumElements = 1;
2774 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002775 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002776 }
2777
Ted Kremenekac034612010-04-13 23:39:13 +00002778 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002779
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002780 // Link this new initializer list into the structured initializer
2781 // lists.
2782 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002783 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002784 else {
2785 Result->setSyntacticForm(IList);
2786 SyntacticToSemantic[IList] = Result;
2787 }
2788
2789 return Result;
2790}
2791
2792/// Update the initializer at index @p StructuredIndex within the
2793/// structured initializer list to the value @p expr.
2794void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2795 unsigned &StructuredIndex,
2796 Expr *expr) {
2797 // No structured initializer list to update
2798 if (!StructuredList)
2799 return;
2800
Ted Kremenekac034612010-04-13 23:39:13 +00002801 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2802 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002803 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002804 // We need to check on source range validity because the previous
2805 // initializer does not have to be an explicit initializer.
2806 // struct P { int a, b; };
2807 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2808 // There is an overwrite taking place because the first braced initializer
2809 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2810 if (PrevInit->getSourceRange().isValid()) {
2811 SemaRef.Diag(expr->getLocStart(),
2812 diag::warn_initializer_overrides)
2813 << expr->getSourceRange();
2814
2815 SemaRef.Diag(PrevInit->getLocStart(),
2816 diag::note_previous_initializer)
2817 << /*FIXME:has side effects=*/0
2818 << PrevInit->getSourceRange();
2819 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002820 }
Mike Stump11289f42009-09-09 15:08:12 +00002821
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002822 ++StructuredIndex;
2823}
2824
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002825/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002826/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002827/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002828/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002829/// failure. Returns the index expression, possibly with an implicit cast
2830/// added, on success. If everything went okay, Value will receive the
2831/// value of the constant expression.
2832static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002833CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002834 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002835
2836 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002837 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2838 if (Result.isInvalid())
2839 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002840
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002841 if (Value.isSigned() && Value.isNegative())
2842 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002843 << Value.toString(10) << Index->getSourceRange();
2844
Douglas Gregor51650d32009-01-23 21:04:18 +00002845 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002846 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002847}
2848
John McCalldadc5752010-08-24 06:29:42 +00002849ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002850 SourceLocation Loc,
2851 bool GNUSyntax,
2852 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002853 typedef DesignatedInitExpr::Designator ASTDesignator;
2854
2855 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002856 SmallVector<ASTDesignator, 32> Designators;
2857 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002858
2859 // Build designators and check array designator expressions.
2860 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2861 const Designator &D = Desig.getDesignator(Idx);
2862 switch (D.getKind()) {
2863 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002864 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002865 D.getFieldLoc()));
2866 break;
2867
2868 case Designator::ArrayDesignator: {
2869 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2870 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002871 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002872 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002873 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002874 Invalid = true;
2875 else {
2876 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002877 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002878 D.getRBracketLoc()));
2879 InitExpressions.push_back(Index);
2880 }
2881 break;
2882 }
2883
2884 case Designator::ArrayRangeDesignator: {
2885 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2886 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2887 llvm::APSInt StartValue;
2888 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002889 bool StartDependent = StartIndex->isTypeDependent() ||
2890 StartIndex->isValueDependent();
2891 bool EndDependent = EndIndex->isTypeDependent() ||
2892 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002893 if (!StartDependent)
2894 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002895 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002896 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002897 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002898
2899 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002900 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002901 else {
2902 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002903 if (StartDependent || EndDependent) {
2904 // Nothing to compute.
2905 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002906 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002907 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002908 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002909
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002910 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002911 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002912 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002913 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2914 Invalid = true;
2915 } else {
2916 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002917 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002918 D.getEllipsisLoc(),
2919 D.getRBracketLoc()));
2920 InitExpressions.push_back(StartIndex);
2921 InitExpressions.push_back(EndIndex);
2922 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002923 }
2924 break;
2925 }
2926 }
2927 }
2928
2929 if (Invalid || Init.isInvalid())
2930 return ExprError();
2931
2932 // Clear out the expressions within the designation.
2933 Desig.ClearExprs(*this);
2934
2935 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002936 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00002937 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002938 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002939 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940
David Blaikiebbafb8a2012-03-11 07:00:24 +00002941 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002942 Diag(DIE->getLocStart(), diag::ext_designated_init)
2943 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002944
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002945 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002946}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002947
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002948//===----------------------------------------------------------------------===//
2949// Initialization entity
2950//===----------------------------------------------------------------------===//
2951
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002953 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002955{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002956 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2957 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002958 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002959 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002960 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002961 Type = VT->getElementType();
2962 } else {
2963 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2964 assert(CT && "Unexpected type");
2965 Kind = EK_ComplexElement;
2966 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002967 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002968}
2969
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002970InitializedEntity
2971InitializedEntity::InitializeBase(ASTContext &Context,
2972 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00002973 bool IsInheritedVirtualBase,
2974 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002975 InitializedEntity Result;
2976 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00002977 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002978 Result.Base = reinterpret_cast<uintptr_t>(Base);
2979 if (IsInheritedVirtualBase)
2980 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002981
Douglas Gregor1b303932009-12-22 15:35:07 +00002982 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002983 return Result;
2984}
2985
Douglas Gregor85dabae2009-12-16 01:38:02 +00002986DeclarationName InitializedEntity::getName() const {
2987 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002988 case EK_Parameter:
2989 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002990 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2991 return (D ? D->getDeclName() : DeclarationName());
2992 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002993
2994 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002995 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002996 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002997 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002998
Douglas Gregor19666fb2012-02-15 16:57:26 +00002999 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003000 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00003001
Douglas Gregor85dabae2009-12-16 01:38:02 +00003002 case EK_Result:
3003 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003004 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003005 case EK_Temporary:
3006 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003007 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003008 case EK_ArrayElement:
3009 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003010 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003011 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003012 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003013 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003014 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003015 return DeclarationName();
3016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017
David Blaikie8a40f702012-01-17 06:56:22 +00003018 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003019}
3020
Richard Smith7873de02016-08-11 22:25:46 +00003021ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003022 switch (getKind()) {
3023 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003024 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003025 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003026 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003027
John McCall31168b02011-06-15 23:02:42 +00003028 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003029 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003030 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3031
Douglas Gregora4b592a2009-12-19 03:01:41 +00003032 case EK_Result:
3033 case EK_Exception:
3034 case EK_New:
3035 case EK_Temporary:
3036 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003037 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003038 case EK_ArrayElement:
3039 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003040 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003041 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003042 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003043 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003044 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003045 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003046 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
David Blaikie8a40f702012-01-17 06:56:22 +00003049 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003050}
3051
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003052bool InitializedEntity::allowsNRVO() const {
3053 switch (getKind()) {
3054 case EK_Result:
3055 case EK_Exception:
3056 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003058 case EK_Variable:
3059 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003060 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003061 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003062 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003063 case EK_New:
3064 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003065 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003066 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003067 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003068 case EK_ArrayElement:
3069 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003070 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003071 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003072 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003073 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003074 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003075 break;
3076 }
3077
3078 return false;
3079}
3080
Richard Smithe6c01442013-06-05 00:46:14 +00003081unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003082 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003083 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3084 for (unsigned I = 0; I != Depth; ++I)
3085 OS << "`-";
3086
3087 switch (getKind()) {
3088 case EK_Variable: OS << "Variable"; break;
3089 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003090 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3091 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003092 case EK_Result: OS << "Result"; break;
3093 case EK_Exception: OS << "Exception"; break;
3094 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003095 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003096 case EK_New: OS << "New"; break;
3097 case EK_Temporary: OS << "Temporary"; break;
3098 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003099 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003100 case EK_Base: OS << "Base"; break;
3101 case EK_Delegating: OS << "Delegating"; break;
3102 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3103 case EK_VectorElement: OS << "VectorElement " << Index; break;
3104 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3105 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003106 case EK_LambdaToBlockConversionBlockElement:
3107 OS << "Block (lambda)";
3108 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003109 case EK_LambdaCapture:
3110 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003111 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003112 break;
3113 }
3114
Richard Smith7873de02016-08-11 22:25:46 +00003115 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003116 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003117 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003118 }
3119
3120 OS << " '" << getType().getAsString() << "'\n";
3121
3122 return Depth + 1;
3123}
3124
Yaron Kerencdae9412016-01-29 19:38:18 +00003125LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003126 dumpImpl(llvm::errs());
3127}
3128
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003129//===----------------------------------------------------------------------===//
3130// Initialization sequence
3131//===----------------------------------------------------------------------===//
3132
3133void InitializationSequence::Step::Destroy() {
3134 switch (Kind) {
3135 case SK_ResolveAddressOfOverloadedFunction:
3136 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003137 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003138 case SK_CastDerivedToBaseLValue:
3139 case SK_BindReference:
3140 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003141 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003142 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003143 case SK_UserConversion:
3144 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003145 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003146 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003147 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003148 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003149 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003150 case SK_UnwrapInitList:
3151 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003152 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003153 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003154 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003155 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003156 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003157 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003158 case SK_ArrayLoopIndex:
3159 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003160 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003161 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003162 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003163 case SK_PassByIndirectCopyRestore:
3164 case SK_PassByIndirectRestore:
3165 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003166 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003167 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003168 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003169 case SK_OCLZeroEvent:
Egor Churaev89831422016-12-23 14:55:49 +00003170 case SK_OCLZeroQueue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003171 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003173 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003174 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003175 delete ICS;
3176 }
3177}
3178
Douglas Gregor838fcc32010-03-26 20:14:36 +00003179bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003180 // There can be some lvalue adjustments after the SK_BindReference step.
3181 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3182 if (I->Kind == SK_BindReference)
3183 return true;
3184 if (I->Kind == SK_BindReferenceToTemporary)
3185 return false;
3186 }
3187 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003188}
3189
3190bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003191 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003192 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193
Douglas Gregor838fcc32010-03-26 20:14:36 +00003194 switch (getFailureKind()) {
3195 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003196 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003197 case FK_ArrayNeedsInitList:
3198 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003199 case FK_ArrayNeedsInitListOrWideStringLiteral:
3200 case FK_NarrowStringIntoWideCharArray:
3201 case FK_WideStringIntoCharArray:
3202 case FK_IncompatWideStringIntoWideChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00003203 case FK_PlainStringIntoUTF8Char:
3204 case FK_UTF8StringIntoPlainChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003205 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3206 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003207 case FK_NonConstLValueReferenceBindingToBitfield:
3208 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003209 case FK_NonConstLValueReferenceBindingToUnrelated:
3210 case FK_RValueReferenceBindingToLValue:
3211 case FK_ReferenceInitDropsQualifiers:
3212 case FK_ReferenceInitFailed:
3213 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003214 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003215 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003216 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003217 case FK_ReferenceBindingToInitList:
3218 case FK_InitListBadDestinationType:
3219 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003220 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003221 case FK_ArrayTypeMismatch:
3222 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003223 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003224 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003225 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003226 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003227 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003228 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229
Douglas Gregor838fcc32010-03-26 20:14:36 +00003230 case FK_ReferenceInitOverloadFailed:
3231 case FK_UserConversionOverloadFailed:
3232 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003233 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003234 return FailedOverloadResult == OR_Ambiguous;
3235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
David Blaikie8a40f702012-01-17 06:56:22 +00003237 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003238}
3239
Douglas Gregorb33eed02010-04-16 22:09:46 +00003240bool InitializationSequence::isConstructorInitialization() const {
3241 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3242}
3243
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003244void
3245InitializationSequence
3246::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3247 DeclAccessPair Found,
3248 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003249 Step S;
3250 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3251 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003252 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003253 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003254 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003255 Steps.push_back(S);
3256}
3257
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003259 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003260 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003261 switch (VK) {
3262 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3263 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3264 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003265 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003266 S.Type = BaseType;
3267 Steps.push_back(S);
3268}
3269
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003270void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003271 bool BindingTemporary) {
3272 Step S;
3273 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3274 S.Type = T;
3275 Steps.push_back(S);
3276}
3277
Richard Smithb8c0f552016-12-09 18:49:13 +00003278void InitializationSequence::AddFinalCopy(QualType T) {
3279 Step S;
3280 S.Kind = SK_FinalCopy;
3281 S.Type = T;
3282 Steps.push_back(S);
3283}
3284
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003285void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3286 Step S;
3287 S.Kind = SK_ExtraneousCopyToTemporary;
3288 S.Type = T;
3289 Steps.push_back(S);
3290}
3291
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003292void
3293InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3294 DeclAccessPair FoundDecl,
3295 QualType T,
3296 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003297 Step S;
3298 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003299 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003300 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003301 S.Function.Function = Function;
3302 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003303 Steps.push_back(S);
3304}
3305
3306void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003307 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003308 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003309 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003310 switch (VK) {
3311 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003312 S.Kind = SK_QualificationConversionRValue;
3313 break;
John McCall2536c6d2010-08-25 10:28:54 +00003314 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003315 S.Kind = SK_QualificationConversionXValue;
3316 break;
John McCall2536c6d2010-08-25 10:28:54 +00003317 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003318 S.Kind = SK_QualificationConversionLValue;
3319 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003320 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003321 S.Type = Ty;
3322 Steps.push_back(S);
3323}
3324
Richard Smith77be48a2014-07-31 06:31:19 +00003325void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3326 Step S;
3327 S.Kind = SK_AtomicConversion;
3328 S.Type = Ty;
3329 Steps.push_back(S);
3330}
3331
Jordan Roseb1312a52013-04-11 00:58:58 +00003332void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3333 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3334
3335 Step S;
3336 S.Kind = SK_LValueToRValue;
3337 S.Type = Ty;
3338 Steps.push_back(S);
3339}
3340
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003341void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003342 const ImplicitConversionSequence &ICS, QualType T,
3343 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003344 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003345 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3346 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003347 S.Type = T;
3348 S.ICS = new ImplicitConversionSequence(ICS);
3349 Steps.push_back(S);
3350}
3351
Douglas Gregor51e77d52009-12-10 17:56:55 +00003352void InitializationSequence::AddListInitializationStep(QualType T) {
3353 Step S;
3354 S.Kind = SK_ListInitialization;
3355 S.Type = T;
3356 Steps.push_back(S);
3357}
3358
Richard Smith55c28882016-05-12 23:45:49 +00003359void InitializationSequence::AddConstructorInitializationStep(
3360 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3361 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003362 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003363 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003364 : SK_ConstructorInitializationFromList
3365 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003366 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003367 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003368 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003369 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003370 Steps.push_back(S);
3371}
3372
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003373void InitializationSequence::AddZeroInitializationStep(QualType T) {
3374 Step S;
3375 S.Kind = SK_ZeroInitialization;
3376 S.Type = T;
3377 Steps.push_back(S);
3378}
3379
Douglas Gregore1314a62009-12-18 05:02:21 +00003380void InitializationSequence::AddCAssignmentStep(QualType T) {
3381 Step S;
3382 S.Kind = SK_CAssignment;
3383 S.Type = T;
3384 Steps.push_back(S);
3385}
3386
Eli Friedman78275202009-12-19 08:11:05 +00003387void InitializationSequence::AddStringInitStep(QualType T) {
3388 Step S;
3389 S.Kind = SK_StringInit;
3390 S.Type = T;
3391 Steps.push_back(S);
3392}
3393
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003394void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3395 Step S;
3396 S.Kind = SK_ObjCObjectConversion;
3397 S.Type = T;
3398 Steps.push_back(S);
3399}
3400
Richard Smith378b8c82016-12-14 03:22:16 +00003401void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003402 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003403 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003404 S.Type = T;
3405 Steps.push_back(S);
3406}
3407
Richard Smith410306b2016-12-12 02:53:20 +00003408void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3409 Step S;
3410 S.Kind = SK_ArrayLoopIndex;
3411 S.Type = EltT;
3412 Steps.insert(Steps.begin(), S);
3413
3414 S.Kind = SK_ArrayLoopInit;
3415 S.Type = T;
3416 Steps.push_back(S);
3417}
3418
Richard Smithebeed412012-02-15 22:38:09 +00003419void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3420 Step S;
3421 S.Kind = SK_ParenthesizedArrayInit;
3422 S.Type = T;
3423 Steps.push_back(S);
3424}
3425
John McCall31168b02011-06-15 23:02:42 +00003426void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3427 bool shouldCopy) {
3428 Step s;
3429 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3430 : SK_PassByIndirectRestore);
3431 s.Type = type;
3432 Steps.push_back(s);
3433}
3434
3435void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3436 Step S;
3437 S.Kind = SK_ProduceObjCObject;
3438 S.Type = T;
3439 Steps.push_back(S);
3440}
3441
Sebastian Redlc1839b12012-01-17 22:49:42 +00003442void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3443 Step S;
3444 S.Kind = SK_StdInitializerList;
3445 S.Type = T;
3446 Steps.push_back(S);
3447}
3448
Guy Benyei61054192013-02-07 10:55:47 +00003449void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3450 Step S;
3451 S.Kind = SK_OCLSamplerInit;
3452 S.Type = T;
3453 Steps.push_back(S);
3454}
3455
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003456void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3457 Step S;
3458 S.Kind = SK_OCLZeroEvent;
3459 S.Type = T;
3460 Steps.push_back(S);
3461}
3462
Egor Churaev89831422016-12-23 14:55:49 +00003463void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3464 Step S;
3465 S.Kind = SK_OCLZeroQueue;
3466 S.Type = T;
3467 Steps.push_back(S);
3468}
3469
Sebastian Redl29526f02011-11-27 16:50:07 +00003470void InitializationSequence::RewrapReferenceInitList(QualType T,
3471 InitListExpr *Syntactic) {
3472 assert(Syntactic->getNumInits() == 1 &&
3473 "Can only rewrap trivial init lists.");
3474 Step S;
3475 S.Kind = SK_UnwrapInitList;
3476 S.Type = Syntactic->getInit(0)->getType();
3477 Steps.insert(Steps.begin(), S);
3478
3479 S.Kind = SK_RewrapInitList;
3480 S.Type = T;
3481 S.WrappingSyntacticList = Syntactic;
3482 Steps.push_back(S);
3483}
3484
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003486 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003487 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003488 this->Failure = Failure;
3489 this->FailedOverloadResult = Result;
3490}
3491
3492//===----------------------------------------------------------------------===//
3493// Attempt initialization
3494//===----------------------------------------------------------------------===//
3495
Nico Weber337d5aa2015-04-17 08:32:38 +00003496/// Tries to add a zero initializer. Returns true if that worked.
3497static bool
3498maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3499 const InitializedEntity &Entity) {
3500 if (Entity.getKind() != InitializedEntity::EK_Variable)
3501 return false;
3502
3503 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3504 if (VD->getInit() || VD->getLocEnd().isMacroID())
3505 return false;
3506
3507 QualType VariableTy = VD->getType().getCanonicalType();
3508 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3509 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3510 if (!Init.empty()) {
3511 Sequence.AddZeroInitializationStep(Entity.getType());
3512 Sequence.SetZeroInitializationFixit(Init, Loc);
3513 return true;
3514 }
3515 return false;
3516}
3517
John McCall31168b02011-06-15 23:02:42 +00003518static void MaybeProduceObjCObject(Sema &S,
3519 InitializationSequence &Sequence,
3520 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003521 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003522
3523 /// When initializing a parameter, produce the value if it's marked
3524 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003525 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003526 if (!Entity.isParameterConsumed())
3527 return;
3528
3529 assert(Entity.getType()->isObjCRetainableType() &&
3530 "consuming an object of unretainable type?");
3531 Sequence.AddProduceObjCObjectStep(Entity.getType());
3532
3533 /// When initializing a return value, if the return type is a
3534 /// retainable type, then returns need to immediately retain the
3535 /// object. If an autorelease is required, it will be done at the
3536 /// last instant.
3537 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3538 if (!Entity.getType()->isObjCRetainableType())
3539 return;
3540
3541 Sequence.AddProduceObjCObjectStep(Entity.getType());
3542 }
3543}
3544
Richard Smithcc1b96d2013-06-12 22:31:48 +00003545static void TryListInitialization(Sema &S,
3546 const InitializedEntity &Entity,
3547 const InitializationKind &Kind,
3548 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003549 InitializationSequence &Sequence,
3550 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003551
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003552/// When initializing from init list via constructor, handle
Richard Smithd86812d2012-07-05 08:39:21 +00003553/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003554///
Richard Smithd86812d2012-07-05 08:39:21 +00003555/// \return true if we have handled initialization of an object of type
3556/// std::initializer_list<T>, false otherwise.
3557static bool TryInitializerListConstruction(Sema &S,
3558 InitListExpr *List,
3559 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003560 InitializationSequence &Sequence,
3561 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003562 QualType E;
3563 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003564 return false;
3565
Richard Smithdb0ac552015-12-18 22:40:25 +00003566 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003567 Sequence.setIncompleteTypeFailure(E);
3568 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003569 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003570
3571 // Try initializing a temporary array from the init list.
3572 QualType ArrayType = S.Context.getConstantArrayType(
3573 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3574 List->getNumInits()),
3575 clang::ArrayType::Normal, 0);
3576 InitializedEntity HiddenArray =
3577 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003578 InitializationKind Kind = InitializationKind::CreateDirectList(
3579 List->getExprLoc(), List->getLocStart(), List->getLocEnd());
Manman Ren073db022016-03-10 18:53:19 +00003580 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3581 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003582 if (Sequence)
3583 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003584 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003585}
3586
Richard Smith7c2bcc92016-09-07 02:14:33 +00003587/// Determine if the constructor has the signature of a copy or move
3588/// constructor for the type T of the class in which it was found. That is,
3589/// determine if its first parameter is of type T or reference to (possibly
3590/// cv-qualified) T.
3591static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3592 const ConstructorInfo &Info) {
3593 if (Info.Constructor->getNumParams() == 0)
3594 return false;
3595
3596 QualType ParmT =
3597 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3598 QualType ClassT =
3599 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3600
3601 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3602}
3603
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003604static OverloadingResult
3605ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003606 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003607 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003608 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003609 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003610 OverloadCandidateSet::iterator &Best,
3611 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003612 bool OnlyListConstructors, bool IsListInit,
3613 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003614 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003615
Richard Smith40c78062015-02-21 02:31:57 +00003616 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003617 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003618 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003619 continue;
3620
Richard Smith7c2bcc92016-09-07 02:14:33 +00003621 if (!AllowExplicit && Info.Constructor->isExplicit())
3622 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003623
Richard Smith7c2bcc92016-09-07 02:14:33 +00003624 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3625 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003626
Richard Smith7c2bcc92016-09-07 02:14:33 +00003627 // C++11 [over.best.ics]p4:
3628 // ... and the constructor or user-defined conversion function is a
3629 // candidate by
3630 // - 13.3.1.3, when the argument is the temporary in the second step
3631 // of a class copy-initialization, or
3632 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3633 // - the second phase of 13.3.1.7 when the initializer list has exactly
3634 // one element that is itself an initializer list, and the target is
3635 // the first parameter of a constructor of class X, and the conversion
3636 // is to X or reference to (possibly cv-qualified X),
3637 // user-defined conversion sequences are not considered.
3638 bool SuppressUserConversions =
3639 SecondStepOfCopyInit ||
3640 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3641 hasCopyOrMoveCtorParam(S.Context, Info));
3642
3643 if (Info.ConstructorTmpl)
3644 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3645 /*ExplicitArgs*/ nullptr, Args,
3646 CandidateSet, SuppressUserConversions);
3647 else {
3648 // C++ [over.match.copy]p1:
3649 // - When initializing a temporary to be bound to the first parameter
3650 // of a constructor [for type T] that takes a reference to possibly
3651 // cv-qualified T as its first argument, called with a single
3652 // argument in the context of direct-initialization, explicit
3653 // conversion functions are also considered.
3654 // FIXME: What if a constructor template instantiates to such a signature?
3655 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3656 Args.size() == 1 &&
3657 hasCopyOrMoveCtorParam(S.Context, Info);
3658 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3659 CandidateSet, SuppressUserConversions,
3660 /*PartialOverloading=*/false,
3661 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003662 }
3663 }
3664
Richard Smith67ef14f2017-09-26 18:37:55 +00003665 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3666 //
3667 // When initializing an object of class type T by constructor
3668 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3669 // from a single expression of class type U, conversion functions of
3670 // U that convert to the non-reference type cv T are candidates.
3671 // Explicit conversion functions are only candidates during
3672 // direct-initialization.
3673 //
3674 // Note: SecondStepOfCopyInit is only ever true in this case when
3675 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003676 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003677 !SecondStepOfCopyInit) {
3678 Expr *Initializer = Args[0];
3679 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3680 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3681 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3682 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3683 NamedDecl *D = *I;
3684 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3685 D = D->getUnderlyingDecl();
3686
3687 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3688 CXXConversionDecl *Conv;
3689 if (ConvTemplate)
3690 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3691 else
3692 Conv = cast<CXXConversionDecl>(D);
3693
3694 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3695 if (ConvTemplate)
3696 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3697 ActingDC, Initializer, DestType,
3698 CandidateSet, AllowExplicit,
3699 /*AllowResultConversion*/false);
3700 else
3701 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3702 DestType, CandidateSet, AllowExplicit,
3703 /*AllowResultConversion*/false);
3704 }
3705 }
3706 }
3707 }
3708
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003709 // Perform overload resolution and return the result.
3710 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3711}
3712
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003713/// Attempt initialization by constructor (C++ [dcl.init]), which
Sebastian Redled2e5322011-12-22 14:44:04 +00003714/// enumerates the constructors of the initialized entity and performs overload
3715/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003716/// \param DestType The destination class type.
3717/// \param DestArrayType The destination type, which is either DestType or
3718/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003719/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003720/// \param IsInitListCopy Is this non-list-initialization resulting from a
3721/// list-initialization from {x} where x is the same
3722/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003723static void TryConstructorInitialization(Sema &S,
3724 const InitializedEntity &Entity,
3725 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003726 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003727 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003728 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003729 bool IsListInit = false,
3730 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003731 assert(((!IsListInit && !IsInitListCopy) ||
3732 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3733 "IsListInit/IsInitListCopy must come with a single initializer list "
3734 "argument.");
3735 InitListExpr *ILE =
3736 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3737 MultiExprArg UnwrappedArgs =
3738 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003739
Sebastian Redled2e5322011-12-22 14:44:04 +00003740 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003741 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003742 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003743 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003744 }
3745
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003746 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003747 // - If the initializer expression is a prvalue and the cv-unqualified
3748 // version of the source type is the same class as the class of the
3749 // destination, the initializer expression is used to initialize the
3750 // destination object.
3751 // Per DR (no number yet), this does not apply when initializing a base
3752 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003753 // ObjC++: Lambda captured by the block in the lambda to block conversion
3754 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003755 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003756 Entity.getKind() != InitializedEntity::EK_Base &&
3757 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003758 Entity.getKind() !=
3759 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003760 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3761 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3762 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003763 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003764 if (ILE)
3765 Sequence.RewrapReferenceInitList(DestType, ILE);
3766 return;
3767 }
3768
Sebastian Redled2e5322011-12-22 14:44:04 +00003769 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3770 assert(DestRecordType && "Constructor initialization requires record type");
3771 CXXRecordDecl *DestRecordDecl
3772 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3773
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003774 // Build the candidate set directly in the initialization sequence
3775 // structure, so that it will persist if we fail.
3776 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3777
3778 // Determine whether we are allowed to call explicit constructors or
3779 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003780 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003781 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003782
Sebastian Redled2e5322011-12-22 14:44:04 +00003783 // - Otherwise, if T is a class type, constructors are considered. The
3784 // applicable constructors are enumerated, and the best one is chosen
3785 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003786 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003787
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003788 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003789 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003790 bool AsInitializerList = false;
3791
Larisse Voufo19d08672015-01-27 18:47:05 +00003792 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003793 // When objects of non-aggregate type T are list-initialized, such that
3794 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3795 // according to the rules in this section, overload resolution selects
3796 // the constructor in two phases:
3797 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003798 // - Initially, the candidate functions are the initializer-list
3799 // constructors of the class T and the argument list consists of the
3800 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003801 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003802 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003803
3804 // If the initializer list has no elements and T has a default constructor,
3805 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003806 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003807 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003808 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003809 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003810 /*OnlyListConstructor=*/true,
3811 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003812 }
3813
3814 // C++11 [over.match.list]p1:
3815 // - If no viable initializer-list constructor is found, overload resolution
3816 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003817 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003818 // elements of the initializer list.
3819 if (Result == OR_No_Viable_Function) {
3820 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003821 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003822 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003823 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003824 /*OnlyListConstructors=*/false,
3825 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003826 }
3827 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003828 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003829 InitializationSequence::FK_ListConstructorOverloadFailed :
3830 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003831 Result);
3832 return;
3833 }
3834
Richard Smith67ef14f2017-09-26 18:37:55 +00003835 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3836
3837 // In C++17, ResolveConstructorOverload can select a conversion function
3838 // instead of a constructor.
3839 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3840 // Add the user-defined conversion step that calls the conversion function.
3841 QualType ConvType = CD->getConversionType();
3842 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3843 "should not have selected this conversion function");
3844 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3845 HadMultipleCandidates);
3846 if (!S.Context.hasSameType(ConvType, DestType))
3847 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3848 if (IsListInit)
3849 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3850 return;
3851 }
3852
Richard Smithd86812d2012-07-05 08:39:21 +00003853 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003854 // If a program calls for the default initialization of an object
3855 // of a const-qualified type T, T shall be a class type with a
3856 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003857 // C++ core issue 253 proposal:
3858 // If the implicit default constructor initializes all subobjects, no
3859 // initializer should be required.
3860 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3861 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003862 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003863 Entity.getType().isConstQualified()) {
3864 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3865 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3866 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3867 return;
3868 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003869 }
3870
Sebastian Redl048a6d72012-04-01 19:54:59 +00003871 // C++11 [over.match.list]p1:
3872 // In copy-list-initialization, if an explicit constructor is chosen, the
3873 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003874 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003875 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3876 return;
3877 }
3878
Sebastian Redled2e5322011-12-22 14:44:04 +00003879 // Add the constructor initialization step. Any cv-qualification conversion is
3880 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00003881 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003882 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003883 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003884}
3885
Sebastian Redl29526f02011-11-27 16:50:07 +00003886static bool
3887ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3888 Expr *Initializer,
3889 QualType &SourceType,
3890 QualType &UnqualifiedSourceType,
3891 QualType UnqualifiedTargetType,
3892 InitializationSequence &Sequence) {
3893 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3894 S.Context.OverloadTy) {
3895 DeclAccessPair Found;
3896 bool HadMultipleCandidates = false;
3897 if (FunctionDecl *Fn
3898 = S.ResolveAddressOfOverloadedFunction(Initializer,
3899 UnqualifiedTargetType,
3900 false, Found,
3901 &HadMultipleCandidates)) {
3902 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3903 HadMultipleCandidates);
3904 SourceType = Fn->getType();
3905 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3906 } else if (!UnqualifiedTargetType->isRecordType()) {
3907 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3908 return true;
3909 }
3910 }
3911 return false;
3912}
3913
3914static void TryReferenceInitializationCore(Sema &S,
3915 const InitializedEntity &Entity,
3916 const InitializationKind &Kind,
3917 Expr *Initializer,
3918 QualType cv1T1, QualType T1,
3919 Qualifiers T1Quals,
3920 QualType cv2T2, QualType T2,
3921 Qualifiers T2Quals,
3922 InitializationSequence &Sequence);
3923
Richard Smithd86812d2012-07-05 08:39:21 +00003924static void TryValueInitialization(Sema &S,
3925 const InitializedEntity &Entity,
3926 const InitializationKind &Kind,
3927 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003928 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003929
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003930/// Attempt list initialization of a reference.
Sebastian Redl29526f02011-11-27 16:50:07 +00003931static void TryReferenceListInitialization(Sema &S,
3932 const InitializedEntity &Entity,
3933 const InitializationKind &Kind,
3934 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003935 InitializationSequence &Sequence,
3936 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003937 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003938 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003939 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3940 return;
3941 }
David Majnemer9370dc22015-04-26 07:35:03 +00003942 // Can't reference initialize a compound literal.
3943 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3944 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3945 return;
3946 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003947
3948 QualType DestType = Entity.getType();
3949 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3950 Qualifiers T1Quals;
3951 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3952
3953 // Reference initialization via an initializer list works thus:
3954 // If the initializer list consists of a single element that is
3955 // reference-related to the referenced type, bind directly to that element
3956 // (possibly creating temporaries).
3957 // Otherwise, initialize a temporary with the initializer list and
3958 // bind to that.
3959 if (InitList->getNumInits() == 1) {
3960 Expr *Initializer = InitList->getInit(0);
3961 QualType cv2T2 = Initializer->getType();
3962 Qualifiers T2Quals;
3963 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3964
3965 // If this fails, creating a temporary wouldn't work either.
3966 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3967 T1, Sequence))
3968 return;
3969
3970 SourceLocation DeclLoc = Initializer->getLocStart();
3971 bool dummy1, dummy2, dummy3;
3972 Sema::ReferenceCompareResult RefRelationship
3973 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3974 dummy2, dummy3);
3975 if (RefRelationship >= Sema::Ref_Related) {
3976 // Try to bind the reference here.
3977 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3978 T1Quals, cv2T2, T2, T2Quals, Sequence);
3979 if (Sequence)
3980 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3981 return;
3982 }
Richard Smith03d93932013-01-15 07:58:29 +00003983
3984 // Update the initializer if we've resolved an overloaded function.
3985 if (Sequence.step_begin() != Sequence.step_end())
3986 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003987 }
3988
3989 // Not reference-related. Create a temporary and bind to that.
3990 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3991
Manman Ren073db022016-03-10 18:53:19 +00003992 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3993 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00003994 if (Sequence) {
3995 if (DestType->isRValueReferenceType() ||
3996 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3997 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3998 else
3999 Sequence.SetFailed(
4000 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4001 }
4002}
4003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004004/// Attempt list initialization (C++0x [dcl.init.list])
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004005static void TryListInitialization(Sema &S,
4006 const InitializedEntity &Entity,
4007 const InitializationKind &Kind,
4008 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004009 InitializationSequence &Sequence,
4010 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004011 QualType DestType = Entity.getType();
4012
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004013 // C++ doesn't allow scalar initialization with more than one argument.
4014 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004015 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004016 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4017 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4018 return;
4019 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004020 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004021 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4022 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004023 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004024 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004025
Larisse Voufod2010992015-01-24 23:09:54 +00004026 if (DestType->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004027 !S.isCompleteType(InitList->getLocStart(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004028 Sequence.setIncompleteTypeFailure(DestType);
4029 return;
4030 }
Richard Smithd86812d2012-07-05 08:39:21 +00004031
Larisse Voufo19d08672015-01-27 18:47:05 +00004032 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004033 // - If T is a class type and the initializer list has a single element of
4034 // type cv U, where U is T or a class derived from T, the object is
4035 // initialized from that element (by copy-initialization for
4036 // copy-list-initialization, or by direct-initialization for
4037 // direct-list-initialization).
4038 // - Otherwise, if T is a character array and the initializer list has a
4039 // single element that is an appropriately-typed string literal
4040 // (8.5.2 [dcl.init.string]), initialization is performed as described
4041 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004042 // - Otherwise, if T is an aggregate, [...] (continue below).
4043 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004044 if (DestType->isRecordType()) {
4045 QualType InitType = InitList->getInit(0)->getType();
4046 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004047 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004048 Expr *InitListAsExpr = InitList;
4049 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004050 DestType, Sequence,
4051 /*InitListSyntax*/false,
4052 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004053 return;
4054 }
4055 }
4056 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4057 Expr *SubInit[1] = {InitList->getInit(0)};
4058 if (!isa<VariableArrayType>(DestAT) &&
4059 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4060 InitializationKind SubKind =
4061 Kind.getKind() == InitializationKind::IK_DirectList
4062 ? InitializationKind::CreateDirect(Kind.getLocation(),
4063 InitList->getLBraceLoc(),
4064 InitList->getRBraceLoc())
4065 : Kind;
4066 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004067 /*TopLevelOfInitList*/ true,
4068 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004069
4070 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4071 // the element is not an appropriately-typed string literal, in which
4072 // case we should proceed as in C++11 (below).
4073 if (Sequence) {
4074 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4075 return;
4076 }
4077 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004078 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004079 }
Larisse Voufod2010992015-01-24 23:09:54 +00004080
4081 // C++11 [dcl.init.list]p3:
4082 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004083 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4084 (S.getLangOpts().CPlusPlus11 &&
4085 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004086 if (S.getLangOpts().CPlusPlus11) {
4087 // - Otherwise, if the initializer list has no elements and T is a
4088 // class type with a default constructor, the object is
4089 // value-initialized.
4090 if (InitList->getNumInits() == 0) {
4091 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4092 if (RD->hasDefaultConstructor()) {
4093 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4094 return;
4095 }
4096 }
4097
4098 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4099 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004100 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4101 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004102 return;
4103
4104 // - Otherwise, if T is a class type, constructors are considered.
4105 Expr *InitListAsExpr = InitList;
4106 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004107 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004108 } else
4109 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4110 return;
4111 }
4112
Richard Smith089c3162013-09-21 21:55:46 +00004113 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004114 InitList->getNumInits() == 1) {
4115 Expr *E = InitList->getInit(0);
4116
4117 // - Otherwise, if T is an enumeration with a fixed underlying type,
4118 // the initializer-list has a single element v, and the initialization
4119 // is direct-list-initialization, the object is initialized with the
4120 // value T(v); if a narrowing conversion is required to convert v to
4121 // the underlying type of T, the program is ill-formed.
4122 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004123 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004124 Kind.getKind() == InitializationKind::IK_DirectList &&
4125 ET && ET->getDecl()->isFixed() &&
4126 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4127 (E->getType()->isIntegralOrEnumerationType() ||
4128 E->getType()->isFloatingType())) {
4129 // There are two ways that T(v) can work when T is an enumeration type.
4130 // If there is either an implicit conversion sequence from v to T or
4131 // a conversion function that can convert from v to T, then we use that.
4132 // Otherwise, if v is of integral, enumeration, or floating-point type,
4133 // it is converted to the enumeration type via its underlying type.
4134 // There is no overlap possible between these two cases (except when the
4135 // source value is already of the destination type), and the first
4136 // case is handled by the general case for single-element lists below.
4137 ImplicitConversionSequence ICS;
4138 ICS.setStandard();
4139 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004140 if (!E->isRValue())
4141 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004142 // If E is of a floating-point type, then the conversion is ill-formed
4143 // due to narrowing, but go through the motions in order to produce the
4144 // right diagnostic.
4145 ICS.Standard.Second = E->getType()->isFloatingType()
4146 ? ICK_Floating_Integral
4147 : ICK_Integral_Conversion;
4148 ICS.Standard.setFromType(E->getType());
4149 ICS.Standard.setToType(0, E->getType());
4150 ICS.Standard.setToType(1, DestType);
4151 ICS.Standard.setToType(2, DestType);
4152 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4153 /*TopLevelOfInitList*/true);
4154 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4155 return;
4156 }
4157
Richard Smith089c3162013-09-21 21:55:46 +00004158 // - Otherwise, if the initializer list has a single element of type E
4159 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004160 // initialized from that element (by copy-initialization for
4161 // copy-list-initialization, or by direct-initialization for
4162 // direct-list-initialization); if a narrowing conversion is required
4163 // to convert the element to T, the program is ill-formed.
4164 //
Richard Smith089c3162013-09-21 21:55:46 +00004165 // Per core-24034, this is direct-initialization if we were performing
4166 // direct-list-initialization and copy-initialization otherwise.
4167 // We can't use InitListChecker for this, because it always performs
4168 // copy-initialization. This only matters if we might use an 'explicit'
4169 // conversion operator, so we only need to handle the cases where the source
4170 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004171 if (InitList->getInit(0)->getType()->isRecordType()) {
4172 InitializationKind SubKind =
4173 Kind.getKind() == InitializationKind::IK_DirectList
4174 ? InitializationKind::CreateDirect(Kind.getLocation(),
4175 InitList->getLBraceLoc(),
4176 InitList->getRBraceLoc())
4177 : Kind;
4178 Expr *SubInit[1] = { InitList->getInit(0) };
4179 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4180 /*TopLevelOfInitList*/true,
4181 TreatUnavailableAsInvalid);
4182 if (Sequence)
4183 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4184 return;
4185 }
Richard Smith089c3162013-09-21 21:55:46 +00004186 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004187
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004188 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004189 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004190 if (CheckInitList.HadError()) {
4191 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4192 return;
4193 }
4194
4195 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004196 Sequence.AddListInitializationStep(DestType);
4197}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004198
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004199/// Try a reference initialization that involves calling a conversion
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004200/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004201static OverloadingResult TryRefInitWithConversionFunction(
4202 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4203 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4204 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004205 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004206 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4207 QualType T1 = cv1T1.getUnqualifiedType();
4208 QualType cv2T2 = Initializer->getType();
4209 QualType T2 = cv2T2.getUnqualifiedType();
4210
4211 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004212 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004213 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004215 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004216 ObjCConversion,
4217 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004218 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004219 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004220 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004221 (void)ObjCLifetimeConversion;
4222
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004223 // Build the candidate set directly in the initialization sequence
4224 // structure, so that it will persist if we fail.
4225 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004226 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004227
Richard Smithb368ea82018-07-02 23:25:22 +00004228 // Determine whether we are allowed to call explicit conversion operators.
4229 // Note that none of [over.match.copy], [over.match.conv], nor
4230 // [over.match.ref] permit an explicit constructor to be chosen when
4231 // initializing a reference, not even for direct-initialization.
4232 bool AllowExplicitCtors = false;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004233 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4234
Craig Topperc3ec1492014-05-26 06:22:03 +00004235 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004236 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004237 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004238 // The type we're converting to is a class type. Enumerate its constructors
4239 // to see if there is a suitable conversion.
4240 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004241
Richard Smith40c78062015-02-21 02:31:57 +00004242 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004243 auto Info = getConstructorInfo(D);
4244 if (!Info.Constructor)
4245 continue;
John McCalla0296f72010-03-19 07:35:19 +00004246
Richard Smithc2bebe92016-05-11 20:37:46 +00004247 if (!Info.Constructor->isInvalidDecl() &&
Richard Smithb368ea82018-07-02 23:25:22 +00004248 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004249 if (Info.ConstructorTmpl)
4250 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004251 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004252 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004253 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004254 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004255 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004256 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004257 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004260 }
John McCall3696dcb2010-08-17 07:23:57 +00004261 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4262 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
Craig Topperc3ec1492014-05-26 06:22:03 +00004264 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004265 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004266 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004267 // The type we're converting from is a class type, enumerate its conversion
4268 // functions.
4269 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4270
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004271 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4272 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273 NamedDecl *D = *I;
4274 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4275 if (isa<UsingShadowDecl>(D))
4276 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004278 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4279 CXXConversionDecl *Conv;
4280 if (ConvTemplate)
4281 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4282 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004283 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 // If the conversion function doesn't return a reference type,
4286 // it can't be considered for this conversion unless we're allowed to
4287 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288 // FIXME: Do we need to make sure that we only consider conversion
4289 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004290 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004291 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004292 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4293 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004294 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004295 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004296 DestType, CandidateSet,
4297 /*AllowObjCConversionOnExplicit=*/
4298 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004299 else
John McCalla0296f72010-03-19 07:35:19 +00004300 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004301 Initializer, DestType, CandidateSet,
4302 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004303 }
4304 }
4305 }
John McCall3696dcb2010-08-17 07:23:57 +00004306 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4307 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004309 SourceLocation DeclLoc = Initializer->getLocStart();
4310
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004312 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004314 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004315 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004316
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004317 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004318 // This is the overload that will be used for this initialization step if we
4319 // use this initialization. Mark it as referenced.
4320 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004321
Richard Smithb8c0f552016-12-09 18:49:13 +00004322 // Compute the returned type and value kind of the conversion.
4323 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004324 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004325 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004326 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004327 cv3T3 = T1;
4328
4329 ExprValueKind VK = VK_RValue;
4330 if (cv3T3->isLValueReferenceType())
4331 VK = VK_LValue;
4332 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4333 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4334 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004335
4336 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004337 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004338 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004339 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004340
Richard Smithb8c0f552016-12-09 18:49:13 +00004341 // Determine whether we'll need to perform derived-to-base adjustments or
4342 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004343 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004344 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004345 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004346 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004347 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004348 NewDerivedToBase, NewObjCConversion,
4349 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004350
4351 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004352 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004353 assert(!isa<CXXConstructorDecl>(Function) &&
4354 "should not have conversion after constructor");
4355
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004356 ImplicitConversionSequence ICS;
4357 ICS.setStandard();
4358 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004359 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4360
4361 // Every implicit conversion results in a prvalue, except for a glvalue
4362 // derived-to-base conversion, which we handle below.
4363 cv3T3 = ICS.Standard.getToType(2);
4364 VK = VK_RValue;
4365 }
4366
4367 // If the converted initializer is a prvalue, its type T4 is adjusted to
4368 // type "cv1 T4" and the temporary materialization conversion is applied.
4369 //
4370 // We adjust the cv-qualifications to match the reference regardless of
4371 // whether we have a prvalue so that the AST records the change. In this
4372 // case, T4 is "cv3 T3".
4373 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4374 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4375 Sequence.AddQualificationConversionStep(cv1T4, VK);
4376 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4377 VK = IsLValueRef ? VK_LValue : VK_XValue;
4378
4379 if (NewDerivedToBase)
4380 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004381 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004382 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004383
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004384 return OR_Success;
4385}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004386
Richard Smithc620f552011-10-19 16:55:56 +00004387static void CheckCXX98CompatAccessibleCopy(Sema &S,
4388 const InitializedEntity &Entity,
4389 Expr *CurInitExpr);
4390
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004391/// Attempt reference initialization (C++0x [dcl.init.ref])
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004393 const InitializedEntity &Entity,
4394 const InitializationKind &Kind,
4395 Expr *Initializer,
4396 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004397 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004398 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004399 Qualifiers T1Quals;
4400 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004401 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004402 Qualifiers T2Quals;
4403 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004404
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004405 // If the initializer is the address of an overloaded function, try
4406 // to resolve the overloaded function. If all goes well, T2 is the
4407 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004408 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4409 T1, Sequence))
4410 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004411
Sebastian Redl29526f02011-11-27 16:50:07 +00004412 // Delegate everything else to a subfunction.
4413 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4414 T1Quals, cv2T2, T2, T2Quals, Sequence);
4415}
4416
Richard Smithb8c0f552016-12-09 18:49:13 +00004417/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004418/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004419/// such a glvalue will always create a temporary.
4420static bool isNonReferenceableGLValue(Expr *E) {
4421 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004422}
4423
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004424/// Reference initialization without resolving overloaded functions.
Sebastian Redl29526f02011-11-27 16:50:07 +00004425static void TryReferenceInitializationCore(Sema &S,
4426 const InitializedEntity &Entity,
4427 const InitializationKind &Kind,
4428 Expr *Initializer,
4429 QualType cv1T1, QualType T1,
4430 Qualifiers T1Quals,
4431 QualType cv2T2, QualType T2,
4432 Qualifiers T2Quals,
4433 InitializationSequence &Sequence) {
4434 QualType DestType = Entity.getType();
4435 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004436 // Compute some basic properties of the types and the initializer.
4437 bool isLValueRef = DestType->isLValueReferenceType();
4438 bool isRValueRef = !isLValueRef;
4439 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004440 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004441 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004442 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004443 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004444 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004445 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004446
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004447 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004449 // "cv2 T2" as follows:
4450 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004452 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004453 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004454 // there are no function rvalues in C++, rvalue refs to functions are treated
4455 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004456 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004457 bool T1Function = T1->isFunctionType();
4458 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004459 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004460 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004461 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004462 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004464 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004465 if (T1Quals != T2Quals)
4466 // Convert to cv1 T2. This should only add qualifiers unless this is a
4467 // c-style cast. The removal of qualifiers in that case notionally
4468 // happens after the reference binding, but that doesn't matter.
4469 Sequence.AddQualificationConversionStep(
4470 S.Context.getQualifiedType(T2, T1Quals),
4471 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004472 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004473 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004474 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004475 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004476
Richard Smithb8c0f552016-12-09 18:49:13 +00004477 // We only create a temporary here when binding a reference to a
4478 // bit-field or vector element. Those cases are't supposed to be
4479 // handled by this bullet, but the outcome is the same either way.
4480 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004481 return;
4482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004483
4484 // - has a class type (i.e., T2 is a class type), where T1 is not
4485 // reference-related to T2, and can be implicitly converted to an
4486 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4487 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004488 // applicable conversion functions (13.3.1.6) and choosing the best
4489 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004490 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004491 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004492 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4493 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004494 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004495 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4496 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004497 if (ConvOvlResult == OR_Success)
4498 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004499 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004500 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004501 InitializationSequence::FK_ReferenceInitOverloadFailed,
4502 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004503 }
4504 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004505
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004507 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004508 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004509 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004510 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4511 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4512 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004513 Sequence.SetOverloadFailure(
4514 InitializationSequence::FK_ReferenceInitOverloadFailed,
4515 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004516 else if (!InitCategory.isLValue())
4517 Sequence.SetFailed(
4518 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4519 else {
4520 InitializationSequence::FailureKind FK;
4521 switch (RefRelationship) {
4522 case Sema::Ref_Compatible:
4523 if (Initializer->refersToBitField())
4524 FK = InitializationSequence::
4525 FK_NonConstLValueReferenceBindingToBitfield;
4526 else if (Initializer->refersToVectorElement())
4527 FK = InitializationSequence::
4528 FK_NonConstLValueReferenceBindingToVectorElement;
4529 else
4530 llvm_unreachable("unexpected kind of compatible initializer");
4531 break;
4532 case Sema::Ref_Related:
4533 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4534 break;
4535 case Sema::Ref_Incompatible:
4536 FK = InitializationSequence::
4537 FK_NonConstLValueReferenceBindingToUnrelated;
4538 break;
4539 }
4540 Sequence.SetFailed(FK);
4541 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004542 return;
4543 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004544
Douglas Gregor92e460e2011-01-20 16:44:54 +00004545 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004546 // - is an
4547 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4548 // [1z] rvalue (but not a bit-field) or
4549 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4550 //
4551 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004552 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004553 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004555 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004556 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004557 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004558 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004559 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004560 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004561 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004562 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4563 // compiler the freedom to perform a copy here or bind to the
4564 // object, while C++0x requires that we bind directly to the
4565 // object. Hence, we always bind to the object without making an
4566 // extra copy. However, in C++03 requires that we check for the
4567 // presence of a suitable copy constructor:
4568 //
4569 // The constructor that would be used to make the copy shall
4570 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004571 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004572 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004573 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004574 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576
Richard Smithb8c0f552016-12-09 18:49:13 +00004577 // C++1z [dcl.init.ref]/5.2.1.2:
4578 // If the converted initializer is a prvalue, its type T4 is adjusted
4579 // to type "cv1 T4" and the temporary materialization conversion is
4580 // applied.
4581 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4582 if (T1Quals != T2Quals)
4583 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4584 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4585 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4586
4587 // In any case, the reference is bound to the resulting glvalue (or to
4588 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004589 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004590 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004591 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004592 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595
4596 // - has a class type (i.e., T2 is a class type), where T1 is not
4597 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004598 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4599 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004600 //
4601 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004602 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004603 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004604 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004605 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4606 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004607 if (ConvOvlResult)
4608 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004609 InitializationSequence::FK_ReferenceInitOverloadFailed,
4610 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004612 return;
4613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614
Richard Smithce766292016-10-21 23:01:55 +00004615 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004616 isRValueRef && InitCategory.isLValue()) {
4617 Sequence.SetFailed(
4618 InitializationSequence::FK_RValueReferenceBindingToLValue);
4619 return;
4620 }
4621
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004622 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4623 return;
4624 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004625
4626 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004627 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004628 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004629 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004630
John McCallec6f4e92010-06-04 02:29:22 +00004631 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4632
Richard Smith2eabf782013-06-13 00:57:57 +00004633 // FIXME: Why do we use an implicit conversion here rather than trying
4634 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004635 ImplicitConversionSequence ICS
4636 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004637 /*SuppressUserConversions=*/false,
4638 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004639 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004640 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4641 /*AllowObjCWritebackConversion=*/false);
4642
4643 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004644 // FIXME: Use the conversion function set stored in ICS to turn
4645 // this into an overloading ambiguity diagnostic. However, we need
4646 // to keep that set as an OverloadCandidateSet rather than as some
4647 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004648 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4649 Sequence.SetOverloadFailure(
4650 InitializationSequence::FK_ReferenceInitOverloadFailed,
4651 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004652 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4653 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004654 else
4655 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004656 return;
John McCall31168b02011-06-15 23:02:42 +00004657 } else {
4658 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004659 }
4660
4661 // [...] If T1 is reference-related to T2, cv1 must be the
4662 // same cv-qualification as, or greater cv-qualification
4663 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004664 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4665 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004666 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004667 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004668 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4669 return;
4670 }
4671
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004672 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004673 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004675 InitCategory.isLValue()) {
4676 Sequence.SetFailed(
4677 InitializationSequence::FK_RValueReferenceBindingToLValue);
4678 return;
4679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004681 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004682}
4683
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004684/// Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004685/// (C++ [dcl.init.string], C99 6.7.8).
4686static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004687 const InitializedEntity &Entity,
4688 const InitializationKind &Kind,
4689 Expr *Initializer,
4690 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004691 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004692}
4693
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004694/// Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004696 const InitializedEntity &Entity,
4697 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004698 InitializationSequence &Sequence,
4699 InitListExpr *InitList) {
4700 assert((!InitList || InitList->getNumInits() == 0) &&
4701 "Shouldn't use value-init for non-empty init lists");
4702
Richard Smith1bfe0682012-02-14 21:14:13 +00004703 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004704 //
4705 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004706 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004708 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004709 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004711 if (const RecordType *RT = T->getAs<RecordType>()) {
4712 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004713 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004714 // C++98:
4715 // -- if T is a class type (clause 9) with a user-declared constructor
4716 // (12.1), then the default constructor for T is called (and the
4717 // initialization is ill-formed if T has no accessible default
4718 // constructor);
4719 // C++11:
4720 // -- if T is a class type (clause 9) with either no default constructor
4721 // (12.1 [class.ctor]) or a default constructor that is user-provided
4722 // or deleted, then the object is default-initialized;
4723 //
4724 // Note that the C++11 rule is the same as the C++98 rule if there are no
4725 // defaulted or deleted constructors, so we just use it unconditionally.
4726 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4727 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4728 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729
Richard Smith1bfe0682012-02-14 21:14:13 +00004730 // -- if T is a (possibly cv-qualified) non-union class type without a
4731 // user-provided or deleted default constructor, then the object is
4732 // zero-initialized and, if T has a non-trivial default constructor,
4733 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004734 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4735 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004736 if (NeedZeroInitialization)
4737 Sequence.AddZeroInitializationStep(Entity.getType());
4738
Richard Smith593f9932012-12-08 02:01:17 +00004739 // C++03:
4740 // -- if T is a non-union class type without a user-declared constructor,
4741 // then every non-static data member and base class component of T is
4742 // value-initialized;
4743 // [...] A program that calls for [...] value-initialization of an
4744 // entity of reference type is ill-formed.
4745 //
4746 // C++11 doesn't need this handling, because value-initialization does not
4747 // occur recursively there, and the implicit default constructor is
4748 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004749 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004750 ClassDecl->hasUninitializedReferenceMember()) {
4751 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4752 return;
4753 }
4754
Richard Smithd86812d2012-07-05 08:39:21 +00004755 // If this is list-value-initialization, pass the empty init list on when
4756 // building the constructor call. This affects the semantics of a few
4757 // things (such as whether an explicit default constructor can be called).
4758 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004759 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004760 bool InitListSyntax = InitList;
4761
Richard Smith81f5ade2016-12-15 02:28:18 +00004762 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004763 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4764 return TryConstructorInitialization(
4765 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004766 }
4767 }
4768
Douglas Gregor1b303932009-12-22 15:35:07 +00004769 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004770}
4771
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004772/// Attempt default initialization (C++ [dcl.init]p6).
Douglas Gregor85dabae2009-12-16 01:38:02 +00004773static void TryDefaultInitialization(Sema &S,
4774 const InitializedEntity &Entity,
4775 const InitializationKind &Kind,
4776 InitializationSequence &Sequence) {
4777 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
Douglas Gregor85dabae2009-12-16 01:38:02 +00004779 // C++ [dcl.init]p6:
4780 // To default-initialize an object of type T means:
4781 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004782 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4783
Douglas Gregor85dabae2009-12-16 01:38:02 +00004784 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4785 // constructor for T is called (and the initialization is ill-formed if
4786 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004787 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004788 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4789 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004790 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004792
Douglas Gregor85dabae2009-12-16 01:38:02 +00004793 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794
Douglas Gregor85dabae2009-12-16 01:38:02 +00004795 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004797 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004798 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004799 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4800 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004801 return;
4802 }
4803
4804 // If the destination type has a lifetime property, zero-initialize it.
4805 if (DestType.getQualifiers().hasObjCLifetime()) {
4806 Sequence.AddZeroInitializationStep(Entity.getType());
4807 return;
4808 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004809}
4810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004811/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004812/// which enumerates all conversion functions and performs overload resolution
4813/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004815 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004816 const InitializationKind &Kind,
4817 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004818 InitializationSequence &Sequence,
4819 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004820 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4821 QualType SourceType = Initializer->getType();
4822 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4823 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824
Douglas Gregor540c3b02009-12-14 17:27:33 +00004825 // Build the candidate set directly in the initialization sequence
4826 // structure, so that it will persist if we fail.
4827 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004828 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829
Douglas Gregor540c3b02009-12-14 17:27:33 +00004830 // Determine whether we are allowed to call explicit constructors or
4831 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004832 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833
Douglas Gregor540c3b02009-12-14 17:27:33 +00004834 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4835 // The type we're converting to is a class type. Enumerate its constructors
4836 // to see if there is a suitable conversion.
4837 CXXRecordDecl *DestRecordDecl
4838 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839
Douglas Gregord9848152010-04-26 14:36:57 +00004840 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004841 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004842 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004843 auto Info = getConstructorInfo(D);
4844 if (!Info.Constructor)
4845 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004846
Richard Smithc2bebe92016-05-11 20:37:46 +00004847 if (!Info.Constructor->isInvalidDecl() &&
4848 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4849 if (Info.ConstructorTmpl)
4850 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004851 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004852 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004853 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004854 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004855 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004856 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004857 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859 }
Douglas Gregord9848152010-04-26 14:36:57 +00004860 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004861 }
Eli Friedman78275202009-12-19 08:11:05 +00004862
4863 SourceLocation DeclLoc = Initializer->getLocStart();
4864
Douglas Gregor540c3b02009-12-14 17:27:33 +00004865 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4866 // The type we're converting from is a class type, enumerate its conversion
4867 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004868
Eli Friedman4afe9a32009-12-20 22:12:03 +00004869 // We can only enumerate the conversion functions for a complete type; if
4870 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004871 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004872 CXXRecordDecl *SourceRecordDecl
4873 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004874
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004875 const auto &Conversions =
4876 SourceRecordDecl->getVisibleConversionFunctions();
4877 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004878 NamedDecl *D = *I;
4879 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4880 if (isa<UsingShadowDecl>(D))
4881 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004882
Eli Friedman4afe9a32009-12-20 22:12:03 +00004883 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4884 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004885 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004886 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004887 else
John McCallda4458e2010-03-31 01:36:47 +00004888 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889
Eli Friedman4afe9a32009-12-20 22:12:03 +00004890 if (AllowExplicit || !Conv->isExplicit()) {
4891 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004892 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004893 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004894 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004895 else
John McCalla0296f72010-03-19 07:35:19 +00004896 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004897 Initializer, DestType, CandidateSet,
4898 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004899 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004900 }
4901 }
4902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903
4904 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004905 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004906 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004907 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004908 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004909 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004910 Result);
4911 return;
4912 }
John McCall0d1da222010-01-12 00:44:57 +00004913
Douglas Gregor540c3b02009-12-14 17:27:33 +00004914 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004915 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004916 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917
Douglas Gregor540c3b02009-12-14 17:27:33 +00004918 if (isa<CXXConstructorDecl>(Function)) {
4919 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004920 // subsumed by the initialization. Per DR5, the created temporary is of the
4921 // cv-unqualified type of the destination.
4922 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4923 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004924 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00004925
4926 // C++14 and before:
4927 // - if the function is a constructor, the call initializes a temporary
4928 // of the cv-unqualified version of the destination type. The [...]
4929 // temporary [...] is then used to direct-initialize, according to the
4930 // rules above, the object that is the destination of the
4931 // copy-initialization.
4932 // Note that this just performs a simple object copy from the temporary.
4933 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004934 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00004935 // - if the function is a constructor, the call is a prvalue of the
4936 // cv-unqualified version of the destination type whose return object
4937 // is initialized by the constructor. The call is used to
4938 // direct-initialize, according to the rules above, the object that
4939 // is the destination of the copy-initialization.
4940 // Therefore we need to do nothing further.
4941 //
4942 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004943 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00004944 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004945 else if (DestType.hasQualifiers())
4946 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004947 return;
4948 }
4949
4950 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004951 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004952 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4953 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004954
Richard Smithb8c0f552016-12-09 18:49:13 +00004955 if (ConvType->getAs<RecordType>()) {
4956 // The call is used to direct-initialize [...] the object that is the
4957 // destination of the copy-initialization.
4958 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004959 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00004960 // - If the initializer expression is a prvalue and the cv-unqualified
4961 // version of the source type is the same as the class of the
4962 // destination [... do not make an extra copy]
4963 //
4964 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004965 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00004966 Function->getReturnType()->isReferenceType() ||
4967 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4968 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004969 else if (!S.Context.hasSameType(ConvType, DestType))
4970 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00004971 return;
4972 }
4973
Douglas Gregor5ab11652010-04-17 22:01:05 +00004974 // If the conversion following the call to the conversion function
4975 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004976 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4977 Best->FinalConversion.Third) {
4978 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004979 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004980 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004981 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004982 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004983}
4984
Richard Smithf032001b2013-06-20 02:18:31 +00004985/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4986/// a function with a pointer return type contains a 'return false;' statement.
4987/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4988/// code using that header.
4989///
4990/// Work around this by treating 'return false;' as zero-initializing the result
4991/// if it's used in a pointer-returning function in a system header.
4992static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4993 const InitializedEntity &Entity,
4994 const Expr *Init) {
4995 return S.getLangOpts().CPlusPlus11 &&
4996 Entity.getKind() == InitializedEntity::EK_Result &&
4997 Entity.getType()->isPointerType() &&
4998 isa<CXXBoolLiteralExpr>(Init) &&
4999 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5000 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5001}
5002
John McCall31168b02011-06-15 23:02:42 +00005003/// The non-zero enum values here are indexes into diagnostic alternatives.
5004enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5005
5006/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00005007static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005008 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00005009 // Skip parens.
5010 e = e->IgnoreParens();
5011
5012 // Skip address-of nodes.
5013 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5014 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005015 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5016 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005017
5018 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005019 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5020 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005021 case CK_Dependent:
5022 case CK_BitCast:
5023 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005024 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005025 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005026
5027 case CK_ArrayToPointerDecay:
5028 return IIK_nonscalar;
5029
5030 case CK_NullToPointer:
5031 return IIK_okay;
5032
5033 default:
5034 break;
5035 }
5036
5037 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005038 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005039 // set isWeakAccess to true, to mean that there will be an implicit
5040 // load which requires a cleanup.
5041 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5042 isWeakAccess = true;
5043
John McCall63f84442011-06-27 23:59:58 +00005044 if (!isAddressOf) return IIK_nonlocal;
5045
John McCall113bee02012-03-10 09:33:50 +00005046 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5047 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005048
5049 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005050
5051 // If we have a conditional operator, check both sides.
5052 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005053 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5054 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005055 return iik;
5056
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005057 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005058
5059 // These are never scalar.
5060 } else if (isa<ArraySubscriptExpr>(e)) {
5061 return IIK_nonscalar;
5062
5063 // Otherwise, it needs to be a null pointer constant.
5064 } else {
5065 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5066 ? IIK_okay : IIK_nonlocal);
5067 }
5068
5069 return IIK_nonlocal;
5070}
5071
5072/// Check whether the given expression is a valid operand for an
5073/// indirect copy/restore.
5074static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5075 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005076 bool isWeakAccess = false;
5077 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5078 // If isWeakAccess to true, there will be an implicit
5079 // load which requires a cleanup.
5080 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005081 S.Cleanup.setExprNeedsCleanups(true);
5082
John McCall31168b02011-06-15 23:02:42 +00005083 if (iik == IIK_okay) return;
5084
5085 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5086 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5087 << src->getSourceRange();
5088}
5089
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005090/// Determine whether we have compatible array types for the
Douglas Gregore2f943b2011-02-22 18:29:51 +00005091/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005092static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005093 const ArrayType *Source) {
5094 // If the source and destination array types are equivalent, we're
5095 // done.
5096 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5097 return true;
5098
5099 // Make sure that the element types are the same.
5100 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5101 return false;
5102
5103 // The only mismatch we allow is when the destination is an
5104 // incomplete array type and the source is a constant array type.
5105 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5106}
5107
John McCall31168b02011-06-15 23:02:42 +00005108static bool tryObjCWritebackConversion(Sema &S,
5109 InitializationSequence &Sequence,
5110 const InitializedEntity &Entity,
5111 Expr *Initializer) {
5112 bool ArrayDecay = false;
5113 QualType ArgType = Initializer->getType();
5114 QualType ArgPointee;
5115 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5116 ArrayDecay = true;
5117 ArgPointee = ArgArrayType->getElementType();
5118 ArgType = S.Context.getPointerType(ArgPointee);
5119 }
5120
5121 // Handle write-back conversion.
5122 QualType ConvertedArgType;
5123 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5124 ConvertedArgType))
5125 return false;
5126
5127 // We should copy unless we're passing to an argument explicitly
5128 // marked 'out'.
5129 bool ShouldCopy = true;
5130 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5131 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5132
5133 // Do we need an lvalue conversion?
5134 if (ArrayDecay || Initializer->isGLValue()) {
5135 ImplicitConversionSequence ICS;
5136 ICS.setStandard();
5137 ICS.Standard.setAsIdentityConversion();
5138
5139 QualType ResultType;
5140 if (ArrayDecay) {
5141 ICS.Standard.First = ICK_Array_To_Pointer;
5142 ResultType = S.Context.getPointerType(ArgPointee);
5143 } else {
5144 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5145 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5146 }
5147
5148 Sequence.AddConversionSequenceStep(ICS, ResultType);
5149 }
5150
5151 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5152 return true;
5153}
5154
Guy Benyei61054192013-02-07 10:55:47 +00005155static bool TryOCLSamplerInitialization(Sema &S,
5156 InitializationSequence &Sequence,
5157 QualType DestType,
5158 Expr *Initializer) {
5159 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005160 (!Initializer->isIntegerConstantExpr(S.Context) &&
5161 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005162 return false;
5163
5164 Sequence.AddOCLSamplerInitStep(DestType);
5165 return true;
5166}
5167
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005168//
5169// OpenCL 1.2 spec, s6.12.10
5170//
5171// The event argument can also be used to associate the
5172// async_work_group_copy with a previous async copy allowing
5173// an event to be shared by multiple async copies; otherwise
5174// event should be zero.
5175//
5176static bool TryOCLZeroEventInitialization(Sema &S,
5177 InitializationSequence &Sequence,
5178 QualType DestType,
5179 Expr *Initializer) {
5180 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5181 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5182 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5183 return false;
5184
5185 Sequence.AddOCLZeroEventStep(DestType);
5186 return true;
5187}
5188
Egor Churaev89831422016-12-23 14:55:49 +00005189static bool TryOCLZeroQueueInitialization(Sema &S,
5190 InitializationSequence &Sequence,
5191 QualType DestType,
5192 Expr *Initializer) {
5193 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5194 !DestType->isQueueT() ||
5195 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5196 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5197 return false;
5198
5199 Sequence.AddOCLZeroQueueStep(DestType);
5200 return true;
5201}
5202
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005203InitializationSequence::InitializationSequence(Sema &S,
5204 const InitializedEntity &Entity,
5205 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005206 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005207 bool TopLevelOfInitList,
5208 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005209 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005210 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5211 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005212}
5213
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005214/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5215/// address of that function, this returns true. Otherwise, it returns false.
5216static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5217 auto *DRE = dyn_cast<DeclRefExpr>(E);
5218 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5219 return false;
5220
5221 return !S.checkAddressOfFunctionIsAvailable(
5222 cast<FunctionDecl>(DRE->getDecl()));
5223}
5224
Richard Smith410306b2016-12-12 02:53:20 +00005225/// Determine whether we can perform an elementwise array copy for this kind
5226/// of entity.
5227static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5228 switch (Entity.getKind()) {
5229 case InitializedEntity::EK_LambdaCapture:
5230 // C++ [expr.prim.lambda]p24:
5231 // For array members, the array elements are direct-initialized in
5232 // increasing subscript order.
5233 return true;
5234
5235 case InitializedEntity::EK_Variable:
5236 // C++ [dcl.decomp]p1:
5237 // [...] each element is copy-initialized or direct-initialized from the
5238 // corresponding element of the assignment-expression [...]
5239 return isa<DecompositionDecl>(Entity.getDecl());
5240
5241 case InitializedEntity::EK_Member:
5242 // C++ [class.copy.ctor]p14:
5243 // - if the member is an array, each element is direct-initialized with
5244 // the corresponding subobject of x
5245 return Entity.isImplicitMemberInitializer();
5246
5247 case InitializedEntity::EK_ArrayElement:
5248 // All the above cases are intended to apply recursively, even though none
5249 // of them actually say that.
5250 if (auto *E = Entity.getParent())
5251 return canPerformArrayCopy(*E);
5252 break;
5253
5254 default:
5255 break;
5256 }
5257
5258 return false;
5259}
5260
Richard Smith089c3162013-09-21 21:55:46 +00005261void InitializationSequence::InitializeFrom(Sema &S,
5262 const InitializedEntity &Entity,
5263 const InitializationKind &Kind,
5264 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005265 bool TopLevelOfInitList,
5266 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005267 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005268
John McCall5e77d762013-04-16 07:28:30 +00005269 // Eliminate non-overload placeholder types in the arguments. We
5270 // need to do this before checking whether types are dependent
5271 // because lowering a pseudo-object expression might well give us
5272 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005273 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005274 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5275 // FIXME: should we be doing this here?
5276 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5277 if (result.isInvalid()) {
5278 SetFailed(FK_PlaceholderType);
5279 return;
5280 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005281 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005282 }
5283
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005284 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005285 // The semantics of initializers are as follows. The destination type is
5286 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005287 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005288 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005289 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005290 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005291
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005292 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005293 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005294 SequenceKind = DependentSequence;
5295 return;
5296 }
5297
Sebastian Redld201edf2011-06-05 13:59:11 +00005298 // Almost everything is a normal sequence.
5299 setSequenceKind(NormalSequence);
5300
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005301 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005302 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005303 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005304 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005305 if (S.getLangOpts().ObjC1) {
5306 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5307 DestType, Initializer->getType(),
5308 Initializer) ||
5309 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5310 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005311 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005312 if (!isa<InitListExpr>(Initializer))
5313 SourceType = Initializer->getType();
5314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005315
Sebastian Redl0501c632012-02-12 16:37:36 +00005316 // - If the initializer is a (non-parenthesized) braced-init-list, the
5317 // object is list-initialized (8.5.4).
5318 if (Kind.getKind() != InitializationKind::IK_Direct) {
5319 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005320 TryListInitialization(S, Entity, Kind, InitList, *this,
5321 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005322 return;
5323 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005325
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005326 // - If the destination type is a reference type, see 8.5.3.
5327 if (DestType->isReferenceType()) {
5328 // C++0x [dcl.init.ref]p1:
5329 // A variable declared to be a T& or T&&, that is, "reference to type T"
5330 // (8.3.2), shall be initialized by an object, or function, of type T or
5331 // by an object that can be converted into a T.
5332 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005333 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005334 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005335 // C++17 [dcl.init.ref]p5:
5336 // A reference [...] is initialized by an expression [...] as follows:
5337 // If the initializer is not an expression, presumably we should reject,
5338 // but the standard fails to actually say so.
5339 else if (isa<InitListExpr>(Args[0]))
5340 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005341 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005342 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005343 return;
5344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005345
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005346 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005347 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005348 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005349 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005350 return;
5351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352
Douglas Gregor85dabae2009-12-16 01:38:02 +00005353 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005354 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005355 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005356 return;
5357 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005358
John McCall66884dd2011-02-21 07:22:22 +00005359 // - If the destination type is an array of characters, an array of
5360 // char16_t, an array of char32_t, or an array of wchar_t, and the
5361 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005362 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005363 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005364 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005365 if (Initializer && isa<VariableArrayType>(DestAT)) {
5366 SetFailed(FK_VariableLengthArrayHasInitializer);
5367 return;
5368 }
5369
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005370 if (Initializer) {
5371 switch (IsStringInit(Initializer, DestAT, Context)) {
5372 case SIF_None:
5373 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5374 return;
5375 case SIF_NarrowStringIntoWideChar:
5376 SetFailed(FK_NarrowStringIntoWideCharArray);
5377 return;
5378 case SIF_WideStringIntoChar:
5379 SetFailed(FK_WideStringIntoCharArray);
5380 return;
5381 case SIF_IncompatWideStringIntoWideChar:
5382 SetFailed(FK_IncompatWideStringIntoWideChar);
5383 return;
Richard Smith3a8244d2018-05-01 05:02:45 +00005384 case SIF_PlainStringIntoUTF8Char:
5385 SetFailed(FK_PlainStringIntoUTF8Char);
5386 return;
5387 case SIF_UTF8StringIntoPlainChar:
5388 SetFailed(FK_UTF8StringIntoPlainChar);
5389 return;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005390 case SIF_Other:
5391 break;
5392 }
John McCall66884dd2011-02-21 07:22:22 +00005393 }
5394
Richard Smith410306b2016-12-12 02:53:20 +00005395 // Some kinds of initialization permit an array to be initialized from
5396 // another array of the same type, and perform elementwise initialization.
5397 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5398 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5399 Entity.getType()) &&
5400 canPerformArrayCopy(Entity)) {
5401 // If source is a prvalue, use it directly.
5402 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005403 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005404 return;
5405 }
5406
5407 // Emit element-at-a-time copy loop.
5408 InitializedEntity Element =
5409 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5410 QualType InitEltT =
5411 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005412 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5413 Initializer->getValueKind(),
5414 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005415 Expr *OVEAsExpr = &OVE;
5416 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5417 TreatUnavailableAsInvalid);
5418 if (!Failed())
5419 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5420 return;
5421 }
5422
Douglas Gregore2f943b2011-02-22 18:29:51 +00005423 // Note: as an GNU C extension, we allow initialization of an
5424 // array from a compound literal that creates an array of the same
5425 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005426 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005427 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5428 Initializer->getType()->isArrayType()) {
5429 const ArrayType *SourceAT
5430 = Context.getAsArrayType(Initializer->getType());
5431 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005432 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005433 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005434 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005435 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005436 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005437 }
Richard Smithebeed412012-02-15 22:38:09 +00005438 }
Richard Smithd86812d2012-07-05 08:39:21 +00005439 // Note: as a GNU C++ extension, we allow list-initialization of a
5440 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005441 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005442 Entity.getKind() == InitializedEntity::EK_Member &&
5443 Initializer && isa<InitListExpr>(Initializer)) {
5444 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005445 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005446 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005447 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005448 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005449 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5450 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005451 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005452 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005453
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005454 return;
5455 }
Eli Friedman78275202009-12-19 08:11:05 +00005456
Larisse Voufod2010992015-01-24 23:09:54 +00005457 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005458 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005459 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005460 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005461
5462 // We're at the end of the line for C: it's either a write-back conversion
5463 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005464 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005465 // If allowed, check whether this is an Objective-C writeback conversion.
5466 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005467 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005468 return;
5469 }
Guy Benyei61054192013-02-07 10:55:47 +00005470
5471 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5472 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005473
5474 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5475 return;
5476
Egor Churaev89831422016-12-23 14:55:49 +00005477 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5478 return;
5479
John McCall31168b02011-06-15 23:02:42 +00005480 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005481 AddCAssignmentStep(DestType);
5482 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005483 return;
5484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005485
David Blaikiebbafb8a2012-03-11 07:00:24 +00005486 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005487
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005488 // - If the destination type is a (possibly cv-qualified) class type:
5489 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005490 // - If the initialization is direct-initialization, or if it is
5491 // copy-initialization where the cv-unqualified version of the
5492 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005493 // class of the destination, constructors are considered. [...]
5494 if (Kind.getKind() == InitializationKind::IK_Direct ||
5495 (Kind.getKind() == InitializationKind::IK_Copy &&
5496 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005497 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005498 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005499 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005501 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005502 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005503 // used) to a derived class thereof are enumerated as described in
5504 // 13.3.1.4, and the best one is chosen through overload resolution
5505 // (13.3).
5506 else
Richard Smith77be48a2014-07-31 06:31:19 +00005507 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005508 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005509 return;
5510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005511
Richard Smith49a6b6e2017-03-24 01:14:25 +00005512 assert(Args.size() >= 1 && "Zero-argument case handled above");
5513
5514 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005515 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005516 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005517 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005518 } else if (isa<InitListExpr>(Args[0])) {
5519 SetFailed(FK_ParenthesizedListInitForScalar);
5520 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522
5523 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005524 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005525 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005526 // For a conversion to _Atomic(T) from either T or a class type derived
5527 // from T, initialize the T object then convert to _Atomic type.
5528 bool NeedAtomicConversion = false;
5529 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5530 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005531 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5532 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005533 DestType = Atomic->getValueType();
5534 NeedAtomicConversion = true;
5535 }
5536 }
5537
5538 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005539 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005540 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005541 if (!Failed() && NeedAtomicConversion)
5542 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005543 return;
5544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005545
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005546 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005547 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005548 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005549 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005550 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005551
John McCall31168b02011-06-15 23:02:42 +00005552 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005553 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005554 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005555 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005556 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005557 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5558 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005559
5560 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005561 ICS.Standard.Second == ICK_Writeback_Conversion) {
5562 // Objective-C ARC writeback conversion.
5563
5564 // We should copy unless we're passing to an argument explicitly
5565 // marked 'out'.
5566 bool ShouldCopy = true;
5567 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5568 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5569
5570 // If there was an lvalue adjustment, add it as a separate conversion.
5571 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5572 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5573 ImplicitConversionSequence LvalueICS;
5574 LvalueICS.setStandard();
5575 LvalueICS.Standard.setAsIdentityConversion();
5576 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5577 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005578 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005579 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005580
Richard Smith77be48a2014-07-31 06:31:19 +00005581 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005582 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005583 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005584 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5585 AddZeroInitializationStep(Entity.getType());
5586 } else if (Initializer->getType() == Context.OverloadTy &&
5587 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5588 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005589 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005590 else if (Initializer->getType()->isFunctionType() &&
5591 isExprAnUnaddressableFunction(S, Initializer))
5592 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005593 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005594 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005595 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005596 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005597
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005598 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005599 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005600}
5601
5602InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005603 for (auto &S : Steps)
5604 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005605}
5606
5607//===----------------------------------------------------------------------===//
5608// Perform initialization
5609//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005610static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005611getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005612 switch(Entity.getKind()) {
5613 case InitializedEntity::EK_Variable:
5614 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005615 case InitializedEntity::EK_Exception:
5616 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005617 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005618 return Sema::AA_Initializing;
5619
5620 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005621 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005622 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5623 return Sema::AA_Sending;
5624
Douglas Gregore1314a62009-12-18 05:02:21 +00005625 return Sema::AA_Passing;
5626
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005627 case InitializedEntity::EK_Parameter_CF_Audited:
5628 if (Entity.getDecl() &&
5629 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5630 return Sema::AA_Sending;
5631
5632 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5633
Douglas Gregore1314a62009-12-18 05:02:21 +00005634 case InitializedEntity::EK_Result:
5635 return Sema::AA_Returning;
5636
Douglas Gregore1314a62009-12-18 05:02:21 +00005637 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005638 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005639 // FIXME: Can we tell apart casting vs. converting?
5640 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005641
Douglas Gregore1314a62009-12-18 05:02:21 +00005642 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005643 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005644 case InitializedEntity::EK_ArrayElement:
5645 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005646 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005647 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005648 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005649 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005650 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005651 return Sema::AA_Initializing;
5652 }
5653
David Blaikie8a40f702012-01-17 06:56:22 +00005654 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005655}
5656
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005657/// Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005658/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005659static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005660 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005661 case InitializedEntity::EK_ArrayElement:
5662 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005663 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00005664 case InitializedEntity::EK_New:
5665 case InitializedEntity::EK_Variable:
5666 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005667 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005668 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005669 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005670 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005671 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005672 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005673 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005674 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005675 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005676
Douglas Gregore1314a62009-12-18 05:02:21 +00005677 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005678 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005679 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005680 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005681 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005682 return true;
5683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005684
Douglas Gregore1314a62009-12-18 05:02:21 +00005685 llvm_unreachable("missed an InitializedEntity kind?");
5686}
5687
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005688/// Whether the given entity, when initialized with an object
Douglas Gregor95562572010-04-24 23:45:46 +00005689/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005690static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005691 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005692 case InitializedEntity::EK_Result:
5693 case InitializedEntity::EK_New:
5694 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005695 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005696 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005697 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005698 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005699 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005700 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005701 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005702
Richard Smith27874d62013-01-08 00:08:23 +00005703 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005704 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005705 case InitializedEntity::EK_Variable:
5706 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005707 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005708 case InitializedEntity::EK_Temporary:
5709 case InitializedEntity::EK_ArrayElement:
5710 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005711 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005712 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005713 return true;
5714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005715
5716 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005717}
5718
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005719/// Get the location at which initialization diagnostics should appear.
Richard Smithc620f552011-10-19 16:55:56 +00005720static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5721 Expr *Initializer) {
5722 switch (Entity.getKind()) {
5723 case InitializedEntity::EK_Result:
5724 return Entity.getReturnLoc();
5725
5726 case InitializedEntity::EK_Exception:
5727 return Entity.getThrowLoc();
5728
5729 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005730 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005731 return Entity.getDecl()->getLocation();
5732
Douglas Gregor19666fb2012-02-15 16:57:26 +00005733 case InitializedEntity::EK_LambdaCapture:
5734 return Entity.getCaptureLoc();
5735
Richard Smithc620f552011-10-19 16:55:56 +00005736 case InitializedEntity::EK_ArrayElement:
5737 case InitializedEntity::EK_Member:
5738 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005739 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005740 case InitializedEntity::EK_Temporary:
5741 case InitializedEntity::EK_New:
5742 case InitializedEntity::EK_Base:
5743 case InitializedEntity::EK_Delegating:
5744 case InitializedEntity::EK_VectorElement:
5745 case InitializedEntity::EK_ComplexElement:
5746 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005747 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005748 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005749 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005750 return Initializer->getLocStart();
5751 }
5752 llvm_unreachable("missed an InitializedEntity kind?");
5753}
5754
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005755/// Make a (potentially elidable) temporary copy of the object
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005756/// provided by the given initializer by calling the appropriate copy
5757/// constructor.
5758///
5759/// \param S The Sema object used for type-checking.
5760///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005761/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005762/// the type of the initializer expression or a superclass thereof.
5763///
James Dennett634962f2012-06-14 21:40:34 +00005764/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005765///
5766/// \param CurInit The initializer expression.
5767///
5768/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5769/// is permitted in C++03 (but not C++0x) when binding a reference to
5770/// an rvalue.
5771///
5772/// \returns An expression that copies the initializer expression into
5773/// a temporary object, or an error expression if a copy could not be
5774/// created.
John McCalldadc5752010-08-24 06:29:42 +00005775static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005776 QualType T,
5777 const InitializedEntity &Entity,
5778 ExprResult CurInit,
5779 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005780 if (CurInit.isInvalid())
5781 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005782 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005783 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005784 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005785 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005786 Class = cast<CXXRecordDecl>(Record->getDecl());
5787 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005788 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005789
Richard Smithc620f552011-10-19 16:55:56 +00005790 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005791
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005792 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005793 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005794 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005795
Richard Smith7c2bcc92016-09-07 02:14:33 +00005796 // Perform overload resolution using the class's constructors. Per
5797 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005798 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005799 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005800 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005801
Douglas Gregore1314a62009-12-18 05:02:21 +00005802 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005803 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005804 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005805 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5806 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5807 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005808 case OR_Success:
5809 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005810
Douglas Gregore1314a62009-12-18 05:02:21 +00005811 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005812 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5813 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5814 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005815 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005816 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005817 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005818 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005819 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005820 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005821
Douglas Gregore1314a62009-12-18 05:02:21 +00005822 case OR_Ambiguous:
5823 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005824 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005825 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005826 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005827 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005828
Douglas Gregore1314a62009-12-18 05:02:21 +00005829 case OR_Deleted:
5830 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005831 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005832 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005833 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005834 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005835 }
5836
Richard Smith7c2bcc92016-09-07 02:14:33 +00005837 bool HadMultipleCandidates = CandidateSet.size() > 1;
5838
Douglas Gregor5ab11652010-04-17 22:01:05 +00005839 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005840 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005841 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005842
Richard Smith5179eb72016-06-28 19:03:57 +00005843 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5844 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005845
5846 if (IsExtraneousCopy) {
5847 // If this is a totally extraneous copy for C++03 reference
5848 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005849 // expression. We don't generate an (elided) copy operation here
5850 // because doing so would require us to pass down a flag to avoid
5851 // infinite recursion, where each step adds another extraneous,
5852 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005853
Douglas Gregor30b52772010-04-18 07:57:34 +00005854 // Instantiate the default arguments of any extra parameters in
5855 // the selected copy constructor, as if we were going to create a
5856 // proper call to the copy constructor.
5857 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5858 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5859 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005860 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005861 break;
5862
5863 // Build the default argument expression; we don't actually care
5864 // if this succeeds or not, because this routine will complain
5865 // if there was a problem.
5866 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5867 }
5868
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005869 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005870 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005871
Douglas Gregor5ab11652010-04-17 22:01:05 +00005872 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005873 // constructor call (we might have derived-to-base conversions, or
5874 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005875 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005876 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005877
Richard Smith7c2bcc92016-09-07 02:14:33 +00005878 // C++0x [class.copy]p32:
5879 // When certain criteria are met, an implementation is allowed to
5880 // omit the copy/move construction of a class object, even if the
5881 // copy/move constructor and/or destructor for the object have
5882 // side effects. [...]
5883 // - when a temporary class object that has not been bound to a
5884 // reference (12.2) would be copied/moved to a class object
5885 // with the same cv-unqualified type, the copy/move operation
5886 // can be omitted by constructing the temporary object
5887 // directly into the target of the omitted copy/move
5888 //
5889 // Note that the other three bullets are handled elsewhere. Copy
5890 // elision for return statements and throw expressions are handled as part
5891 // of constructor initialization, while copy elision for exception handlers
5892 // is handled by the run-time.
5893 //
5894 // FIXME: If the function parameter is not the same type as the temporary, we
5895 // should still be able to elide the copy, but we don't have a way to
5896 // represent in the AST how much should be elided in this case.
5897 bool Elidable =
5898 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5899 S.Context.hasSameUnqualifiedType(
5900 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5901 CurInitExpr->getType());
5902
Douglas Gregord0ace022010-04-25 00:55:24 +00005903 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00005904 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5905 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005906 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005907 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005908 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005909 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005910 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005911 CXXConstructExpr::CK_Complete,
5912 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005913
Douglas Gregord0ace022010-04-25 00:55:24 +00005914 // If we're supposed to bind temporaries, do so.
5915 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005916 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005917 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005918}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005919
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005920/// Check whether elidable copy construction for binding a reference to
Richard Smithc620f552011-10-19 16:55:56 +00005921/// a temporary would have succeeded if we were building in C++98 mode, for
5922/// -Wc++98-compat.
5923static void CheckCXX98CompatAccessibleCopy(Sema &S,
5924 const InitializedEntity &Entity,
5925 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005926 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005927
5928 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5929 if (!Record)
5930 return;
5931
5932 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005933 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005934 return;
5935
5936 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005937 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005938 DeclContext::lookup_result Ctors =
5939 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00005940
5941 // Perform overload resolution.
5942 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005943 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005944 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005945 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5946 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5947 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00005948
5949 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5950 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5951 << CurInitExpr->getSourceRange();
5952
5953 switch (OR) {
5954 case OR_Success:
5955 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00005956 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005957 // FIXME: Check default arguments as far as that's possible.
5958 break;
5959
5960 case OR_No_Viable_Function:
5961 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005962 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005963 break;
5964
5965 case OR_Ambiguous:
5966 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005967 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005968 break;
5969
5970 case OR_Deleted:
5971 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005972 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005973 break;
5974 }
5975}
5976
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005977void InitializationSequence::PrintInitLocationNote(Sema &S,
5978 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005979 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005980 if (Entity.getDecl()->getLocation().isInvalid())
5981 return;
5982
5983 if (Entity.getDecl()->getDeclName())
5984 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5985 << Entity.getDecl()->getDeclName();
5986 else
5987 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5988 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005989 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5990 Entity.getMethodDecl())
5991 S.Diag(Entity.getMethodDecl()->getLocation(),
5992 diag::note_method_return_type_change)
5993 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005994}
5995
Jordan Rose6c0505e2013-05-06 16:48:12 +00005996/// Returns true if the parameters describe a constructor initialization of
5997/// an explicit temporary object, e.g. "Point(x, y)".
5998static bool isExplicitTemporary(const InitializedEntity &Entity,
5999 const InitializationKind &Kind,
6000 unsigned NumArgs) {
6001 switch (Entity.getKind()) {
6002 case InitializedEntity::EK_Temporary:
6003 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006004 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006005 break;
6006 default:
6007 return false;
6008 }
6009
6010 switch (Kind.getKind()) {
6011 case InitializationKind::IK_DirectList:
6012 return true;
6013 // FIXME: Hack to work around cast weirdness.
6014 case InitializationKind::IK_Direct:
6015 case InitializationKind::IK_Value:
6016 return NumArgs != 1;
6017 default:
6018 return false;
6019 }
6020}
6021
Sebastian Redled2e5322011-12-22 14:44:04 +00006022static ExprResult
6023PerformConstructorInitialization(Sema &S,
6024 const InitializedEntity &Entity,
6025 const InitializationKind &Kind,
6026 MultiExprArg Args,
6027 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006028 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006029 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006030 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006031 SourceLocation LBraceLoc,
6032 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006033 unsigned NumArgs = Args.size();
6034 CXXConstructorDecl *Constructor
6035 = cast<CXXConstructorDecl>(Step.Function.Function);
6036 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6037
6038 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006039 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006040 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6041 ? Kind.getEqualLoc()
6042 : Kind.getLocation();
6043
6044 if (Kind.getKind() == InitializationKind::IK_Default) {
6045 // Force even a trivial, implicit default constructor to be
6046 // semantically checked. We do this explicitly because we don't build
6047 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006048 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006049 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006050 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006051 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6052 }
6053
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006054 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006055
Douglas Gregor6073dca2012-02-24 23:56:31 +00006056 // C++ [over.match.copy]p1:
6057 // - When initializing a temporary to be bound to the first parameter
6058 // of a constructor that takes a reference to possibly cv-qualified
6059 // T as its first argument, called with a single argument in the
6060 // context of direct-initialization, explicit conversion functions
6061 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006062 bool AllowExplicitConv =
6063 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6064 hasCopyOrMoveCtorParam(S.Context,
6065 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006066
Sebastian Redled2e5322011-12-22 14:44:04 +00006067 // Determine the arguments required to actually perform the constructor
6068 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006069 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006070 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006071 AllowExplicitConv,
6072 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006073 return ExprError();
6074
6075
Jordan Rose6c0505e2013-05-06 16:48:12 +00006076 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006077 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006078 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6079 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006080
6081 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6082 if (!TSInfo)
6083 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumara14a1f92018-01-17 18:53:51 +00006084 SourceRange ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006085
Richard Smith5179eb72016-06-28 19:03:57 +00006086 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006087 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006088 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006089 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6090 return ExprError();
6091 }
Richard Smith5179eb72016-06-28 19:03:57 +00006092 S.MarkFunctionReferenced(Loc, Constructor);
6093
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006094 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00006095 S.Context, Constructor,
6096 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006097 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6098 IsListInitialization, IsStdInitListInitialization,
6099 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006100 } else {
6101 CXXConstructExpr::ConstructionKind ConstructKind =
6102 CXXConstructExpr::CK_Complete;
6103
6104 if (Entity.getKind() == InitializedEntity::EK_Base) {
6105 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6106 CXXConstructExpr::CK_VirtualBase :
6107 CXXConstructExpr::CK_NonVirtualBase;
6108 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6109 ConstructKind = CXXConstructExpr::CK_Delegating;
6110 }
6111
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006112 // Only get the parenthesis or brace range if it is a list initialization or
6113 // direct construction.
6114 SourceRange ParenOrBraceRange;
6115 if (IsListInitialization)
6116 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6117 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006118 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006119
6120 // If the entity allows NRVO, mark the construction as elidable
6121 // unconditionally.
6122 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006123 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006124 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006125 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006126 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006127 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006128 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006129 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006130 ConstructorInitRequiresZeroInit,
6131 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006132 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006133 else
Richard Smith410306b2016-12-12 02:53:20 +00006134 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006135 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006136 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006137 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006138 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006139 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006140 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006141 ConstructorInitRequiresZeroInit,
6142 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006143 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006144 }
6145 if (CurInit.isInvalid())
6146 return ExprError();
6147
6148 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006149 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006150 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6151 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006152
6153 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006154 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006155
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006156 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006157}
6158
Richard Smitheb3cad52012-06-04 22:27:30 +00006159/// Determine whether the specified InitializedEntity definitely has a lifetime
6160/// longer than the current full-expression. Conservatively returns false if
6161/// it's unclear.
6162static bool
6163InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6164 const InitializedEntity *Top = &Entity;
6165 while (Top->getParent())
6166 Top = Top->getParent();
6167
6168 switch (Top->getKind()) {
6169 case InitializedEntity::EK_Variable:
6170 case InitializedEntity::EK_Result:
6171 case InitializedEntity::EK_Exception:
6172 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00006173 case InitializedEntity::EK_Binding:
Richard Smitheb3cad52012-06-04 22:27:30 +00006174 case InitializedEntity::EK_New:
6175 case InitializedEntity::EK_Base:
6176 case InitializedEntity::EK_Delegating:
6177 return true;
6178
6179 case InitializedEntity::EK_ArrayElement:
6180 case InitializedEntity::EK_VectorElement:
6181 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006182 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smitheb3cad52012-06-04 22:27:30 +00006183 case InitializedEntity::EK_ComplexElement:
6184 // Could not determine what the full initialization is. Assume it might not
6185 // outlive the full-expression.
6186 return false;
6187
6188 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006189 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00006190 case InitializedEntity::EK_Temporary:
6191 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006192 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006193 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00006194 // The entity being initialized might not outlive the full-expression.
6195 return false;
6196 }
6197
6198 llvm_unreachable("unknown entity kind");
6199}
6200
Richard Smith0a9969b2018-07-17 00:11:41 +00006201namespace {
6202enum LifetimeKind {
6203 /// The lifetime of a temporary bound to this entity ends at the end of the
6204 /// full-expression, and that's (probably) fine.
6205 LK_FullExpression,
6206
6207 /// The lifetime of a temporary bound to this entity is extended to the
6208 /// lifeitme of the entity itself.
6209 LK_Extended,
6210
6211 /// The lifetime of a temporary bound to this entity probably ends too soon,
6212 /// because the entity is allocated in a new-expression.
6213 LK_New,
6214
6215 /// The lifetime of a temporary bound to this entity ends too soon, because
6216 /// the entity is a return object.
6217 LK_Return,
6218
6219 /// This is a mem-initializer: if it would extend a temporary (other than via
6220 /// a default member initializer), the program is ill-formed.
6221 LK_MemInitializer,
6222};
6223using LifetimeResult =
6224 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6225}
6226
Richard Smithe6c01442013-06-05 00:46:14 +00006227/// Determine the declaration which an initialized entity ultimately refers to,
6228/// for the purpose of lifetime-extending a temporary bound to a reference in
6229/// the initialization of \p Entity.
Richard Smith0a9969b2018-07-17 00:11:41 +00006230static LifetimeResult getEntityForTemporaryLifetimeExtension(
David Majnemerdaff3702014-05-01 17:50:17 +00006231 const InitializedEntity *Entity,
Richard Smith0a9969b2018-07-17 00:11:41 +00006232 const InitializedEntity *InitField = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006233 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006234 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006235 case InitializedEntity::EK_Variable:
6236 // The temporary [...] persists for the lifetime of the reference
Richard Smith0a9969b2018-07-17 00:11:41 +00006237 return {Entity, LK_Extended};
Richard Smithe6c01442013-06-05 00:46:14 +00006238
6239 case InitializedEntity::EK_Member:
6240 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006241 if (Entity->getParent())
6242 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6243 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006244
6245 // except:
Richard Smith0a9969b2018-07-17 00:11:41 +00006246 // C++17 [class.base.init]p8:
6247 // A temporary expression bound to a reference member in a
6248 // mem-initializer is ill-formed.
6249 // C++17 [class.base.init]p11:
6250 // A temporary expression bound to a reference member from a
6251 // default member initializer is ill-formed.
6252 //
6253 // The context of p11 and its example suggest that it's only the use of a
6254 // default member initializer from a constructor that makes the program
6255 // ill-formed, not its mere existence, and that it can even be used by
6256 // aggregate initialization.
6257 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6258 : LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006259
Richard Smith7873de02016-08-11 22:25:46 +00006260 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006261 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6262 // type.
Richard Smith0a9969b2018-07-17 00:11:41 +00006263 return {Entity, LK_Extended};
Richard Smith7873de02016-08-11 22:25:46 +00006264
Richard Smithe6c01442013-06-05 00:46:14 +00006265 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006266 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006267 // -- A temporary bound to a reference parameter in a function call
6268 // persists until the completion of the full-expression containing
6269 // the call.
Richard Smith0a9969b2018-07-17 00:11:41 +00006270 return {nullptr, LK_FullExpression};
6271
Richard Smithe6c01442013-06-05 00:46:14 +00006272 case InitializedEntity::EK_Result:
6273 // -- The lifetime of a temporary bound to the returned value in a
6274 // function return statement is not extended; the temporary is
6275 // destroyed at the end of the full-expression in the return statement.
Richard Smith0a9969b2018-07-17 00:11:41 +00006276 return {nullptr, LK_Return};
6277
Richard Smithe6c01442013-06-05 00:46:14 +00006278 case InitializedEntity::EK_New:
6279 // -- A temporary bound to a reference in a new-initializer persists
6280 // until the completion of the full-expression containing the
6281 // new-initializer.
Richard Smith0a9969b2018-07-17 00:11:41 +00006282 return {nullptr, LK_New};
Richard Smithe6c01442013-06-05 00:46:14 +00006283
6284 case InitializedEntity::EK_Temporary:
6285 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006286 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006287 // We don't yet know the storage duration of the surrounding temporary.
6288 // Assume it's got full-expression duration for now, it will patch up our
6289 // storage duration if that's not correct.
Richard Smith0a9969b2018-07-17 00:11:41 +00006290 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006291
6292 case InitializedEntity::EK_ArrayElement:
6293 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006294 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
Richard Smith0a9969b2018-07-17 00:11:41 +00006295 InitField);
Richard Smithe6c01442013-06-05 00:46:14 +00006296
6297 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006298 // For subobjects, we look at the complete object.
6299 if (Entity->getParent())
6300 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
Richard Smith0a9969b2018-07-17 00:11:41 +00006301 InitField);
6302 return {InitField, LK_MemInitializer};
6303
Richard Smithe6c01442013-06-05 00:46:14 +00006304 case InitializedEntity::EK_Delegating:
6305 // We can reach this case for aggregate initialization in a constructor:
6306 // struct A { int &&r; };
6307 // struct B : A { B() : A{0} {} };
Richard Smith0a9969b2018-07-17 00:11:41 +00006308 // In this case, use the outermost field decl as the context.
6309 return {InitField, LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006310
6311 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006312 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006313 case InitializedEntity::EK_LambdaCapture:
6314 case InitializedEntity::EK_Exception:
6315 case InitializedEntity::EK_VectorElement:
6316 case InitializedEntity::EK_ComplexElement:
Richard Smith0a9969b2018-07-17 00:11:41 +00006317 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006318 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006319 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006320}
6321
Richard Smith0a9969b2018-07-17 00:11:41 +00006322namespace {
6323enum ExtensionKind {
6324 /// Lifetime would be extended by a reference binding to a temporary.
6325 EK_ReferenceBinding,
6326 /// Lifetime would be extended by a std::initializer_list object binding to
6327 /// its backing array.
6328 EK_StdInitializerList,
6329};
6330using IndirectTemporaryPathEntry =
6331 llvm::PointerUnion<CXXDefaultInitExpr *, ValueDecl *>;
6332using IndirectTemporaryPath = llvm::SmallVectorImpl<IndirectTemporaryPathEntry>;
Richard Smithe6c01442013-06-05 00:46:14 +00006333
Richard Smith0a9969b2018-07-17 00:11:41 +00006334struct RevertToOldSizeRAII {
6335 IndirectTemporaryPath &Path;
6336 unsigned OldSize = Path.size();
6337 RevertToOldSizeRAII(IndirectTemporaryPath &Path) : Path(Path) {}
6338 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6339};
6340}
6341
6342template <typename TemporaryVisitor>
6343static void visitTemporariesExtendedByInitializer(IndirectTemporaryPath &Path,
6344 Expr *Init,
6345 TemporaryVisitor Visit);
6346
6347/// Visit the temporaries whose lifetimes would be extended by binding a
6348/// reference to the glvalue expression \c Init.
6349template <typename TemporaryVisitor>
6350static void
6351visitTemporariesExtendedByReferenceBinding(IndirectTemporaryPath &Path,
6352 Expr *Init, ExtensionKind EK,
6353 TemporaryVisitor Visit) {
6354 RevertToOldSizeRAII RAII(Path);
6355
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006356 // Walk past any constructs which we can lifetime-extend across.
6357 Expr *Old;
6358 do {
6359 Old = Init;
6360
Richard Smithdbc82492015-01-10 01:28:13 +00006361 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith0a9969b2018-07-17 00:11:41 +00006362 // If this is just redundant braces around an initializer, step over it.
6363 if (ILE->isTransparent())
Richard Smithdbc82492015-01-10 01:28:13 +00006364 Init = ILE->getInit(0);
Richard Smithdbc82492015-01-10 01:28:13 +00006365 }
6366
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006367 // Step over any subobject adjustments; we may have a materialized
6368 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006369 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006370
6371 // Per current approach for DR1376, look through casts to reference type
6372 // when performing lifetime extension.
6373 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6374 if (CE->getSubExpr()->isGLValue())
6375 Init = CE->getSubExpr();
6376
Richard Smithb3189a12016-12-05 07:49:14 +00006377 // Per the current approach for DR1299, look through array element access
6378 // when performing lifetime extension.
6379 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6380 Init = ASE->getBase();
Richard Smith0a9969b2018-07-17 00:11:41 +00006381
6382 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6383 // constructor inherits one as an implicit mem-initializer.
6384 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6385 Path.push_back(DIE);
6386 Init = DIE->getExpr();
6387
6388 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
6389 Init = EWC->getSubExpr();
6390 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006391 } while (Init != Old);
6392
Richard Smith0a9969b2018-07-17 00:11:41 +00006393 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6394 if (Visit(Path, MTE, EK))
6395 visitTemporariesExtendedByInitializer(Path, MTE->GetTemporaryExpr(),
6396 Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006397 }
6398}
6399
Richard Smith0a9969b2018-07-17 00:11:41 +00006400/// Visit the temporaries whose lifetimes would be extended by
6401/// lifetime-extending the object initialized by the prvalue expression \c
6402/// Init.
6403template <typename TemporaryVisitor>
6404static void visitTemporariesExtendedByInitializer(IndirectTemporaryPath &Path,
6405 Expr *Init,
6406 TemporaryVisitor Visit) {
6407 RevertToOldSizeRAII RAII(Path);
6408
6409 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6410 // constructor inherits one as an implicit mem-initializer.
6411 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6412 Path.push_back(DIE);
6413 Init = DIE->getExpr();
6414
6415 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
6416 Init = EWC->getSubExpr();
6417 }
6418
Richard Smithe6c01442013-06-05 00:46:14 +00006419 // Dig out the expression which constructs the extended temporary.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006420 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smithe6c01442013-06-05 00:46:14 +00006421
Richard Smith736a9472013-06-12 20:42:33 +00006422 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6423 Init = BTE->getSubExpr();
6424
Richard Smith0a9969b2018-07-17 00:11:41 +00006425 // C++17 [dcl.init.list]p6:
6426 // initializing an initializer_list object from the array extends the
6427 // lifetime of the array exactly like binding a reference to a temporary.
6428 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
6429 return visitTemporariesExtendedByReferenceBinding(
6430 Path, ILE->getSubExpr(), EK_StdInitializerList, Visit);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006431
Richard Smithe6c01442013-06-05 00:46:14 +00006432 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith0a9969b2018-07-17 00:11:41 +00006433 if (ILE->isTransparent())
6434 return visitTemporariesExtendedByInitializer(Path, ILE->getInit(0),
6435 Visit);
6436
Richard Smithcc1b96d2013-06-12 22:31:48 +00006437 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006438 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Richard Smith0a9969b2018-07-17 00:11:41 +00006439 visitTemporariesExtendedByInitializer(Path, ILE->getInit(I), Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006440 return;
6441 }
6442
Richard Smithcc1b96d2013-06-12 22:31:48 +00006443 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006444 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6445
6446 // If we lifetime-extend a braced initializer which is initializing an
6447 // aggregate, and that aggregate contains reference members which are
6448 // bound to temporaries, those temporaries are also lifetime-extended.
6449 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6450 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Richard Smith0a9969b2018-07-17 00:11:41 +00006451 visitTemporariesExtendedByReferenceBinding(Path, ILE->getInit(0),
6452 EK_ReferenceBinding, Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006453 else {
6454 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006455 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006456 if (Index >= ILE->getNumInits())
6457 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006458 if (I->isUnnamedBitfield())
6459 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006460 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006461 if (I->getType()->isReferenceType())
Richard Smith0a9969b2018-07-17 00:11:41 +00006462 visitTemporariesExtendedByReferenceBinding(
6463 Path, SubInit, EK_ReferenceBinding, Visit);
6464 else
6465 // This might be either aggregate-initialization of a member or
6466 // initialization of a std::initializer_list object. Regardless,
Richard Smithe6c01442013-06-05 00:46:14 +00006467 // we should recursively lifetime-extend that initializer.
Richard Smith0a9969b2018-07-17 00:11:41 +00006468 visitTemporariesExtendedByInitializer(Path, SubInit, Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006469 ++Index;
6470 }
6471 }
6472 }
6473 }
6474}
6475
Richard Smith0a9969b2018-07-17 00:11:41 +00006476/// Determine whether this is an indirect path to a temporary that we are
6477/// supposed to lifetime-extend along (but don't).
6478static bool shouldLifetimeExtendThroughPath(const IndirectTemporaryPath &Path) {
6479 for (auto Elem : Path) {
6480 if (!Elem.is<CXXDefaultInitExpr*>())
6481 return false;
6482 }
6483 return true;
6484}
6485
6486void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
6487 Expr *Init) {
6488 LifetimeResult LR = getEntityForTemporaryLifetimeExtension(&Entity);
6489 LifetimeKind LK = LR.getInt();
6490 const InitializedEntity *ExtendingEntity = LR.getPointer();
6491
6492 // If this entity doesn't have an interesting lifetime, don't bother looking
6493 // for temporaries within its initializer.
6494 if (LK == LK_FullExpression)
6495 return;
6496
6497 auto TemporaryVisitor = [&](IndirectTemporaryPath &Path,
6498 MaterializeTemporaryExpr *MTE,
6499 ExtensionKind EK) -> bool {
6500 switch (LK) {
6501 case LK_FullExpression:
6502 llvm_unreachable("already handled this");
6503
6504 case LK_Extended:
6505 // Lifetime-extend the temporary.
6506 if (Path.empty()) {
6507 // Update the storage duration of the materialized temporary.
6508 // FIXME: Rebuild the expression instead of mutating it.
6509 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
6510 ExtendingEntity->allocateManglingNumber());
6511 // Also visit the temporaries lifetime-extended by this initializer.
6512 return true;
6513 }
6514
6515 if (shouldLifetimeExtendThroughPath(Path)) {
6516 // We're supposed to lifetime-extend the temporary along this path (per
6517 // the resolution of DR1815), but we don't support that yet.
6518 //
6519 // FIXME: Properly handle this situation. Perhaps the easiest approach
6520 // would be to clone the initializer expression on each use that would
6521 // lifetime extend its temporaries.
6522 Diag(MTE->getExprLoc(),
6523 EK == EK_ReferenceBinding
6524 ? diag::warn_default_member_init_temporary_not_extended
6525 : diag::warn_default_member_init_init_list_not_extended);
6526 } else {
6527 llvm_unreachable("unexpected indirect temporary path");
6528 }
6529 break;
6530
6531 case LK_MemInitializer:
6532 // Under C++ DR1696, if a mem-initializer (or a default member
6533 // initializer used by the absence of one) would lifetime-extend a
6534 // temporary, the program is ill-formed.
6535 if (auto *ExtendingDecl = ExtendingEntity->getDecl()) {
6536 bool IsSubobjectMember = ExtendingEntity != &Entity;
6537 Diag(MTE->getExprLoc(), diag::err_bind_ref_member_to_temporary)
6538 << ExtendingDecl << Init->getSourceRange() << IsSubobjectMember
6539 << EK;
6540 // Don't bother adding a note pointing to the field if we're inside its
6541 // default member initializer; our primary diagnostic points to the
6542 // same place in that case.
6543 if (Path.empty() || !Path.back().is<CXXDefaultInitExpr*>()) {
6544 Diag(ExtendingDecl->getLocation(),
6545 diag::note_lifetime_extending_member_declared_here)
6546 << EK << IsSubobjectMember;
6547 }
6548 } else {
6549 // We have a mem-initializer but no particular field within it; this
6550 // is either a base class or a delegating initializer directly
6551 // initializing the base-class from something that doesn't live long
6552 // enough. Either way, that can't happen.
6553 // FIXME: Move CheckForDanglingReferenceOrPointer checks here.
6554 llvm_unreachable(
6555 "temporary initializer for base class / delegating ctor");
6556 }
6557 break;
6558
6559 case LK_New:
6560 if (EK == EK_ReferenceBinding) {
6561 Diag(MTE->getExprLoc(), diag::warn_new_dangling_reference);
6562 } else {
6563 Diag(MTE->getExprLoc(), diag::warn_new_dangling_initializer_list)
6564 << (ExtendingEntity != &Entity);
6565 }
6566 break;
6567
6568 case LK_Return:
6569 // FIXME: Move -Wreturn-stack-address checks here.
6570 return false;
Richard Smithcc1b96d2013-06-12 22:31:48 +00006571 }
6572
Richard Smith0a9969b2018-07-17 00:11:41 +00006573 // FIXME: Model these as CodeSynthesisContexts to fix the note emission
6574 // order.
6575 for (auto Elem : llvm::reverse(Path)) {
6576 if (auto *DIE = Elem.dyn_cast<CXXDefaultInitExpr*>()) {
6577 Diag(DIE->getExprLoc(), diag::note_in_default_member_initalizer_here)
6578 << DIE->getField();
Richard Smithcc1b96d2013-06-12 22:31:48 +00006579 }
6580 }
Richard Smith0a9969b2018-07-17 00:11:41 +00006581
6582 // We didn't lifetime-extend, so don't go any further; we don't need more
6583 // warnings or errors on inner temporaries within this one's initializer.
6584 return false;
6585 };
6586
6587 llvm::SmallVector<IndirectTemporaryPathEntry, 8> Path;
6588 if (Init->isGLValue())
6589 visitTemporariesExtendedByReferenceBinding(Path, Init, EK_ReferenceBinding,
6590 TemporaryVisitor);
6591 else
6592 visitTemporariesExtendedByInitializer(Path, Init, TemporaryVisitor);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006593}
6594
Richard Smithaaa0ec42013-09-21 21:19:19 +00006595static void DiagnoseNarrowingInInitList(Sema &S,
6596 const ImplicitConversionSequence &ICS,
6597 QualType PreNarrowingType,
6598 QualType EntityType,
6599 const Expr *PostInit);
6600
Richard Trieuac3eca52015-04-29 01:52:17 +00006601/// Provide warnings when std::move is used on construction.
6602static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6603 bool IsReturnStmt) {
6604 if (!InitExpr)
6605 return;
6606
Richard Smith51ec0cf2017-02-21 01:17:38 +00006607 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00006608 return;
6609
Richard Trieuac3eca52015-04-29 01:52:17 +00006610 QualType DestType = InitExpr->getType();
6611 if (!DestType->isRecordType())
6612 return;
6613
6614 unsigned DiagID = 0;
6615 if (IsReturnStmt) {
6616 const CXXConstructExpr *CCE =
6617 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6618 if (!CCE || CCE->getNumArgs() != 1)
6619 return;
6620
6621 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6622 return;
6623
6624 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00006625 }
6626
6627 // Find the std::move call and get the argument.
6628 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
Nico Weber192184c2018-06-20 15:57:38 +00006629 if (!CE || !CE->isCallToStdMove())
Richard Trieuac3eca52015-04-29 01:52:17 +00006630 return;
6631
6632 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6633
6634 if (IsReturnStmt) {
6635 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6636 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6637 return;
6638
6639 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6640 if (!VD || !VD->hasLocalStorage())
6641 return;
6642
Alex Lorenzbbe51d82017-11-07 21:40:11 +00006643 // __block variables are not moved implicitly.
6644 if (VD->hasAttr<BlocksAttr>())
6645 return;
6646
Richard Trieu8d4006a2015-07-28 19:06:16 +00006647 QualType SourceType = VD->getType();
6648 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00006649 return;
6650
Richard Trieu8d4006a2015-07-28 19:06:16 +00006651 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00006652 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00006653 }
6654
Davide Italiano7842c3f2015-07-18 01:15:19 +00006655 // If we're returning a function parameter, copy elision
6656 // is not possible.
6657 if (isa<ParmVarDecl>(VD))
6658 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00006659 else
6660 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00006661 } else {
6662 DiagID = diag::warn_pessimizing_move_on_initialization;
6663 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6664 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6665 return;
6666 }
6667
6668 S.Diag(CE->getLocStart(), DiagID);
6669
6670 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6671 // is within a macro.
6672 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6673 if (CallBegin.isMacroID())
6674 return;
6675 SourceLocation RParen = CE->getRParenLoc();
6676 if (RParen.isMacroID())
6677 return;
6678 SourceLocation LParen;
6679 SourceLocation ArgLoc = Arg->getLocStart();
6680
6681 // Special testing for the argument location. Since the fix-it needs the
6682 // location right before the argument, the argument location can be in a
6683 // macro only if it is at the beginning of the macro.
6684 while (ArgLoc.isMacroID() &&
6685 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
Richard Smithb5f81712018-04-30 05:25:48 +00006686 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
Richard Trieuac3eca52015-04-29 01:52:17 +00006687 }
6688
6689 if (LParen.isMacroID())
6690 return;
6691
6692 LParen = ArgLoc.getLocWithOffset(-1);
6693
6694 S.Diag(CE->getLocStart(), diag::note_remove_move)
6695 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6696 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6697}
6698
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006699static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6700 // Check to see if we are dereferencing a null pointer. If so, this is
6701 // undefined behavior, so warn about it. This only handles the pattern
6702 // "*null", which is a very syntactic check.
6703 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6704 if (UO->getOpcode() == UO_Deref &&
6705 UO->getSubExpr()->IgnoreParenCasts()->
6706 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6707 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6708 S.PDiag(diag::warn_binding_null_to_reference)
6709 << UO->getSubExpr()->getSourceRange());
6710 }
6711}
6712
Tim Shen4a05bb82016-06-21 20:29:17 +00006713MaterializeTemporaryExpr *
6714Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6715 bool BoundToLvalueReference) {
6716 auto MTE = new (Context)
6717 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6718
6719 // Order an ExprWithCleanups for lifetime marks.
6720 //
6721 // TODO: It'll be good to have a single place to check the access of the
6722 // destructor and generate ExprWithCleanups for various uses. Currently these
6723 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6724 // but there may be a chance to merge them.
6725 Cleanup.setExprNeedsCleanups(false);
6726 return MTE;
6727}
6728
Richard Smith4baaa5a2016-12-03 01:14:32 +00006729ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6730 // In C++98, we don't want to implicitly create an xvalue.
6731 // FIXME: This means that AST consumers need to deal with "prvalues" that
6732 // denote materialized temporaries. Maybe we should add another ValueKind
6733 // for "xvalue pretending to be a prvalue" for C++98 support.
6734 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6735 return E;
6736
6737 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00006738 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6739 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006740 QualType T = E->getType();
6741 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6742 return ExprError();
6743
6744 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6745}
6746
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006748InitializationSequence::Perform(Sema &S,
6749 const InitializedEntity &Entity,
6750 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00006751 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006752 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006753 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006754 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00006755 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006756 }
Nico Weber337d5aa2015-04-17 08:32:38 +00006757 if (!ZeroInitializationFixit.empty()) {
6758 unsigned DiagID = diag::err_default_init_const;
6759 if (Decl *D = Entity.getDecl())
6760 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6761 DiagID = diag::ext_default_init_const;
6762
6763 // The initialization would have succeeded with this fixit. Since the fixit
6764 // is on the error, we need to build a valid AST in this case, so this isn't
6765 // handled in the Failed() branch above.
6766 QualType DestType = Entity.getType();
6767 S.Diag(Kind.getLocation(), DiagID)
6768 << DestType << (bool)DestType->getAs<RecordType>()
6769 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6770 ZeroInitializationFixit);
6771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006772
Sebastian Redld201edf2011-06-05 13:59:11 +00006773 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006774 // If the declaration is a non-dependent, incomplete array type
6775 // that has an initializer, then its type will be completed once
6776 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00006777 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00006778 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006779 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006780 if (const IncompleteArrayType *ArrayT
6781 = S.Context.getAsIncompleteArrayType(DeclType)) {
6782 // FIXME: We don't currently have the ability to accurately
6783 // compute the length of an initializer list without
6784 // performing full type-checking of the initializer list
6785 // (since we have to determine where braces are implicitly
6786 // introduced and such). So, we fall back to making the array
6787 // type a dependently-sized array type with no specified
6788 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006789 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006790 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00006791
Douglas Gregor51e77d52009-12-10 17:56:55 +00006792 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00006793 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006794 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6795 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00006796 if (IncompleteArrayTypeLoc ArrayLoc =
6797 TL.getAs<IncompleteArrayTypeLoc>())
6798 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00006799 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00006800 }
6801
6802 *ResultType
6803 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006804 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006805 ArrayT->getSizeModifier(),
6806 ArrayT->getIndexTypeCVRQualifiers(),
6807 Brackets);
6808 }
6809
6810 }
6811 }
Sebastian Redla9351792012-02-11 23:51:47 +00006812 if (Kind.getKind() == InitializationKind::IK_Direct &&
6813 !Kind.isExplicitCast()) {
6814 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00006815 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00006816 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006817 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00006818 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00006819 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00006820 Kind.isExplicitCast() ||
6821 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006822 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006823 }
6824
Sebastian Redld201edf2011-06-05 13:59:11 +00006825 // No steps means no initialization.
6826 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006827 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006828
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006829 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006830 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006831 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00006832 // Produce a C++98 compatibility warning if we are initializing a reference
6833 // from an initializer list. For parameters, we produce a better warning
6834 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006835 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00006836 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6837 << Init->getSourceRange();
6838 }
6839
Egor Churaev3bccec52017-04-05 12:47:10 +00006840 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6841 QualType ETy = Entity.getType();
6842 Qualifiers TyQualifiers = ETy.getQualifiers();
6843 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6844 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6845
6846 if (S.getLangOpts().OpenCLVersion >= 200 &&
6847 ETy->isAtomicType() && !HasGlobalAS &&
6848 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6849 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6850 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6851 return ExprError();
6852 }
6853
Richard Smitheb3cad52012-06-04 22:27:30 +00006854 // Diagnose cases where we initialize a pointer to an array temporary, and the
6855 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006856 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00006857 Entity.getType()->isPointerType() &&
6858 InitializedEntityOutlivesFullExpression(Entity)) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00006859 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6860 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6861 Init = MTE->GetTemporaryExpr();
Richard Smitheb3cad52012-06-04 22:27:30 +00006862 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6863 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6864 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6865 << Init->getSourceRange();
6866 }
6867
Douglas Gregor1b303932009-12-22 15:35:07 +00006868 QualType DestType = Entity.getType().getNonReferenceType();
6869 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00006870 // the same as Entity.getDecl()->getType() in cases involving type merging,
6871 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00006872 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00006873 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00006874 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006875
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006876 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00006877 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006879 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00006880 // grab the only argument out the Args and place it into the "current"
6881 // initializer.
6882 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006883 case SK_ResolveAddressOfOverloadedFunction:
6884 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006885 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006886 case SK_CastDerivedToBaseLValue:
6887 case SK_BindReference:
6888 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00006889 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006890 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00006891 case SK_UserConversion:
6892 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006893 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006894 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00006895 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00006896 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006897 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00006898 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00006899 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00006900 case SK_UnwrapInitList:
6901 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00006902 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00006903 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00006904 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00006905 case SK_ArrayLoopIndex:
6906 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00006907 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00006908 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00006909 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00006910 case SK_PassByIndirectCopyRestore:
6911 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00006912 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006913 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00006914 case SK_OCLSamplerInit:
Egor Churaev89831422016-12-23 14:55:49 +00006915 case SK_OCLZeroEvent:
6916 case SK_OCLZeroQueue: {
Douglas Gregore1314a62009-12-18 05:02:21 +00006917 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006918 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00006919 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006920 break;
John McCall34376a62010-12-04 03:47:34 +00006921 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006922
Douglas Gregore1314a62009-12-18 05:02:21 +00006923 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00006924 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006925 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00006926 case SK_ZeroInitialization:
6927 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006929
Richard Smithd6a15082017-01-07 00:48:55 +00006930 // Promote from an unevaluated context to an unevaluated list context in
6931 // C++11 list-initialization; we need to instantiate entities usable in
6932 // constant expressions here in order to perform narrowing checks =(
6933 EnterExpressionEvaluationContext Evaluated(
6934 S, EnterExpressionEvaluationContext::InitList,
6935 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6936
Richard Smith81f5ade2016-12-15 02:28:18 +00006937 // C++ [class.abstract]p2:
6938 // no objects of an abstract class can be created except as subobjects
6939 // of a class derived from it
6940 auto checkAbstractType = [&](QualType T) -> bool {
6941 if (Entity.getKind() == InitializedEntity::EK_Base ||
6942 Entity.getKind() == InitializedEntity::EK_Delegating)
6943 return false;
6944 return S.RequireNonAbstractType(Kind.getLocation(), T,
6945 diag::err_allocation_of_abstract_type);
6946 };
6947
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006948 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006949 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006950 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006951 for (step_iterator Step = step_begin(), StepEnd = step_end();
6952 Step != StepEnd; ++Step) {
6953 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006954 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006955
John Wiegley01296292011-04-08 18:41:53 +00006956 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006958 switch (Step->Kind) {
6959 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006960 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006961 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00006962 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00006963 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6964 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006965 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00006966 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00006967 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006968 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006969
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006970 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006971 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006972 case SK_CastDerivedToBaseLValue: {
6973 // We have a derived-to-base cast that produces either an rvalue or an
6974 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975
John McCallcf142162010-08-07 06:22:56 +00006976 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00006977
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006978 // Casts to inaccessible base classes are allowed with C-style casts.
6979 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6980 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00006981 CurInit.get()->getLocStart(),
6982 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00006983 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00006984 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006985
John McCall2536c6d2010-08-25 10:28:54 +00006986 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006987 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006988 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006989 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006990 VK_XValue :
6991 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006992 CurInit =
6993 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6994 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006995 break;
6996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006998 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006999 // Reference binding does not have any corresponding ASTs.
7000
7001 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007002 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007003 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007004
George Burgess IVcfd48d92017-04-13 23:47:08 +00007005 // We don't check for e.g. function pointers here, since address
7006 // availability checks should only occur when the function first decays
7007 // into a pointer or reference.
7008 if (CurInit.get()->getType()->isFunctionProtoType()) {
7009 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7010 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7011 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7012 DRE->getLocStart()))
7013 return ExprError();
7014 }
7015 }
7016 }
7017
Richard Smith6b6f8aa2013-06-15 00:30:29 +00007018 // Even though we didn't materialize a temporary, the binding may still
Richard Smith0a9969b2018-07-17 00:11:41 +00007019 // extend the lifetime of a temporary. This happens if we bind a
7020 // reference to the result of a cast to reference type.
7021 S.checkInitializerLifetime(Entity, CurInit.get());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00007022
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007023 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007024 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007025
Richard Smithe6c01442013-06-05 00:46:14 +00007026 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00007027 // Make sure the "temporary" is actually an rvalue.
7028 assert(CurInit.get()->isRValue() && "not a temporary");
7029
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007030 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007031 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007032 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007033
Douglas Gregorfe314812011-06-21 17:03:29 +00007034 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007035 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00007036 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
Richard Smith0a9969b2018-07-17 00:11:41 +00007037 CurInit = MTE;
David Majnemerdaff3702014-05-01 17:50:17 +00007038
7039 // Maybe lifetime-extend the temporary's subobjects to match the
7040 // entity's lifetime.
Richard Smith0a9969b2018-07-17 00:11:41 +00007041 S.checkInitializerLifetime(Entity, CurInit.get());
Douglas Gregor58df5092011-06-22 16:12:01 +00007042
Brian Kelley762f9282017-03-29 18:16:38 +00007043 // If we're extending this temporary to automatic storage duration -- we
7044 // need to register its cleanup during the full-expression's cleanups.
7045 if (MTE->getStorageDuration() == SD_Automatic &&
7046 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00007047 S.Cleanup.setExprNeedsCleanups(true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007048 break;
Richard Smithe6c01442013-06-05 00:46:14 +00007049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007050
Richard Smithb8c0f552016-12-09 18:49:13 +00007051 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00007052 if (checkAbstractType(Step->Type))
7053 return ExprError();
7054
Richard Smithb8c0f552016-12-09 18:49:13 +00007055 // If the overall initialization is initializing a temporary, we already
7056 // bound our argument if it was necessary to do so. If not (if we're
7057 // ultimately initializing a non-temporary), our argument needs to be
7058 // bound since it's initializing a function parameter.
7059 // FIXME: This is a mess. Rationalize temporary destruction.
7060 if (!shouldBindAsTemporary(Entity))
7061 CurInit = S.MaybeBindToTemporary(CurInit.get());
7062 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7063 /*IsExtraneousCopy=*/false);
7064 break;
7065
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007066 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007067 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007068 /*IsExtraneousCopy=*/true);
7069 break;
7070
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007071 case SK_UserConversion: {
7072 // We have a user-defined conversion that invokes either a constructor
7073 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00007074 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00007075 FunctionDecl *Fn = Step->Function.Function;
7076 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007077 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00007078 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00007079 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007080 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00007081 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00007082 SourceLocation Loc = CurInit.get()->getLocStart();
John McCall760af172010-02-01 03:16:54 +00007083
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007084 // Determine the arguments required to actually perform the constructor
7085 // call.
John Wiegley01296292011-04-08 18:41:53 +00007086 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007087 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00007088 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007089 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00007090 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007091
Richard Smithb24f0672012-02-11 19:22:50 +00007092 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00007093 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
7094 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007095 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007096 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00007097 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007098 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00007099 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00007100 CXXConstructExpr::CK_Complete,
7101 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007102 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007103 return ExprError();
John McCall760af172010-02-01 03:16:54 +00007104
Richard Smith5179eb72016-06-28 19:03:57 +00007105 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7106 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00007107 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7108 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007109
John McCalle3027922010-08-25 11:45:40 +00007110 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00007111 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007112 } else {
7113 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00007114 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00007115 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00007116 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00007117 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7118 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119
7120 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007121 // derived-to-base conversion? I believe the answer is "no", because
7122 // we don't want to turn off access control here for c-style casts.
Richard Smithb8c0f552016-12-09 18:49:13 +00007123 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
7124 /*Qualifier=*/nullptr,
7125 FoundFn, Conversion);
7126 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007127 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007129 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007130 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7131 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00007132 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007133 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007134
John McCalle3027922010-08-25 11:45:40 +00007135 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00007136 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007138
Richard Smith81f5ade2016-12-15 02:28:18 +00007139 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7140 return ExprError();
7141
Richard Smithb8c0f552016-12-09 18:49:13 +00007142 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
7143 CastKind, CurInit.get(), nullptr,
7144 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00007145
Richard Smithb8c0f552016-12-09 18:49:13 +00007146 if (shouldBindAsTemporary(Entity))
7147 // The overall entity is temporary, so this expression should be
7148 // destroyed at the end of its full-expression.
7149 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7150 else if (CreatedObject && shouldDestroyEntity(Entity)) {
7151 // The object outlasts the full-expression, but we need to prepare for
7152 // a destructor being run on it.
7153 // FIXME: It makes no sense to do this here. This should happen
7154 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00007155 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00007156 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007157 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00007158 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00007159 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00007160 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00007161 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00007162 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
7163 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00007164 }
7165 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007166 break;
7167 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007168
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007169 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007170 case SK_QualificationConversionXValue:
7171 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007172 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00007173 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007174 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007175 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007176 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007177 VK_XValue :
7178 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007179 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007180 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007181 }
7182
Richard Smith77be48a2014-07-31 06:31:19 +00007183 case SK_AtomicConversion: {
7184 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7185 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7186 CK_NonAtomicToAtomic, VK_RValue);
7187 break;
7188 }
7189
Jordan Roseb1312a52013-04-11 00:58:58 +00007190 case SK_LValueToRValue: {
7191 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007192 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7193 CK_LValueToRValue, CurInit.get(),
7194 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00007195 break;
7196 }
7197
Richard Smithaaa0ec42013-09-21 21:19:19 +00007198 case SK_ConversionSequence:
7199 case SK_ConversionSequenceNoNarrowing: {
7200 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007201 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7202 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007203 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007204 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007205 ExprResult CurInitExprRes =
7206 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007207 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007208 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007209 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007210
7211 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7212
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007213 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007214
7215 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007216 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007217 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7218 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007219
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007220 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007222
Douglas Gregor51e77d52009-12-10 17:56:55 +00007223 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007224 if (checkAbstractType(Step->Type))
7225 return ExprError();
7226
John Wiegley01296292011-04-08 18:41:53 +00007227 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007228 // If we're not initializing the top-level entity, we need to create an
7229 // InitializeTemporary entity for our target type.
7230 QualType Ty = Step->Type;
7231 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007232 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007233 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7234 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007235 InitList, Ty, /*VerifyOnly=*/false,
7236 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007237 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007238 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007239
Richard Smithcc1b96d2013-06-12 22:31:48 +00007240 // Hack: We must update *ResultType if available in order to set the
7241 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7242 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7243 if (ResultType &&
7244 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007245 if ((*ResultType)->isRValueReferenceType())
7246 Ty = S.Context.getRValueReferenceType(Ty);
7247 else if ((*ResultType)->isLValueReferenceType())
7248 Ty = S.Context.getLValueReferenceType(Ty,
7249 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7250 *ResultType = Ty;
7251 }
7252
7253 InitListExpr *StructuredInitList =
7254 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007255 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007256 CurInit = shouldBindAsTemporary(InitEntity)
7257 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007258 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007259 break;
7260 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007261
Richard Smith53324112014-07-16 21:33:43 +00007262 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007263 if (checkAbstractType(Step->Type))
7264 return ExprError();
7265
Sebastian Redl5a41f682012-02-12 16:37:24 +00007266 // When an initializer list is passed for a parameter of type "reference
7267 // to object", we don't get an EK_Temporary entity, but instead an
7268 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007269 // FIXME: This is a hack. What we really should do is create a user
7270 // conversion step for this case, but this makes it considerably more
7271 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007272 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7273 Entity.getType().getNonReferenceType());
7274 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007275 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007276 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007277 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7278 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007279 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007280 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7281 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007282 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007283 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007284 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007285 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007286 InitList->getLBraceLoc(),
7287 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007288 break;
7289 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007290
Sebastian Redl29526f02011-11-27 16:50:07 +00007291 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007292 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007293 break;
7294
7295 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007296 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007297 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7298 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007299 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007300 ILE->setSyntacticForm(Syntactic);
7301 ILE->setType(E->getType());
7302 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007303 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007304 break;
7305 }
7306
Richard Smith53324112014-07-16 21:33:43 +00007307 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007308 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007309 if (checkAbstractType(Step->Type))
7310 return ExprError();
7311
Sebastian Redl99f66162012-02-19 12:27:56 +00007312 // When an initializer list is passed for a parameter of type "reference
7313 // to object", we don't get an EK_Temporary entity, but instead an
7314 // EK_Parameter entity with reference type.
7315 // FIXME: This is a hack. What we really should do is create a user
7316 // conversion step for this case, but this makes it considerably more
7317 // complicated. For now, this will do.
7318 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7319 Entity.getType().getNonReferenceType());
7320 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00007321 bool IsStdInitListInit =
7322 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00007323 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00007324 SourceRange Range = Kind.hasParenOrBraceRange()
7325 ? Kind.getParenOrBraceRange()
7326 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00007327 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00007328 S, UseTemporary ? TempEntity : Entity, Kind,
7329 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00007330 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00007331 /*IsListInitialization*/ IsStdInitListInit,
7332 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00007333 /*LBraceLoc*/ Range.getBegin(),
7334 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007335 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00007336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007337
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007338 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007339 step_iterator NextStep = Step;
7340 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007341 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007342 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007343 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007344 // The need for zero-initialization is recorded directly into
7345 // the call to the object's constructor within the next step.
7346 ConstructorInitRequiresZeroInit = true;
7347 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007348 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007349 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007350 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7351 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007352 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007353 Kind.getRange().getBegin());
7354
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007355 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007356 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007357 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007358 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007359 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007360 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007361 break;
7362 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007363
7364 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007365 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007366 // Save off the initial CurInit in case we need to emit a diagnostic
7367 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007368 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007369 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007370 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7371 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007372 if (Result.isInvalid())
7373 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007374 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007375
7376 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007377 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007378 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007379 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007380 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007381 == Sema::Compatible)
7382 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007383 if (CurInitExprRes.isInvalid())
7384 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007385 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007386
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007387 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007388 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7389 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007390 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007391 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007392 &Complained)) {
7393 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007394 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007395 } else if (Complained)
7396 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007397 break;
7398 }
Eli Friedman78275202009-12-19 08:11:05 +00007399
7400 case SK_StringInit: {
7401 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007402 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007403 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007404 break;
7405 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007406
7407 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007408 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007409 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007410 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007411 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007412
Richard Smith410306b2016-12-12 02:53:20 +00007413 case SK_ArrayLoopIndex: {
7414 Expr *Cur = CurInit.get();
7415 Expr *BaseExpr = new (S.Context)
7416 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7417 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7418 Expr *IndexExpr =
7419 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7420 CurInit = S.CreateBuiltinArraySubscriptExpr(
7421 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7422 ArrayLoopCommonExprs.push_back(BaseExpr);
7423 break;
7424 }
7425
7426 case SK_ArrayLoopInit: {
7427 assert(!ArrayLoopCommonExprs.empty() &&
7428 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7429 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7430 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7431 CurInit.get());
7432 break;
7433 }
7434
Richard Smith378b8c82016-12-14 03:22:16 +00007435 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007436 // Okay: we checked everything before creating this step. Note that
7437 // this is a GNU extension.
7438 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007439 << Step->Type << CurInit.get()->getType()
7440 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007441 LLVM_FALLTHROUGH;
7442 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007443 // If the destination type is an incomplete array type, update the
7444 // type accordingly.
7445 if (ResultType) {
7446 if (const IncompleteArrayType *IncompleteDest
7447 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7448 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007449 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007450 *ResultType = S.Context.getConstantArrayType(
7451 IncompleteDest->getElementType(),
7452 ConstantSource->getSize(),
7453 ArrayType::Normal, 0);
7454 }
7455 }
7456 }
John McCall31168b02011-06-15 23:02:42 +00007457 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007458
Richard Smithebeed412012-02-15 22:38:09 +00007459 case SK_ParenthesizedArrayInit:
7460 // Okay: we checked everything before creating this step. Note that
7461 // this is a GNU extension.
7462 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7463 << CurInit.get()->getSourceRange();
7464 break;
7465
John McCall31168b02011-06-15 23:02:42 +00007466 case SK_PassByIndirectCopyRestore:
7467 case SK_PassByIndirectRestore:
7468 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007469 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7470 CurInit.get(), Step->Type,
7471 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007472 break;
7473
7474 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007475 CurInit =
7476 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7477 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007478 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007479
7480 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007481 S.Diag(CurInit.get()->getExprLoc(),
7482 diag::warn_cxx98_compat_initializer_list_init)
7483 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007484
Richard Smithcc1b96d2013-06-12 22:31:48 +00007485 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007486 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7487 CurInit.get()->getType(), CurInit.get(),
7488 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007489
Richard Smithcc1b96d2013-06-12 22:31:48 +00007490 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007491 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007492
Richard Smith0a9969b2018-07-17 00:11:41 +00007493 // Maybe lifetime-extend the array temporary's subobjects to match the
7494 // entity's lifetime.
7495 S.checkInitializerLifetime(Entity, CurInit.get());
7496
Richard Smithcc1b96d2013-06-12 22:31:48 +00007497 // Bind the result, in case the library has given initializer_list a
7498 // non-trivial destructor.
7499 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007500 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007501 break;
7502 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007503
Guy Benyei61054192013-02-07 10:55:47 +00007504 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007505 // Sampler initialzation have 5 cases:
7506 // 1. function argument passing
7507 // 1a. argument is a file-scope variable
7508 // 1b. argument is a function-scope variable
7509 // 1c. argument is one of caller function's parameters
7510 // 2. variable initialization
7511 // 2a. initializing a file-scope variable
7512 // 2b. initializing a function-scope variable
7513 //
7514 // For file-scope variables, since they cannot be initialized by function
7515 // call of __translate_sampler_initializer in LLVM IR, their references
7516 // need to be replaced by a cast from their literal initializers to
7517 // sampler type. Since sampler variables can only be used in function
7518 // calls as arguments, we only need to replace them when handling the
7519 // argument passing.
7520 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007521 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007522 Expr *Init = CurInit.get();
7523 QualType SourceType = Init->getType();
7524 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007525 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00007526 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00007527 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7528 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007529 break;
7530 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7531 auto Var = cast<VarDecl>(DRE->getDecl());
7532 // Case 1b and 1c
7533 // No cast from integer to sampler is needed.
7534 if (!Var->hasGlobalStorage()) {
7535 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7536 CK_LValueToRValue, Init,
7537 /*BasePath=*/nullptr, VK_RValue);
7538 break;
7539 }
7540 // Case 1a
7541 // For function call with a file-scope sampler variable as argument,
7542 // get the integer literal.
7543 // Do not diagnose if the file-scope variable does not have initializer
7544 // since this has already been diagnosed when parsing the variable
7545 // declaration.
7546 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7547 break;
7548 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7549 Var->getInit()))->getSubExpr();
7550 SourceType = Init->getType();
7551 }
7552 } else {
7553 // Case 2
7554 // Check initializer is 32 bit integer constant.
7555 // If the initializer is taken from global variable, do not diagnose since
7556 // this has already been done when parsing the variable declaration.
7557 if (!Init->isConstantInitializer(S.Context, false))
7558 break;
7559
7560 if (!SourceType->isIntegerType() ||
7561 32 != S.Context.getIntWidth(SourceType)) {
7562 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7563 << SourceType;
7564 break;
7565 }
7566
7567 llvm::APSInt Result;
7568 Init->EvaluateAsInt(Result, S.Context);
7569 const uint64_t SamplerValue = Result.getLimitedValue();
7570 // 32-bit value of sampler's initializer is interpreted as
7571 // bit-field with the following structure:
7572 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7573 // |31 6|5 4|3 1| 0|
7574 // This structure corresponds to enum values of sampler properties
7575 // defined in SPIR spec v1.2 and also opencl-c.h
7576 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7577 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7578 if (FilterMode != 1 && FilterMode != 2)
7579 S.Diag(Kind.getLocation(),
7580 diag::warn_sampler_initializer_invalid_bits)
7581 << "Filter Mode";
7582 if (AddressingMode > 4)
7583 S.Diag(Kind.getLocation(),
7584 diag::warn_sampler_initializer_invalid_bits)
7585 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00007586 }
7587
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007588 // Cases 1a, 2a and 2b
7589 // Insert cast from integer to sampler.
7590 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7591 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00007592 break;
7593 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007594 case SK_OCLZeroEvent: {
7595 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007596 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007597
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007598 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007599 CK_ZeroToOCLEvent,
7600 CurInit.get()->getValueKind());
7601 break;
7602 }
Egor Churaev89831422016-12-23 14:55:49 +00007603 case SK_OCLZeroQueue: {
7604 assert(Step->Type->isQueueT() &&
7605 "Event initialization on non queue type.");
7606
7607 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7608 CK_ZeroToOCLQueue,
7609 CurInit.get()->getValueKind());
7610 break;
7611 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007612 }
7613 }
John McCall1f425642010-11-11 03:21:53 +00007614
7615 // Diagnose non-fatal problems with the completed initialization.
7616 if (Entity.getKind() == InitializedEntity::EK_Member &&
7617 cast<FieldDecl>(Entity.getDecl())->isBitField())
7618 S.CheckBitFieldInitialization(Kind.getLocation(),
7619 cast<FieldDecl>(Entity.getDecl()),
7620 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007621
Richard Trieuac3eca52015-04-29 01:52:17 +00007622 // Check for std::move on construction.
7623 if (const Expr *E = CurInit.get()) {
7624 CheckMoveOnConstruction(S, E,
7625 Entity.getKind() == InitializedEntity::EK_Result);
7626 }
7627
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007628 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007629}
7630
Richard Smith593f9932012-12-08 02:01:17 +00007631/// Somewhere within T there is an uninitialized reference subobject.
7632/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00007633static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7634 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00007635 if (T->isReferenceType()) {
7636 S.Diag(Loc, diag::err_reference_without_init)
7637 << T.getNonReferenceType();
7638 return true;
7639 }
7640
7641 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7642 if (!RD || !RD->hasUninitializedReferenceMember())
7643 return false;
7644
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007645 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00007646 if (FI->isUnnamedBitfield())
7647 continue;
7648
7649 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7650 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7651 return true;
7652 }
7653 }
7654
Aaron Ballman574705e2014-03-13 15:41:46 +00007655 for (const auto &BI : RD->bases()) {
7656 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00007657 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7658 return true;
7659 }
7660 }
7661
7662 return false;
7663}
7664
7665
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007666//===----------------------------------------------------------------------===//
7667// Diagnose initialization failures
7668//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00007669
7670/// Emit notes associated with an initialization that failed due to a
7671/// "simple" conversion failure.
7672static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7673 Expr *op) {
7674 QualType destType = entity.getType();
7675 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7676 op->getType()->isObjCObjectPointerType()) {
7677
7678 // Emit a possible note about the conversion failing because the
7679 // operand is a message send with a related result type.
7680 S.EmitRelatedResultTypeNote(op);
7681
7682 // Emit a possible note about a return failing because we're
7683 // expecting a related result type.
7684 if (entity.getKind() == InitializedEntity::EK_Result)
7685 S.EmitRelatedResultTypeNoteForReturn(destType);
7686 }
7687}
7688
Richard Smith0449aaf2013-11-21 23:30:57 +00007689static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7690 InitListExpr *InitList) {
7691 QualType DestType = Entity.getType();
7692
7693 QualType E;
7694 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7695 QualType ArrayType = S.Context.getConstantArrayType(
7696 E.withConst(),
7697 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7698 InitList->getNumInits()),
7699 clang::ArrayType::Normal, 0);
7700 InitializedEntity HiddenArray =
7701 InitializedEntity::InitializeTemporary(ArrayType);
7702 return diagnoseListInit(S, HiddenArray, InitList);
7703 }
7704
Richard Smith8d082d12014-09-04 22:13:39 +00007705 if (DestType->isReferenceType()) {
7706 // A list-initialization failure for a reference means that we tried to
7707 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7708 // inner initialization failed.
7709 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7710 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7711 SourceLocation Loc = InitList->getLocStart();
7712 if (auto *D = Entity.getDecl())
7713 Loc = D->getLocation();
7714 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7715 return;
7716 }
7717
Richard Smith0449aaf2013-11-21 23:30:57 +00007718 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00007719 /*VerifyOnly=*/false,
7720 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00007721 assert(DiagnoseInitList.HadError() &&
7722 "Inconsistent init list check result.");
7723}
7724
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007725bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007726 const InitializedEntity &Entity,
7727 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007728 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007729 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007730 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007731
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007732 // When we want to diagnose only one element of a braced-init-list,
7733 // we need to factor it out.
7734 Expr *OnlyArg;
7735 if (Args.size() == 1) {
7736 auto *List = dyn_cast<InitListExpr>(Args[0]);
7737 if (List && List->getNumInits() == 1)
7738 OnlyArg = List->getInit(0);
7739 else
7740 OnlyArg = Args[0];
7741 }
7742 else
7743 OnlyArg = nullptr;
7744
Douglas Gregor1b303932009-12-22 15:35:07 +00007745 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007746 switch (Failure) {
7747 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007748 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007749 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00007750 // Dig out the reference subobject which is uninitialized and diagnose it.
7751 // If this is value-initialization, this could be nested some way within
7752 // the target type.
7753 assert(Kind.getKind() == InitializationKind::IK_Value ||
7754 DestType->isReferenceType());
7755 bool Diagnosed =
7756 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7757 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7758 (void)Diagnosed;
7759 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007760 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007761 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007762 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00007763 case FK_ParenthesizedListInitForReference:
7764 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7765 << 1 << Entity.getType() << Args[0]->getSourceRange();
7766 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007767
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007768 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007769 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007770 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007771 case FK_ArrayNeedsInitListOrStringLiteral:
7772 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7773 break;
7774 case FK_ArrayNeedsInitListOrWideStringLiteral:
7775 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7776 break;
7777 case FK_NarrowStringIntoWideCharArray:
7778 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7779 break;
7780 case FK_WideStringIntoCharArray:
7781 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7782 break;
7783 case FK_IncompatWideStringIntoWideChar:
7784 S.Diag(Kind.getLocation(),
7785 diag::err_array_init_incompat_wide_string_into_wchar);
7786 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00007787 case FK_PlainStringIntoUTF8Char:
7788 S.Diag(Kind.getLocation(),
7789 diag::err_array_init_plain_string_into_char8_t);
7790 S.Diag(Args.front()->getLocStart(),
7791 diag::note_array_init_plain_string_into_char8_t)
7792 << FixItHint::CreateInsertion(Args.front()->getLocStart(), "u8");
7793 break;
7794 case FK_UTF8StringIntoPlainChar:
7795 S.Diag(Kind.getLocation(),
7796 diag::err_array_init_utf8_string_into_char);
7797 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007798 case FK_ArrayTypeMismatch:
7799 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00007800 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00007801 (Failure == FK_ArrayTypeMismatch
7802 ? diag::err_array_init_different_type
7803 : diag::err_array_init_non_constant_array))
7804 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007805 << OnlyArg->getType()
Douglas Gregore2f943b2011-02-22 18:29:51 +00007806 << Args[0]->getSourceRange();
7807 break;
7808
John McCalla59dc2f2012-01-05 00:13:19 +00007809 case FK_VariableLengthArrayHasInitializer:
7810 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7811 << Args[0]->getSourceRange();
7812 break;
7813
John McCall16df1e52010-03-30 21:47:33 +00007814 case FK_AddressOfOverloadFailed: {
7815 DeclAccessPair Found;
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007816 S.ResolveAddressOfOverloadedFunction(OnlyArg,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007817 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00007818 true,
7819 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007820 break;
John McCall16df1e52010-03-30 21:47:33 +00007821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007822
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007823 case FK_AddressOfUnaddressableFunction: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007824 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007825 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007826 OnlyArg->getLocStart());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007827 break;
7828 }
7829
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007830 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00007831 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007832 switch (FailedOverloadResult) {
7833 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00007834 if (Failure == FK_UserConversionOverloadFailed)
7835 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007836 << OnlyArg->getType() << DestType
Douglas Gregore1314a62009-12-18 05:02:21 +00007837 << Args[0]->getSourceRange();
7838 else
7839 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007840 << DestType << OnlyArg->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00007841 << Args[0]->getSourceRange();
7842
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007843 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007844 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007845
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007846 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00007847 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007848 DestType.getNonReferenceType(),
7849 diag::err_typecheck_nonviable_condition_incomplete,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007850 OnlyArg->getType(), Args[0]->getSourceRange()))
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007851 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00007852 << (Entity.getKind() == InitializedEntity::EK_Result)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007853 << OnlyArg->getType() << Args[0]->getSourceRange()
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007854 << DestType.getNonReferenceType();
7855
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007856 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007857 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007858
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007859 case OR_Deleted: {
7860 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007861 << OnlyArg->getType() << DestType.getNonReferenceType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007862 << Args[0]->getSourceRange();
7863 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007864 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00007865 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007866 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00007867 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007868 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007869 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007870 }
7871 break;
7872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007873
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007874 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007875 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007876 }
7877 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007878
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007879 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00007880 if (isa<InitListExpr>(Args[0])) {
7881 S.Diag(Kind.getLocation(),
7882 diag::err_lvalue_reference_bind_to_initlist)
7883 << DestType.getNonReferenceType().isVolatileQualified()
7884 << DestType.getNonReferenceType()
7885 << Args[0]->getSourceRange();
7886 break;
7887 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007888 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00007889
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007890 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007891 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007892 Failure == FK_NonConstLValueReferenceBindingToTemporary
7893 ? diag::err_lvalue_reference_bind_to_temporary
7894 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00007895 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007896 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007897 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007898 << Args[0]->getSourceRange();
7899 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007900
Richard Smithb8c0f552016-12-09 18:49:13 +00007901 case FK_NonConstLValueReferenceBindingToBitfield: {
7902 // We don't necessarily have an unambiguous source bit-field.
7903 FieldDecl *BitField = Args[0]->getSourceBitField();
7904 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7905 << DestType.isVolatileQualified()
7906 << (BitField ? BitField->getDeclName() : DeclarationName())
7907 << (BitField != nullptr)
7908 << Args[0]->getSourceRange();
7909 if (BitField)
7910 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7911 break;
7912 }
7913
7914 case FK_NonConstLValueReferenceBindingToVectorElement:
7915 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7916 << DestType.isVolatileQualified()
7917 << Args[0]->getSourceRange();
7918 break;
7919
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007920 case FK_RValueReferenceBindingToLValue:
7921 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007922 << DestType.getNonReferenceType() << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007923 << Args[0]->getSourceRange();
7924 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007925
Richard Trieuf956a492015-05-16 01:27:03 +00007926 case FK_ReferenceInitDropsQualifiers: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007927 QualType SourceType = OnlyArg->getType();
Richard Trieuf956a492015-05-16 01:27:03 +00007928 QualType NonRefType = DestType.getNonReferenceType();
7929 Qualifiers DroppedQualifiers =
7930 SourceType.getQualifiers() - NonRefType.getQualifiers();
7931
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007932 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00007933 << SourceType
7934 << NonRefType
7935 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007936 << Args[0]->getSourceRange();
7937 break;
Richard Trieuf956a492015-05-16 01:27:03 +00007938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007939
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007940 case FK_ReferenceInitFailed:
7941 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7942 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007943 << OnlyArg->isLValue()
7944 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007945 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00007946 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007947 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007948
Douglas Gregorb491ed32011-02-19 21:32:49 +00007949 case FK_ConversionFailed: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007950 QualType FromType = OnlyArg->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00007951 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00007952 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007953 << DestType
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007954 << OnlyArg->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00007955 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007956 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00007957 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7958 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00007959 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00007960 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007961 }
John Wiegley01296292011-04-08 18:41:53 +00007962
7963 case FK_ConversionFromPropertyFailed:
7964 // No-op. This error has already been reported.
7965 break;
7966
Douglas Gregor51e77d52009-12-10 17:56:55 +00007967 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00007968 SourceRange R;
7969
David Majnemerbd385442015-04-10 04:52:06 +00007970 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007971 if (InitList && InitList->getNumInits() >= 1) {
David Majnemerbd385442015-04-10 04:52:06 +00007972 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007973 } else {
7974 assert(Args.size() > 1 && "Expected multiple initializers!");
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007975 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007976 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007977
Alp Tokerb6cc5922014-05-03 03:45:55 +00007978 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00007979 if (Kind.isCStyleOrFunctionalCast())
7980 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7981 << R;
7982 else
7983 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7984 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007985 break;
7986 }
7987
Richard Smith49a6b6e2017-03-24 01:14:25 +00007988 case FK_ParenthesizedListInitForScalar:
7989 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7990 << 0 << Entity.getType() << Args[0]->getSourceRange();
7991 break;
7992
Douglas Gregor51e77d52009-12-10 17:56:55 +00007993 case FK_ReferenceBindingToInitList:
7994 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7995 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7996 break;
7997
7998 case FK_InitListBadDestinationType:
7999 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8000 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8001 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008002
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008003 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008004 case FK_ConstructorOverloadFailed: {
8005 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008006 if (Args.size())
8007 ArgsRange = SourceRange(Args.front()->getLocStart(),
8008 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008009
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008010 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00008011 assert(Args.size() == 1 &&
8012 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008013 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008014 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008015 }
8016
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008017 // FIXME: Using "DestType" for the entity we're printing is probably
8018 // bad.
8019 switch (FailedOverloadResult) {
8020 case OR_Ambiguous:
8021 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
8022 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008023 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008024 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008026 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008027 if (Kind.getKind() == InitializationKind::IK_Default &&
8028 (Entity.getKind() == InitializedEntity::EK_Base ||
8029 Entity.getKind() == InitializedEntity::EK_Member) &&
8030 isa<CXXConstructorDecl>(S.CurContext)) {
8031 // This is implicit default initialization of a member or
8032 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00008033 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008034 // initialize this base/member.
8035 CXXConstructorDecl *Constructor
8036 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00008037 const CXXRecordDecl *InheritedFrom = nullptr;
8038 if (auto Inherited = Constructor->getInheritedConstructor())
8039 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008040 if (Entity.getKind() == InitializedEntity::EK_Base) {
8041 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008042 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008043 << S.Context.getTypeDeclType(Constructor->getParent())
8044 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00008045 << Entity.getType()
8046 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008047
8048 RecordDecl *BaseDecl
8049 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
8050 ->getDecl();
8051 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8052 << S.Context.getTagDeclType(BaseDecl);
8053 } else {
8054 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008055 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008056 << S.Context.getTypeDeclType(Constructor->getParent())
8057 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00008058 << Entity.getName()
8059 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00008060 S.Diag(Entity.getDecl()->getLocation(),
8061 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008062
8063 if (const RecordType *Record
8064 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008065 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008066 diag::note_previous_decl)
8067 << S.Context.getTagDeclType(Record->getDecl());
8068 }
8069 break;
8070 }
8071
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008072 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
8073 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008074 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008075 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008076
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008077 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008078 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008079 OverloadingResult Ovl
8080 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00008081 if (Ovl != OR_Deleted) {
8082 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8083 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008084 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00008085 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008086 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00008087
8088 // If this is a defaulted or implicitly-declared function, then
8089 // it was implicitly deleted. Make it clear that the deletion was
8090 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00008091 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008092 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00008093 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008094 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00008095 else
8096 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8097 << true << DestType << ArgsRange;
8098
8099 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008100 break;
8101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008102
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008103 case OR_Success:
8104 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008105 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008106 }
David Blaikie60deeee2012-01-17 08:24:58 +00008107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008108
Douglas Gregor85dabae2009-12-16 01:38:02 +00008109 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008110 if (Entity.getKind() == InitializedEntity::EK_Member &&
8111 isa<CXXConstructorDecl>(S.CurContext)) {
8112 // This is implicit default-initialization of a const member in
8113 // a constructor. Complain that it needs to be explicitly
8114 // initialized.
8115 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
8116 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00008117 << (Constructor->getInheritedConstructor() ? 2 :
8118 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008119 << S.Context.getTypeDeclType(Constructor->getParent())
8120 << /*const=*/1
8121 << Entity.getName();
8122 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
8123 << Entity.getName();
8124 } else {
8125 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00008126 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008127 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00008128 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008129
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008130 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00008131 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008132 diag::err_init_incomplete_type);
8133 break;
8134
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008135 case FK_ListInitializationFailed: {
8136 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00008137 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8138 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008139 break;
8140 }
John McCall4124c492011-10-17 18:40:02 +00008141
8142 case FK_PlaceholderType: {
8143 // FIXME: Already diagnosed!
8144 break;
8145 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00008146
Sebastian Redl048a6d72012-04-01 19:54:59 +00008147 case FK_ExplicitConstructor: {
8148 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
8149 << Args[0]->getSourceRange();
8150 OverloadCandidateSet::iterator Best;
8151 OverloadingResult Ovl
8152 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00008153 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008154 assert(Ovl == OR_Success && "Inconsistent overload resolution");
8155 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00008156 S.Diag(CtorDecl->getLocation(),
8157 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008158 break;
8159 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008161
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008162 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008163 return true;
8164}
Douglas Gregore1314a62009-12-18 05:02:21 +00008165
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008166void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008167 switch (SequenceKind) {
8168 case FailedSequence: {
8169 OS << "Failed sequence: ";
8170 switch (Failure) {
8171 case FK_TooManyInitsForReference:
8172 OS << "too many initializers for reference";
8173 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008174
Richard Smith49a6b6e2017-03-24 01:14:25 +00008175 case FK_ParenthesizedListInitForReference:
8176 OS << "parenthesized list init for reference";
8177 break;
8178
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008179 case FK_ArrayNeedsInitList:
8180 OS << "array requires initializer list";
8181 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008182
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008183 case FK_AddressOfUnaddressableFunction:
8184 OS << "address of unaddressable function was taken";
8185 break;
8186
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008187 case FK_ArrayNeedsInitListOrStringLiteral:
8188 OS << "array requires initializer list or string literal";
8189 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008190
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008191 case FK_ArrayNeedsInitListOrWideStringLiteral:
8192 OS << "array requires initializer list or wide string literal";
8193 break;
8194
8195 case FK_NarrowStringIntoWideCharArray:
8196 OS << "narrow string into wide char array";
8197 break;
8198
8199 case FK_WideStringIntoCharArray:
8200 OS << "wide string into char array";
8201 break;
8202
8203 case FK_IncompatWideStringIntoWideChar:
8204 OS << "incompatible wide string into wide char array";
8205 break;
8206
Richard Smith3a8244d2018-05-01 05:02:45 +00008207 case FK_PlainStringIntoUTF8Char:
8208 OS << "plain string literal into char8_t array";
8209 break;
8210
8211 case FK_UTF8StringIntoPlainChar:
8212 OS << "u8 string literal into char array";
8213 break;
8214
Douglas Gregore2f943b2011-02-22 18:29:51 +00008215 case FK_ArrayTypeMismatch:
8216 OS << "array type mismatch";
8217 break;
8218
8219 case FK_NonConstantArrayInit:
8220 OS << "non-constant array initializer";
8221 break;
8222
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008223 case FK_AddressOfOverloadFailed:
8224 OS << "address of overloaded function failed";
8225 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008226
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008227 case FK_ReferenceInitOverloadFailed:
8228 OS << "overload resolution for reference initialization failed";
8229 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008230
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008231 case FK_NonConstLValueReferenceBindingToTemporary:
8232 OS << "non-const lvalue reference bound to temporary";
8233 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008234
Richard Smithb8c0f552016-12-09 18:49:13 +00008235 case FK_NonConstLValueReferenceBindingToBitfield:
8236 OS << "non-const lvalue reference bound to bit-field";
8237 break;
8238
8239 case FK_NonConstLValueReferenceBindingToVectorElement:
8240 OS << "non-const lvalue reference bound to vector element";
8241 break;
8242
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008243 case FK_NonConstLValueReferenceBindingToUnrelated:
8244 OS << "non-const lvalue reference bound to unrelated type";
8245 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008246
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008247 case FK_RValueReferenceBindingToLValue:
8248 OS << "rvalue reference bound to an lvalue";
8249 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008250
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008251 case FK_ReferenceInitDropsQualifiers:
8252 OS << "reference initialization drops qualifiers";
8253 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008254
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008255 case FK_ReferenceInitFailed:
8256 OS << "reference initialization failed";
8257 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008258
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008259 case FK_ConversionFailed:
8260 OS << "conversion failed";
8261 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008262
John Wiegley01296292011-04-08 18:41:53 +00008263 case FK_ConversionFromPropertyFailed:
8264 OS << "conversion from property failed";
8265 break;
8266
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008267 case FK_TooManyInitsForScalar:
8268 OS << "too many initializers for scalar";
8269 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008270
Richard Smith49a6b6e2017-03-24 01:14:25 +00008271 case FK_ParenthesizedListInitForScalar:
8272 OS << "parenthesized list init for reference";
8273 break;
8274
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008275 case FK_ReferenceBindingToInitList:
8276 OS << "referencing binding to initializer list";
8277 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008278
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008279 case FK_InitListBadDestinationType:
8280 OS << "initializer list for non-aggregate, non-scalar type";
8281 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008282
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008283 case FK_UserConversionOverloadFailed:
8284 OS << "overloading failed for user-defined conversion";
8285 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008286
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008287 case FK_ConstructorOverloadFailed:
8288 OS << "constructor overloading failed";
8289 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008290
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008291 case FK_DefaultInitOfConst:
8292 OS << "default initialization of a const variable";
8293 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008294
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00008295 case FK_Incomplete:
8296 OS << "initialization of incomplete type";
8297 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008298
8299 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008300 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00008301 break;
8302
John McCalla59dc2f2012-01-05 00:13:19 +00008303 case FK_VariableLengthArrayHasInitializer:
8304 OS << "variable length array has an initializer";
8305 break;
8306
John McCall4124c492011-10-17 18:40:02 +00008307 case FK_PlaceholderType:
8308 OS << "initializer expression isn't contextually valid";
8309 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00008310
8311 case FK_ListConstructorOverloadFailed:
8312 OS << "list constructor overloading failed";
8313 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008314
Sebastian Redl048a6d72012-04-01 19:54:59 +00008315 case FK_ExplicitConstructor:
8316 OS << "list copy initialization chose explicit constructor";
8317 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008318 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008319 OS << '\n';
8320 return;
8321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008322
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008323 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00008324 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008325 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008326
Sebastian Redld201edf2011-06-05 13:59:11 +00008327 case NormalSequence:
8328 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008329 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008331
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008332 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8333 if (S != step_begin()) {
8334 OS << " -> ";
8335 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008336
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008337 switch (S->Kind) {
8338 case SK_ResolveAddressOfOverloadedFunction:
8339 OS << "resolve address of overloaded function";
8340 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008341
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008342 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008343 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008344 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008345
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008346 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008347 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008348 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008349
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008350 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008351 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008352 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008353
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008354 case SK_BindReference:
8355 OS << "bind reference to lvalue";
8356 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008357
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008358 case SK_BindReferenceToTemporary:
8359 OS << "bind reference to a temporary";
8360 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008361
Richard Smithb8c0f552016-12-09 18:49:13 +00008362 case SK_FinalCopy:
8363 OS << "final copy in class direct-initialization";
8364 break;
8365
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008366 case SK_ExtraneousCopyToTemporary:
8367 OS << "extraneous C++03 copy to temporary";
8368 break;
8369
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008370 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008371 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008372 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008373
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008374 case SK_QualificationConversionRValue:
8375 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008376 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008377
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008378 case SK_QualificationConversionXValue:
8379 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008380 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008381
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008382 case SK_QualificationConversionLValue:
8383 OS << "qualification conversion (lvalue)";
8384 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008385
Richard Smith77be48a2014-07-31 06:31:19 +00008386 case SK_AtomicConversion:
8387 OS << "non-atomic-to-atomic conversion";
8388 break;
8389
Jordan Roseb1312a52013-04-11 00:58:58 +00008390 case SK_LValueToRValue:
8391 OS << "load (lvalue to rvalue)";
8392 break;
8393
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008394 case SK_ConversionSequence:
8395 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008396 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008397 OS << ")";
8398 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008399
Richard Smithaaa0ec42013-09-21 21:19:19 +00008400 case SK_ConversionSequenceNoNarrowing:
8401 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008402 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008403 OS << ")";
8404 break;
8405
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008406 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008407 OS << "list aggregate initialization";
8408 break;
8409
Sebastian Redl29526f02011-11-27 16:50:07 +00008410 case SK_UnwrapInitList:
8411 OS << "unwrap reference initializer list";
8412 break;
8413
8414 case SK_RewrapInitList:
8415 OS << "rewrap reference initializer list";
8416 break;
8417
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008418 case SK_ConstructorInitialization:
8419 OS << "constructor initialization";
8420 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008421
Richard Smith53324112014-07-16 21:33:43 +00008422 case SK_ConstructorInitializationFromList:
8423 OS << "list initialization via constructor";
8424 break;
8425
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008426 case SK_ZeroInitialization:
8427 OS << "zero initialization";
8428 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008429
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008430 case SK_CAssignment:
8431 OS << "C assignment";
8432 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008433
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008434 case SK_StringInit:
8435 OS << "string initialization";
8436 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008437
8438 case SK_ObjCObjectConversion:
8439 OS << "Objective-C object conversion";
8440 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008441
Richard Smith410306b2016-12-12 02:53:20 +00008442 case SK_ArrayLoopIndex:
8443 OS << "indexing for array initialization loop";
8444 break;
8445
8446 case SK_ArrayLoopInit:
8447 OS << "array initialization loop";
8448 break;
8449
Douglas Gregore2f943b2011-02-22 18:29:51 +00008450 case SK_ArrayInit:
8451 OS << "array initialization";
8452 break;
John McCall31168b02011-06-15 23:02:42 +00008453
Richard Smith378b8c82016-12-14 03:22:16 +00008454 case SK_GNUArrayInit:
8455 OS << "array initialization (GNU extension)";
8456 break;
8457
Richard Smithebeed412012-02-15 22:38:09 +00008458 case SK_ParenthesizedArrayInit:
8459 OS << "parenthesized array initialization";
8460 break;
8461
John McCall31168b02011-06-15 23:02:42 +00008462 case SK_PassByIndirectCopyRestore:
8463 OS << "pass by indirect copy and restore";
8464 break;
8465
8466 case SK_PassByIndirectRestore:
8467 OS << "pass by indirect restore";
8468 break;
8469
8470 case SK_ProduceObjCObject:
8471 OS << "Objective-C object retension";
8472 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008473
8474 case SK_StdInitializerList:
8475 OS << "std::initializer_list from initializer list";
8476 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008477
Richard Smithf8adcdc2014-07-17 05:12:35 +00008478 case SK_StdInitializerListConstructorCall:
8479 OS << "list initialization from std::initializer_list";
8480 break;
8481
Guy Benyei61054192013-02-07 10:55:47 +00008482 case SK_OCLSamplerInit:
8483 OS << "OpenCL sampler_t from integer constant";
8484 break;
8485
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008486 case SK_OCLZeroEvent:
8487 OS << "OpenCL event_t from zero";
8488 break;
Egor Churaev89831422016-12-23 14:55:49 +00008489
8490 case SK_OCLZeroQueue:
8491 OS << "OpenCL queue_t from zero";
8492 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008493 }
Richard Smith6b216962013-02-05 05:52:24 +00008494
8495 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008496 }
Richard Smith6b216962013-02-05 05:52:24 +00008497
8498 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008499}
8500
8501void InitializationSequence::dump() const {
8502 dump(llvm::errs());
8503}
8504
Nico Weber3d7f00d2018-06-19 23:19:34 +00008505static bool NarrowingErrs(const LangOptions &L) {
8506 return L.CPlusPlus11 &&
8507 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
8508}
8509
Richard Smithaaa0ec42013-09-21 21:19:19 +00008510static void DiagnoseNarrowingInInitList(Sema &S,
8511 const ImplicitConversionSequence &ICS,
8512 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008513 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008514 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008515 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008516 switch (ICS.getKind()) {
8517 case ImplicitConversionSequence::StandardConversion:
8518 SCS = &ICS.Standard;
8519 break;
8520 case ImplicitConversionSequence::UserDefinedConversion:
8521 SCS = &ICS.UserDefined.After;
8522 break;
8523 case ImplicitConversionSequence::AmbiguousConversion:
8524 case ImplicitConversionSequence::EllipsisConversion:
8525 case ImplicitConversionSequence::BadConversion:
8526 return;
8527 }
8528
Richard Smith66e05fe2012-01-18 05:21:49 +00008529 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8530 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00008531 QualType ConstantType;
8532 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8533 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00008534 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00008535 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00008536 // No narrowing occurred.
8537 return;
8538
8539 case NK_Type_Narrowing:
8540 // This was a floating-to-integer conversion, which is always considered a
8541 // narrowing conversion even if the value is a constant and can be
8542 // represented exactly as an integer.
Nico Weber3d7f00d2018-06-19 23:19:34 +00008543 S.Diag(PostInit->getLocStart(), NarrowingErrs(S.getLangOpts())
8544 ? diag::ext_init_list_type_narrowing
8545 : diag::warn_init_list_type_narrowing)
8546 << PostInit->getSourceRange()
8547 << PreNarrowingType.getLocalUnqualifiedType()
8548 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008549 break;
8550
8551 case NK_Constant_Narrowing:
8552 // A constant value was narrowed.
8553 S.Diag(PostInit->getLocStart(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00008554 NarrowingErrs(S.getLangOpts())
8555 ? diag::ext_init_list_constant_narrowing
8556 : diag::warn_init_list_constant_narrowing)
8557 << PostInit->getSourceRange()
8558 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
8559 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008560 break;
8561
8562 case NK_Variable_Narrowing:
8563 // A variable's value may have been narrowed.
8564 S.Diag(PostInit->getLocStart(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00008565 NarrowingErrs(S.getLangOpts())
8566 ? diag::ext_init_list_variable_narrowing
8567 : diag::warn_init_list_variable_narrowing)
8568 << PostInit->getSourceRange()
8569 << PreNarrowingType.getLocalUnqualifiedType()
8570 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008571 break;
8572 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008573
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008574 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008575 llvm::raw_svector_ostream OS(StaticCast);
8576 OS << "static_cast<";
8577 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8578 // It's important to use the typedef's name if there is one so that the
8579 // fixit doesn't break code using types like int64_t.
8580 //
8581 // FIXME: This will break if the typedef requires qualification. But
8582 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008583 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008584 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00008585 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008586 else {
8587 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8588 // with a broken cast.
8589 return;
8590 }
8591 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00008592 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008593 << PostInit->getSourceRange()
8594 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8595 << FixItHint::CreateInsertion(
8596 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008597}
8598
Douglas Gregore1314a62009-12-18 05:02:21 +00008599//===----------------------------------------------------------------------===//
8600// Initialization helper functions
8601//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00008602bool
8603Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8604 ExprResult Init) {
8605 if (Init.isInvalid())
8606 return false;
8607
8608 Expr *InitE = Init.get();
8609 assert(InitE && "No initialization expression");
8610
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00008611 InitializationKind Kind
8612 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008613 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00008614 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00008615}
8616
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008617ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00008618Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8619 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008620 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00008621 bool TopLevelOfInitList,
8622 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00008623 if (Init.isInvalid())
8624 return ExprError();
8625
John McCall1f425642010-11-11 03:21:53 +00008626 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00008627 assert(InitE && "No initialization expression?");
8628
8629 if (EqualLoc.isInvalid())
8630 EqualLoc = InitE->getLocStart();
8631
8632 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00008633 EqualLoc,
8634 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00008635 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008636
Alex Lorenzde69ff92017-05-16 10:23:58 +00008637 // Prevent infinite recursion when performing parameter copy-initialization.
8638 const bool ShouldTrackCopy =
8639 Entity.isParameterKind() && Seq.isConstructorInitialization();
8640 if (ShouldTrackCopy) {
8641 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
8642 CurrentParameterCopyTypes.end()) {
8643 Seq.SetOverloadFailure(
8644 InitializationSequence::FK_ConstructorOverloadFailed,
8645 OR_No_Viable_Function);
8646
8647 // Try to give a meaningful diagnostic note for the problematic
8648 // constructor.
8649 const auto LastStep = Seq.step_end() - 1;
8650 assert(LastStep->Kind ==
8651 InitializationSequence::SK_ConstructorInitialization);
8652 const FunctionDecl *Function = LastStep->Function.Function;
8653 auto Candidate =
8654 llvm::find_if(Seq.getFailedCandidateSet(),
8655 [Function](const OverloadCandidate &Candidate) -> bool {
8656 return Candidate.Viable &&
8657 Candidate.Function == Function &&
8658 Candidate.Conversions.size() > 0;
8659 });
8660 if (Candidate != Seq.getFailedCandidateSet().end() &&
8661 Function->getNumParams() > 0) {
8662 Candidate->Viable = false;
8663 Candidate->FailureKind = ovl_fail_bad_conversion;
8664 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
8665 InitE,
8666 Function->getParamDecl(0)->getType());
8667 }
8668 }
8669 CurrentParameterCopyTypes.push_back(Entity.getType());
8670 }
8671
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008672 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00008673
Alex Lorenzde69ff92017-05-16 10:23:58 +00008674 if (ShouldTrackCopy)
8675 CurrentParameterCopyTypes.pop_back();
8676
Richard Smith66e05fe2012-01-18 05:21:49 +00008677 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00008678}
Richard Smith60437622017-02-09 19:17:44 +00008679
Richard Smith1363e8f2017-09-07 07:22:36 +00008680/// Determine whether RD is, or is derived from, a specialization of CTD.
8681static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
8682 ClassTemplateDecl *CTD) {
8683 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
8684 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
8685 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
8686 };
8687 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
8688}
8689
Richard Smith60437622017-02-09 19:17:44 +00008690QualType Sema::DeduceTemplateSpecializationFromInitializer(
8691 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8692 const InitializationKind &Kind, MultiExprArg Inits) {
8693 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8694 TSInfo->getType()->getContainedDeducedType());
8695 assert(DeducedTST && "not a deduced template specialization type");
8696
8697 // We can only perform deduction for class templates.
8698 auto TemplateName = DeducedTST->getTemplateName();
8699 auto *Template =
8700 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8701 if (!Template) {
8702 Diag(Kind.getLocation(),
8703 diag::err_deduced_non_class_template_specialization_type)
8704 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8705 if (auto *TD = TemplateName.getAsTemplateDecl())
8706 Diag(TD->getLocation(), diag::note_template_decl_here);
8707 return QualType();
8708 }
8709
Richard Smith32918772017-02-14 00:25:28 +00008710 // Can't deduce from dependent arguments.
8711 if (Expr::hasAnyTypeDependentArguments(Inits))
8712 return Context.DependentTy;
8713
Richard Smith60437622017-02-09 19:17:44 +00008714 // FIXME: Perform "exact type" matching first, per CWG discussion?
8715 // Or implement this via an implied 'T(T) -> T' deduction guide?
8716
8717 // FIXME: Do we need/want a std::initializer_list<T> special case?
8718
Richard Smith32918772017-02-14 00:25:28 +00008719 // Look up deduction guides, including those synthesized from constructors.
8720 //
Richard Smith60437622017-02-09 19:17:44 +00008721 // C++1z [over.match.class.deduct]p1:
8722 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00008723 // - For each constructor of the class template designated by the
8724 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00008725 // - For each deduction-guide, a function or function template [...]
8726 DeclarationNameInfo NameInfo(
8727 Context.DeclarationNames.getCXXDeductionGuideName(Template),
8728 TSInfo->getTypeLoc().getEndLoc());
8729 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
8730 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00008731
8732 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
8733 // clear on this, but they're not found by name so access does not apply.
8734 Guides.suppressDiagnostics();
8735
8736 // Figure out if this is list-initialization.
8737 InitListExpr *ListInit =
8738 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
8739 ? dyn_cast<InitListExpr>(Inits[0])
8740 : nullptr;
8741
8742 // C++1z [over.match.class.deduct]p1:
8743 // Initialization and overload resolution are performed as described in
8744 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
8745 // (as appropriate for the type of initialization performed) for an object
8746 // of a hypothetical class type, where the selected functions and function
8747 // templates are considered to be the constructors of that class type
8748 //
8749 // Since we know we're initializing a class type of a type unrelated to that
8750 // of the initializer, this reduces to something fairly reasonable.
8751 OverloadCandidateSet Candidates(Kind.getLocation(),
8752 OverloadCandidateSet::CSK_Normal);
8753 OverloadCandidateSet::iterator Best;
8754 auto tryToResolveOverload =
8755 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00008756 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Richard Smith32918772017-02-14 00:25:28 +00008757 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
8758 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00008759 if (D->isInvalidDecl())
8760 continue;
8761
Richard Smithbc491202017-02-17 20:05:37 +00008762 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
8763 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
8764 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
8765 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00008766 continue;
8767
8768 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
8769 // For copy-initialization, the candidate functions are all the
8770 // converting constructors (12.3.1) of that class.
8771 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
8772 // The converting constructors of T are candidate functions.
8773 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00008774 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00008775 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00008776 continue;
Richard Smith60437622017-02-09 19:17:44 +00008777
8778 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00008779 // could never be called with one argument are not interesting to
8780 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00008781 if (GD->getMinRequiredArguments() > 1 ||
8782 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00008783 continue;
8784 }
8785
8786 // C++ [over.match.list]p1.1: (first phase list initialization)
8787 // Initially, the candidate functions are the initializer-list
8788 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00008789 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00008790 continue;
8791
8792 // C++ [over.match.list]p1.2: (second phase list initialization)
8793 // the candidate functions are all the constructors of the class T
8794 // C++ [over.match.ctor]p1: (all other cases)
8795 // the candidate functions are all the constructors of the class of
8796 // the object being initialized
8797
8798 // C++ [over.best.ics]p4:
8799 // When [...] the constructor [...] is a candidate by
8800 // - [over.match.copy] (in all cases)
8801 // FIXME: The "second phase of [over.match.list] case can also
8802 // theoretically happen here, but it's not clear whether we can
8803 // ever have a parameter of the right type.
8804 bool SuppressUserConversions = Kind.isCopyInit();
8805
Richard Smith60437622017-02-09 19:17:44 +00008806 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00008807 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
8808 Inits, Candidates,
8809 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00008810 else
Richard Smithbc491202017-02-17 20:05:37 +00008811 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00008812 SuppressUserConversions);
8813 }
8814 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
8815 };
8816
8817 OverloadingResult Result = OR_No_Viable_Function;
8818
8819 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
8820 // try initializer-list constructors.
8821 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00008822 bool TryListConstructors = true;
8823
8824 // Try list constructors unless the list is empty and the class has one or
8825 // more default constructors, in which case those constructors win.
8826 if (!ListInit->getNumInits()) {
8827 for (NamedDecl *D : Guides) {
8828 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
8829 if (FD && FD->getMinRequiredArguments() == 0) {
8830 TryListConstructors = false;
8831 break;
8832 }
8833 }
Richard Smith1363e8f2017-09-07 07:22:36 +00008834 } else if (ListInit->getNumInits() == 1) {
8835 // C++ [over.match.class.deduct]:
8836 // As an exception, the first phase in [over.match.list] (considering
8837 // initializer-list constructors) is omitted if the initializer list
8838 // consists of a single expression of type cv U, where U is a
8839 // specialization of C or a class derived from a specialization of C.
8840 Expr *E = ListInit->getInit(0);
8841 auto *RD = E->getType()->getAsCXXRecordDecl();
8842 if (!isa<InitListExpr>(E) && RD &&
8843 isOrIsDerivedFromSpecializationOf(RD, Template))
8844 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00008845 }
8846
8847 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00008848 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
8849 // Then unwrap the initializer list and try again considering all
8850 // constructors.
8851 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
8852 }
8853
8854 // If list-initialization fails, or if we're doing any other kind of
8855 // initialization, we (eventually) consider constructors.
8856 if (Result == OR_No_Viable_Function)
8857 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
8858
8859 switch (Result) {
8860 case OR_Ambiguous:
8861 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
8862 << TemplateName;
8863 // FIXME: For list-initialization candidates, it'd usually be better to
8864 // list why they were not viable when given the initializer list itself as
8865 // an argument.
8866 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
8867 return QualType();
8868
Richard Smith32918772017-02-14 00:25:28 +00008869 case OR_No_Viable_Function: {
8870 CXXRecordDecl *Primary =
8871 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
8872 bool Complete =
8873 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00008874 Diag(Kind.getLocation(),
8875 Complete ? diag::err_deduced_class_template_ctor_no_viable
8876 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00008877 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00008878 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
8879 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00008880 }
Richard Smith60437622017-02-09 19:17:44 +00008881
8882 case OR_Deleted: {
8883 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
8884 << TemplateName;
8885 NoteDeletedFunction(Best->Function);
8886 return QualType();
8887 }
8888
8889 case OR_Success:
8890 // C++ [over.match.list]p1:
8891 // In copy-list-initialization, if an explicit constructor is chosen, the
8892 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00008893 if (Kind.isCopyInit() && ListInit &&
8894 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00008895 bool IsDeductionGuide = !Best->Function->isImplicit();
8896 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
8897 << TemplateName << IsDeductionGuide;
8898 Diag(Best->Function->getLocation(),
8899 diag::note_explicit_ctor_deduction_guide_here)
8900 << IsDeductionGuide;
8901 return QualType();
8902 }
8903
8904 // Make sure we didn't select an unusable deduction guide, and mark it
8905 // as referenced.
8906 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
8907 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
8908 break;
8909 }
8910
8911 // C++ [dcl.type.class.deduct]p1:
8912 // The placeholder is replaced by the return type of the function selected
8913 // by overload resolution for class template deduction.
8914 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
8915}